import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent'; import { discoverAgents } from '../src/runtime/agents.ts'; import { createGraphAgentRole, editGraphAgentRole, deleteGraphAgentRole, readGraphAgentRole, readGraphModelSettings, readRoleModelOverride, selectGraphModelProfile, writeGraphModelSettings } from '../src/runtime/settings.ts'; import {readCustomGraphModels,setCustomGraphModel,deleteCustomGraphModel} from '../src/runtime/custom-models.ts'; function show(ctx:ExtensionCommandContext,value:unknown){ctx.ui.notify(typeof value==='string'?value:JSON.stringify(value,null,2),'info');} export function registerGraphModelSettings(pi:ExtensionAPI) { pi.registerCommand('graph-models',{description:'独立配置 Graph 子 Agent 的主模型、替补模型与思考等级;新 Graph 生效。',handler:async(args,ctx)=>{ try{ const raw=args.trim();if(raw){const space=raw.indexOf(' '),action=space<0?raw:raw.slice(0,space),body=space<0?'':raw.slice(space+1);if(action==='list'){const s=readGraphModelSettings(ctx.cwd);show(ctx,{settings:s,customModels:readCustomGraphModels(ctx.cwd),availableModels:[...ctx.modelRegistry.getAvailable().map(m=>`${m.provider}/${m.id}`),...readCustomGraphModels(ctx.cwd).map(m=>`${m.provider}/${m.id}`)],roles:discoverAgents(ctx.cwd,'both').agents.map(a=>({name:a.name,originalModel:a.model,override:readRoleModelOverride(a.name,ctx.cwd)}))});return;}const value=JSON.parse(body);if(action==='set')show(ctx,writeGraphModelSettings({cwd:ctx.cwd,scope:value.scope??'project',role:value.role,value:value.value}));else if(action==='useprofile')show(ctx,selectGraphModelProfile({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else if(action==='profile')show(ctx,writeGraphModelSettings({cwd:ctx.cwd,scope:value.scope??'project',profile:value.name,value:value.value}));else if(action==='modelset')show(ctx,setCustomGraphModel({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else if(action==='modeldelete')show(ctx,deleteCustomGraphModel({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else if(action==='roleedit')show(ctx,editGraphAgentRole({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else if(action==='roledelete')show(ctx,deleteGraphAgentRole({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else if(action==='rolecreate')show(ctx,createGraphAgentRole({...value,cwd:ctx.cwd,scope:value.scope??'project'}));else throw new Error('使用 /graph-models list 或 set/profile/useprofile/modelset/modeldelete/rolecreate/roleedit/roledelete 后接 JSON。');return;} if(!ctx.hasUI){show(ctx,'使用 /graph-models list;保存:/graph-models set {"scope":"project","role":"researcher","value":{"model":"kimi-coding/k3","fallbackModels":[],"thinking":"high"}}');return;} const action=await ctx.ui.select('Graph 模型设置(新 Graph 生效)',['查看角色与模型','配置角色模型','配置模型方案','切换岗位模型方案','创建子 Agent','自定义模型定义','删除自定义模型','编辑岗位规则和工具','删除岗位']);if(!action)return; if(action==='查看角色与模型'){show(ctx,{settings:readGraphModelSettings(ctx.cwd),roles:discoverAgents(ctx.cwd,'both').agents.map(a=>({name:a.name,originalModel:a.model,override:readRoleModelOverride(a.name,ctx.cwd)}))});return;} const scopeChoice=await ctx.ui.select('保存范围',['当前项目','全局']);if(!scopeChoice)return;const scope=scopeChoice==='全局'?'global':'project'; if(action==='切换岗位模型方案'){const role=await ctx.ui.select('选择岗位',discoverAgents(ctx.cwd,'both').agents.map(a=>a.name));if(!role)return;const profiles=Object.keys(readGraphModelSettings(ctx.cwd).profiles);if(!profiles.length){show(ctx,'尚无模型方案,请先选择“配置模型方案”创建。');return;}const profile=await ctx.ui.select('选择模型方案(清除所选范围的单独模型覆盖)',profiles);if(!profile)return;show(ctx,selectGraphModelProfile({cwd:ctx.cwd,scope,role,profile}));return;} if(action==='自定义模型定义'){const text=await ctx.ui.input('模型定义 JSON(provider须graph-开头;auth仅env或pi引用)','{"provider":"graph-custom","id":"model-id","name":"My model","api":"openai-completions","baseUrl":"https://example.com/v1","input":["text"],"contextWindow":128000,"maxTokens":8192,"reasoning":false,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"auth":{"type":"env","variable":"CUSTOM_MODEL_API_KEY"}}');if(!text)return;show(ctx,setCustomGraphModel({cwd:ctx.cwd,scope,value:JSON.parse(text)}));return;} if(action==='删除自定义模型'){const models=readCustomGraphModels(ctx.cwd).filter(m=>m.source===scope),selected=await ctx.ui.select('选择要删除的模型定义',models.map(m=>`${m.provider}/${m.id}`));if(!selected)return;const m=models.find(m=>`${m.provider}/${m.id}`===selected)!;if(!await ctx.ui.confirm('删除模型定义',`${selected} 将从${scope}设置中删除;现有冻结Graph不变,后续使用此模型的任务需重新配置。`))return;show(ctx,deleteCustomGraphModel({cwd:ctx.cwd,scope,provider:m.provider,id:m.id}));return;} if(action==='编辑岗位规则和工具'||action==='删除岗位'){const name=await ctx.ui.input('岗位名称(仅所选范围的 agents/.md)');if(!name)return;const current=readGraphAgentRole({cwd:ctx.cwd,scope,name});if(action==='删除岗位'){if(!await ctx.ui.confirm('删除岗位文件',`${current.path} 将被删除。仅删除此岗位文件;当前冻结Graph不变。`))return;show(ctx,deleteGraphAgentRole({cwd:ctx.cwd,scope,name,expectedDigest:current.digest}));return;}const text=await ctx.ui.input('岗位修改 JSON(description/prompt/tools/model/thinking)',JSON.stringify({description:current.agent.description,prompt:current.agent.systemPrompt,tools:current.agent.tools??[]}));if(!text)return;show(ctx,editGraphAgentRole({cwd:ctx.cwd,scope,name,expectedDigest:current.digest,value:JSON.parse(text)}));return;} if(action==='创建子 Agent'){const name=await ctx.ui.input('角色名称(小写英文)');if(!name)return;const description=await ctx.ui.input('角色说明');if(!description)return;const prompt=await ctx.ui.input('角色执行规则');if(!prompt)return;const tools=await ctx.ui.input('工具名称,逗号分隔','read, grep, find, ls');if(tools===undefined)return;show(ctx,createGraphAgentRole({cwd:ctx.cwd,scope,name,description,prompt,tools:tools.split(',').map(t=>t.trim()).filter(Boolean)}));return;} const name=action==='配置模型方案'?await ctx.ui.input('方案名称'):await ctx.ui.select('选择角色',discoverAgents(ctx.cwd,'both').agents.map(a=>a.name));if(!name)return; const models=[...ctx.modelRegistry.getAvailable().map(m=>`${m.provider}/${m.id}`),...readCustomGraphModels(ctx.cwd).map(m=>`${m.provider}/${m.id}`)],selected=await ctx.ui.select('选择主模型',['手动填写 provider/model',...models]);if(!selected)return;const chosen=selected==='手动填写 provider/model'?await ctx.ui.input('主模型 provider/model'):selected;if(!chosen)return;const fallback=await ctx.ui.input('替补模型 provider/model,逗号分隔;留空表示不设置替补','kimi-coding/k3');if(fallback===undefined)return;const thinking=await ctx.ui.select('思考等级',['off','minimal','low','medium','high','xhigh','max']);if(!thinking)return; const value={model:chosen,fallbackModels:fallback.split(',').map(s=>s.trim()).filter(Boolean),thinking};const result=writeGraphModelSettings({cwd:ctx.cwd,scope,...(action==='配置模型方案'?{profile:name}:{role:name}),value});show(ctx,`已保存 ${result.path}。现有 Graph 保持冻结配置,新 Graph 使用此设置。`); }catch(e){ctx.ui.notify(e instanceof Error?e.message:String(e),'error');} }}); }