import {randomUUID} from 'node:crypto'; import {existsSync,lstatSync,mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync} from 'node:fs'; import {dirname} from 'node:path'; import {graphModelSettingsLocations} from './settings.ts'; export interface CustomGraphModel {provider:string;id:string;name:string;api:string;baseUrl:string;input:('text'|'image')[];contextWindow:number;maxTokens:number;reasoning:boolean;cost:{input:number;output:number;cacheRead:number;cacheWrite:number};auth:{type:'env';variable:string}|{type:'pi';provider:string};source?:'global'|'project';} const APIS=['openai-completions','openai-responses','anthropic-messages','google-generative-ai','google-vertex','bedrock-converse-stream','azure-openai-responses']; function validId(v:unknown,label:string):asserts v is string {if(typeof v!=='string'||!v.trim()||/\s|[\\\u0000-\u001f]/u.test(v))throw new Error(`Invalid custom model ${label}.`);} export function validateCustomGraphModel(value:unknown):CustomGraphModel {if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Custom model must be an object.');const m=value as CustomGraphModel;for(const k of Object.keys(m))if(!['provider','id','name','api','baseUrl','input','contextWindow','maxTokens','reasoning','cost','auth','source'].includes(k))throw new Error(`Unknown custom model field: ${k}`);validId(m.provider,'provider');validId(m.id,'id');if(m.provider.includes('/')||!/^graph-[a-z0-9][a-z0-9._-]*$/u.test(m.provider))throw new Error('Custom provider names must start with graph- to avoid replacing existing Pi providers.');if(typeof m.name!=='string'||!m.name.trim())throw new Error('Custom model requires a display name.');if(!APIS.includes(m.api))throw new Error(`Unsupported model API '${m.api}'.`);const url=new URL(m.baseUrl);if(!['http:','https:'].includes(url.protocol)||url.username||url.password||url.search||url.hash)throw new Error('baseUrl must be an HTTP(S) endpoint without embedded credentials, query or fragment.');if(!Array.isArray(m.input)||!m.input.length||m.input.some(v=>!['text','image'].includes(v))||new Set(m.input).size!==m.input.length)throw new Error('Model input must list text and/or image.');for(const k of ['contextWindow','maxTokens'] as const)if(!Number.isSafeInteger(m[k])||m[k]<=0)throw new Error(`Invalid ${k}.`);if(m.maxTokens>m.contextWindow)throw new Error('maxTokens cannot exceed contextWindow.');if(typeof m.reasoning!=='boolean')throw new Error('Model reasoning must be boolean.');if(!m.cost||Object.keys(m.cost).some(k=>!['input','output','cacheRead','cacheWrite'].includes(k)))throw new Error('Model cost must contain input/output/cacheRead/cacheWrite.');for(const k of ['input','output','cacheRead','cacheWrite'] as const)if(typeof m.cost[k]!=='number'||!Number.isFinite(m.cost[k])||m.cost[k]<0)throw new Error(`Invalid model cost.${k}.`);if(!m.auth||typeof m.auth!=='object'||Array.isArray(m.auth))throw new Error('Model auth must reference env or existing Pi credentials.');if(m.auth.type==='env'){if(Object.keys(m.auth).some(k=>!['type','variable'].includes(k))||! /^[A-Za-z_][A-Za-z0-9_]*$/u.test(m.auth.variable))throw new Error('Env auth requires only an environment variable name.');}else if(m.auth.type==='pi'){if(Object.keys(m.auth).some(k=>!['type','provider'].includes(k)))throw new Error('Pi auth accepts only a provider reference.');validId(m.auth.provider,'credential provider');if(['kimi-coding','xai'].includes(m.auth.provider))throw new Error('Official subscription credentials cannot be forwarded to a custom provider.');}else throw new Error('Plaintext/API-key auth is prohibited; use env or Pi credential references.');return {...m,input:[...m.input],cost:{...m.cost},auth:{...m.auth}};} function readDocument(path:string):any { if(!existsSync(path))return {version:1,roles:{},profiles:{},models:{}}; const fail=(field:string,message:string):never=>{throw new Error(`Invalid model configuration '${path}' (${field}): ${message}`);}; if(lstatSync(path).isSymbolicLink())fail('file','symbolic links are not accepted'); let d:any;try{d=JSON.parse(readFileSync(path,'utf8'));}catch{fail('JSON','invalid JSON syntax or unreadable file');} if(!d||typeof d!=='object'||Array.isArray(d))fail('root','expected an object'); for(const field of Object.keys(d))if(!['version','roles','profiles','models'].includes(field))fail(field,'unknown top-level field'); if(d.version!==1)fail('version','expected 1'); for(const kind of ['roles','profiles'])if(!d[kind]||typeof d[kind]!=='object'||Array.isArray(d[kind]))fail(kind,'expected an object'); if(d.models!==undefined){if(!d.models||typeof d.models!=='object'||Array.isArray(d.models))fail('models','expected an object');for(const [identity,value]of Object.entries(d.models)){try{const m=validateCustomGraphModel(value);if(identity!==`${m.provider}/${m.id}`)throw new Error('identity key does not match provider/id');}catch(e){fail(`models.${identity}`,e instanceof Error?e.message:'invalid model definition');}}} return d; } export function readCustomGraphModels(cwd:string,agentDir?:string):CustomGraphModel[] {const locations=graphModelSettingsLocations(cwd,agentDir),map=new Map();for(const source of ['global','project'] as const){const d=readDocument(locations[source]);if(d.models!==undefined&&(!d.models||typeof d.models!=='object'||Array.isArray(d.models)))throw new Error('models must be an object keyed by provider/model.');for(const [key,v]of Object.entries(d.models??{})){const m=validateCustomGraphModel(v);if(key!==`${m.provider}/${m.id}`)throw new Error('Custom model key does not match its identity.');map.set(key,{...m,source});}}return [...map.values()];} function save(path:string,value:unknown){const dir=dirname(path);for(const p of [path,dir,dirname(dir)])if(existsSync(p)&&lstatSync(p).isSymbolicLink())throw new Error('Refusing symbolic-link model config target.');mkdirSync(dir,{recursive:true});const temp=`${path}.${randomUUID()}.tmp`;try{writeFileSync(temp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});renameSync(temp,path);}finally{if(existsSync(temp))unlinkSync(temp);}} export function setCustomGraphModel(input:{cwd:string;scope:'global'|'project';value:CustomGraphModel;agentDir?:string}) {if(!['global','project'].includes(input.scope))throw new Error('Invalid scope.');const m=validateCustomGraphModel(input.value);delete m.source;const path=graphModelSettingsLocations(input.cwd,input.agentDir)[input.scope],d=readDocument(path);d.models??={};d.models[`${m.provider}/${m.id}`]=m;save(path,d);return {path,model:`${m.provider}/${m.id}`};} export function deleteCustomGraphModel(input:{cwd:string;scope:'global'|'project';provider:string;id:string;agentDir?:string}) {if(!['global','project'].includes(input.scope))throw new Error('Invalid scope.');const path=graphModelSettingsLocations(input.cwd,input.agentDir)[input.scope],d=readDocument(path),key=`${input.provider}/${input.id}`;if(!Object.hasOwn(d.models??{},key))throw new Error('Custom model does not exist in the selected scope.');delete d.models[key];save(path,d);return {path,model:key};}