agent-afk 3.60.4 → 3.60.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +3 -3
- package/dist/index.mjs +2 -2
- package/dist/telegram.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1177,7 +1177,7 @@ ${s}`}}}return{...e,systemPrompt:r}}function Zu(e,t="cli"){return n=>{if(n.event
|
|
|
1177
1177
|
${u.content}`,isError:!0,...u.truncated===!0?{truncated:!0}:{}}),i.push({call:c,result:u}),yield{type:"tool.output",toolUseId:c.id,toolName:c.name,content:u.content,...u.isError===!0?{isError:!0}:{},...u.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},u.render?.diff&&(yield{type:"tool.diff",toolUseId:c.id,diff:u.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(cy(t.assistantText,r,t.reasoningText));for(let a of uy(i))this.priorTurns.push(a)}async interrupt(){let t=this.abortController;if(t&&!t.signal.aborted){t.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(t){t!==void 0&&(this.currentModel=t)}async setPermissionMode(t){this.currentPermissionMode=py(t)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t)}async supportedCommands(){try{return sr().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let t=this.lastUsage,n=it(this.currentModel),r;if(t&&n>0){let i=Jr(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=ca(t);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(t=>({name:t.serverName,status:t.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(t,n){return{canRewind:!1,error:`${nd} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let t=this.abortController;t&&!t.signal.aborted?t.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),J(`\u{1F7E2} ${nd}: closed`)}};function T0(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),new w0(t)}function E0(e){if(!e||typeof e!="object")return"";let t=e,n=t.file_path??t.path??t.filePath;if(typeof n=="string")return" "+n;let r=t.command??t.cmd;if(typeof r=="string"){let s=r.split(`
|
|
1178
1178
|
`)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=t.query??t.pattern??t.url??t.description;return typeof o=="string"?" "+o:""}function my(e,t,n={}){let r=bs(e.apiKey),o=e.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof e.model=="string"?e.model:"gpt-4o-mini",i={auth:r,model:s,synthesizedSessionId:o,promptStream:t,config:e};return n.baseURL!==void 0&&(i.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(i.toolDispatcher=n.toolDispatcher),n.mcpManager!==void 0&&(i.mcpManager=n.mcpManager),new ua(i)}var od="openai-compatible",xt=class{name=od;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_presenceSessionId=null;constructor(t={}){this.providerOpts=t,this.memoryStore=t.memoryStore??new Be;let n=[...Xt];t.subagentExecutor&&n.push(er),t.skillExecutor&&n.push(tr),t.composeExecutor&&n.push(nr),n.push(...An),n.push(Lt),this.schemas=n}query(t){let n=t.config,r=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=ls({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:od,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof en?o.toolDefs.map(m=>m.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?cs(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{}});let a={};if(this.providerOpts.baseURL!==void 0&&(a.baseURL=this.providerOpts.baseURL),a.toolDispatcher=o,this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let m=n.sessionId,f=i.getWorkspace();us({sessionId:m,surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:od,name:s},workspace:f,pid:process.pid}),process.once("exit",()=>{Qt(m)}),process.once("SIGINT",()=>{Qt(m),process.exit(130)}),process.once("SIGTERM",()=>{Qt(m),process.exit(143)})}let c=Hr({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),u=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,d={...n,systemPrompt:u!==void 0?`${u}
|
|
1179
1179
|
|
|
1180
|
-
${c}`:c};return my(d,t.prompt,a)}buildDispatcher(t,n){let r=sa(t,n.cwd),o=as(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[l,c]of o)r.set(l,c);n.runtimeStateSource&&r.set("get_runtime_state",Kr(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[l,c]of this.providerOpts.mcpManager.getMcpHandlers())r.set(l,c);let i=n.isSkillDispatch?this.schemas.filter(l=>l.name!=="ask_question"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new en(a)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}addReadRoot(t,n="slash",r){this.ensureSharedRoots();let o=rd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(t,n="slash",r){this.ensureSharedRoots();let o=rd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(t,n="slash",r){if(!this._sharedReadRoots)return;let o=rd.resolve(t);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(t){try{let n=Dr();R0(A0(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});x0(n,r+`
|
|
1180
|
+
${c}`:c};return my(d,t.prompt,a)}buildDispatcher(t,n){let r=sa(t,n.cwd),o=as(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[l,c]of o)r.set(l,c);n.runtimeStateSource&&r.set("get_runtime_state",Kr(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[l,c]of this.providerOpts.mcpManager.getMcpHandlers())r.set(l,c);let i=n.isSkillDispatch?this.schemas.filter(l=>l.name!=="ask_question"&&l.name!=="terminal_font_size"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new en(a)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}addReadRoot(t,n="slash",r){this.ensureSharedRoots();let o=rd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(t,n="slash",r){this.ensureSharedRoots();let o=rd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(t,n="slash",r){if(!this._sharedReadRoots)return;let o=rd.resolve(t);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(t){try{let n=Dr();R0(A0(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});x0(n,r+`
|
|
1181
1181
|
`)}catch{}}close(){this.memoryStore.close()}},_0=new xt;var C0=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search"]),I0=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size"]),P0=new Set(["Bash","BashOutput","KillBash","bash"]),Vr=new Set(["Agent","Task","agent"]),sd=new Set(["Skill","skill"]),id=new Set(["Compose","compose"]),Je=new Set([...Vr,...id,...sd]),M0=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),O0=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),$0=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),D0=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Cn(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}var fy=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...st];function In(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":Cn(C0,e)?"read":Cn(I0,e)?"write":Cn(P0,e)?"shell":Cn(Vr,e)?"subagent":Cn(sd,e)?"skill":Cn(id,e)?"dag":Cn(M0,e)?"web":O0.has(e)?"browser":Cn($0,e)?"planning":D0.has(e)?"schedule":"other"}var L0={subagent:"subagent",skill:"skill",dag:"dag"};function ad(e){return L0[e]}import{isAbsolute as W0}from"node:path";import{EventEmitter as N0}from"node:events";import*as Pn from"node:fs/promises";import*as by from"node:path";import{createHash as U0}from"node:crypto";B();import*as Yr from"node:fs";import*as De from"node:fs/promises";import*as gy from"node:readline";import{randomBytes as F0}from"node:crypto";var da=class{jobId;logPath;metaPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;metaWriteQueue=Promise.resolve();constructor(t){this.jobId=t,this.logPath=Ii(t),this.metaPath=su(t);try{Yr.mkdirSync(Yn(t),{recursive:!0})}catch(n){process.stderr.write(`[afk] bg-job-log: mkdir failed for ${t}: ${String(n)}
|
|
1182
1182
|
`),this.errored=!0}}write(t){if(this.errored||this.closed)return;let n=JSON.stringify(t)+`
|
|
1183
1183
|
`;if(!this.stream){this.pendingLines.push(n),this._openStream();return}if(!this.streamReady){this.pendingLines.push(n);return}this._writeLine(n)}_openStream(){if(!this.stream){this.readyPromise=new Promise(t=>{this.readyResolve=t});try{let t=Yr.createWriteStream(this.logPath,{flags:"a",encoding:"utf8",mode:384});this.stream=t,t.once("open",()=>{this.streamReady=!0;for(let n of this.pendingLines)this._writeLine(n);this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}),t.once("error",n=>{process.stderr.write(`[afk] bg-job-log: stream error for ${this.jobId}: ${String(n)}
|
|
@@ -1925,7 +1925,7 @@ Save reusable multi-step workflows the user teaches you or that you discover wor
|
|
|
1925
1925
|
`;process.stderr.write(l);return}let i=cD(t),a=uD(i);try{iD(a,{recursive:!0});let c=(!lD(i)?dD:"")+JSON.stringify(s)+`
|
|
1926
1926
|
`;aD(i,c)}catch(l){let c=`[prompt-dump] Failed to write to ${i}: ${String(l)}
|
|
1927
1927
|
`;process.stderr.write(c)}}B();G();var Oa="anthropic-direct",wD="claude-sonnet-4-5-20250929",SD=e=>/opus-4-(7|[89])/.test(e),bw=null;var Le=class{name=Oa;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;mcpManager;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...Xt];if(t.subagentExecutor&&n.push(er),t.skillExecutor&&n.push(tr),t.composeExecutor&&n.push(nr),n.push(...An),n.push(Lt),this.memoryStore=t.memoryStore??new Be,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.subagentExecutor=t.subagentExecutor,this.composeExecutor=t.composeExecutor,this.surface=t.surface??"cli",this.mcpManager=t.mcpManager,t.mcpManager){let r=t.mcpManager.onToolsRefreshed;t.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}t.clientFactory&&(this.providerFactory=t.clientFactory)}buildDispatcher(t,n){let r=sa(t,n?.cwd),o=as(this.memoryStore,void 0,this.surface);for(let[i,a]of o)r.set(i,a);if(n?.runtimeStateSource&&r.set("get_runtime_state",Kr(n.runtimeStateSource)),this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[i,a]of this._mcpHandlersCache)r.set(i,a)}let s=this._mcpToolsCache??[];return new en({handlers:r,schemas:[...this.schemas,...s],hookRegistry:this.hookRegistry,permissions:this.permissions,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{}})}close(){this.memoryStore.close()}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}addReadRoot(t,n="slash",r){this.ensureSharedRoots();let o=Wd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(t,n="slash",r){this.ensureSharedRoots();let o=Wd.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(t,n="slash",r){if(!this._sharedReadRoots)return;let o=Wd.resolve(t);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(t){try{let n=Dr();yD(bD(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});hD(n,r+`
|
|
1928
|
-
`)}catch{}}query(t){let n=t.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:T.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:T.ANTHROPIC_API_KEY||T.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Oa} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ui(o),i=ss(o,s,n.baseUrl),a=this.providerFactory??bw,l=a?a(i):new yw(i),c=r?null:fg(s),u=kD(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ln(n.model)??n.model:wD,m=TD(n,d),f=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,h=ls({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:d,providerName:Oa,permissionMode:f,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof en?g.toolDefs.map(R=>R.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let R=n.sessionId,O=h.getWorkspace();us({sessionId:R,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Oa,name:d},workspace:O,pid:process.pid}),process.once("exit",()=>{Qt(R)}),process.once("SIGINT",()=>{Qt(R),process.exit(130)}),process.once("SIGTERM",()=>{Qt(R),process.exit(143)})}g=this.externalTools?cs(this.externalTools,h):this.buildDispatcher(f,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:h});let y=g instanceof en?[...g.toolDefs]:[...Xt,Lt],w=n.isSkillDispatch?y.filter(R=>R.name!=="ask_question"):y,S=this.skillExecutor?Zb():"",x=n.cwd||process.cwd(),v=n.isSkillDispatch?Ma:`${Ma}
|
|
1928
|
+
`)}catch{}}query(t){let n=t.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:T.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:T.ANTHROPIC_API_KEY||T.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Oa} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ui(o),i=ss(o,s,n.baseUrl),a=this.providerFactory??bw,l=a?a(i):new yw(i),c=r?null:fg(s),u=kD(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ln(n.model)??n.model:wD,m=TD(n,d),f=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,h=ls({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:d,providerName:Oa,permissionMode:f,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof en?g.toolDefs.map(R=>R.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let R=n.sessionId,O=h.getWorkspace();us({sessionId:R,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Oa,name:d},workspace:O,pid:process.pid}),process.once("exit",()=>{Qt(R)}),process.once("SIGINT",()=>{Qt(R),process.exit(130)}),process.once("SIGTERM",()=>{Qt(R),process.exit(143)})}g=this.externalTools?cs(this.externalTools,h):this.buildDispatcher(f,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:h});let y=g instanceof en?[...g.toolDefs]:[...Xt,Lt],w=n.isSkillDispatch?y.filter(R=>R.name!=="ask_question"&&R.name!=="terminal_font_size"):y,S=this.skillExecutor?Zb():"",x=n.cwd||process.cwd(),v=n.isSkillDispatch?Ma:`${Ma}
|
|
1929
1929
|
|
|
1930
1930
|
${Nd}
|
|
1931
1931
|
|
|
@@ -2215,7 +2215,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2215
2215
|
`))!==-1;){let u=n.slice(0,c);n=n.slice(c+1),this.opts.writeLine(u)}},s={command:t,mode:"foreground",onChunk:c=>{r||(n+=c.toString("utf8"),o())}},i=this.opts.getCwd();i!==void 0&&(s.cwd=i);let{job:a,handle:l}=this.registry.start(s);this.activeFgJobId=a.id;try{let c=await l.promise;r=!0,n.length>0&&(this.opts.writeLine(n),n=""),this.opts.writeLine(VB(a,c)),this.queueInjection({command:t,mode:"foreground",result:c})}finally{this.activeFgJobId=null}}startBackground(t){let n={command:t,mode:"background"},r=this.opts.getCwd();r!==void 0&&(n.cwd=r);let{job:o}=this.registry.start(n);this.opts.writeLine(p.dim(` [${o.id}] background: `)+t)}queueInjection(t){this.pendingInjections.push(t),this.pendingInjections.length>e.MAX_PENDING_INJECTIONS&&this.pendingInjections.shift()}};async function XB(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}function bc(e,t){let n=p.brand("afk")+p.dim(` (${e})`),r=t?p.warning(" \u25CF plan"):"";return n+r+p.dim(" \u203A ")}async function fE(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async g=>{Ue()&&(o=Qa(g)),await Kl(e.session.current),Ue()&&(s=aT())}).catch(()=>{});let i=await YT(),a=new gc({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d,m,f=!1;try{await a.armCompositor({promptFn:()=>bc(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let S=e.slashCtx;S.stats.planMode&&S.stats.pendingPlanExit?(S.stats.pendingPlanExit=!1,At(S,!1,{closureSummarySkipped:!0}).catch(()=>{})):At(S).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{}});let g=a.getCompositor();Ft.install(Va({readLine:S=>a.readLine({promptFn:()=>S}).then(x=>x.text),writer:{line:(S="")=>{let x=a.getCompositor();x?x.commitAbove(S):process.stdout.write(S+`
|
|
2216
2216
|
`)}},pendingCount:()=>Ft.pendingCount(),...g?{pickFromList:S=>tE(g,S),readTextOverlay:S=>nE(g,S)}:{}})),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor();let h=a.getCompositor();if(h){let S=x=>h.commitAbove(x);e.completionWriter.fn=S,e.completionWriter.idleFn=S}e.slashCtx.setSoftStopHandler=S=>a.setSoftStopHandler(S),e.inputSurfaceRef&&(e.inputSurfaceRef.current=a),c=aE();let b=lE();e.clearVerdictLedger=()=>b.reset(),u=new sl,QS(u),lk(u),dk(u),ck(e.backgroundRegistry),d=new hc(u,e.backgroundRegistry),d.setRowCountChangeHandler(S=>{e.statusLine.setExtraRows(S)}),d.start();let y=50,w=[];for(u.on("complete",S=>{w.length>=y&&w.shift(),w.push(S)}),m=new yc({writeLine:S=>e.replRenderer.writeLine(S),getCwd:()=>e.stats.cwd}),ik(m),n.tryAbortShellForeground=()=>m.abortActiveForeground();;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let E of s)e.replRenderer.writeLine(E);e.replRenderer.writeLine(""),s=[]}for(;w.length>0;){let E=w.shift(),_=E.status==="succeeded"?"\u2713":"\u2717",L=[];if(E.resultText){let O=E.resultText.trim().split(`
|
|
2217
2217
|
`)[0]?.slice(0,80)??"";O&&L.push(O)}E.error&&L.push(E.error.message);let R=[E.stats.toolUses>0?`${E.stats.toolUses} tools`:"",E.stats.tokens>0?`${Math.round(E.stats.tokens/1e3)}k tok`:"",E.stats.durationMs>0?`${Math.round(E.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");R&&L.push(R),e.replRenderer.writeLine(Tn({kind:E.status==="succeeded"?"checkpoint":"diagnosis",title:`${_} ${E.id} ${E.label}`,body:L})),e.replRenderer.writeLine("")}let S=m.drainNotifications();for(let{job:E,result:_}of S){let L=_.errorReason===void 0?"\u2713":"\u2717",R=_.errorReason==="abort"?"killed":_.errorReason==="timeout"?"timed out":_.errorReason==="signal-killed"?"killed by signal":`exit ${_.exitCode??0}`,O=Math.max(0,Math.round(_.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${L} [${E.id}] ${R} \xB7 ${O}s \xB7 `)+E.command)}let x=c.renderIfChanged(e.stats.sessionId);if(x.length>0){for(let E of x)e.replRenderer.writeLine(E);e.replRenderer.writeLine("")}let v=b.render();v&&e.replRenderer.writeLine(v);let A,P;if(l!==void 0){let E=l;l=void 0;let _=bc(e.stats.model,e.stats.planMode),L=pr({buffer:E.text,promptText:_,isTTY:!!process.stdout.isTTY,attachmentSummary:Ao([...E.attachments])});e.replRenderer.writeLine(L),A=E.text.trim(),P=E.attachments}else{let E=await a.readLine({promptFn:()=>bc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let _=e.slashCtx;_.stats.planMode&&_.stats.pendingPlanExit?(_.stats.pendingPlanExit=!1,At(_,!1,{closureSummarySkipped:!0}).catch(()=>{})):At(_).catch(()=>{}),e.statusLine.rearm()}});A=E.text.trim(),P=E.attachments}if(!A&&P.length===0)continue;if(A.startsWith("!")){let E=/^(0|false|off|no)$/i.test(T.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!E&&(f||(f=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await m.dispatch(A))){e.statusLine.rearm();continue}}let D=!1;if(A.startsWith("/")){let E=await wS(A,e.slashCtx,P);if(E.handled){if(E.result==="exit"){e.rl.close();return}if((A==="/clear"||A.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),b.reset()),E.result!==null&&typeof E.result=="object"&&"kind"in E.result&&E.result.kind==="submit"){l={text:E.result.message,attachments:P??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}D=!0}i.push(A),await XB(e,A);let I=A;if(D){let E=Qd(A);if(E){let _=E.name.replace(/^\//,"").split(":").pop()??"";if(_&&Xp(_)){let L={skillName:_,rawArgs:E.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},R=e.session.current.sessionId,O=kr(R),U=Date.now();J(`[afk trace] preflight.start commandName=${_}`);let K=!1,C=await Sr(L,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},N=>{Ue()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${_}) failed: `)+(N instanceof Error?N.message:String(N)))});K=C!==null,J(`[afk trace] preflight.end commandName=${_} durationMs=${Date.now()-U} success=${K}`),I=em(C?.manifestBlock,A)}}}let M=m.drainInjections();M.length>0&&(I=M+I),await iE({text:I,attachments:P},e.session.current,e.stats,{setInFlight(E){n.turnInFlight=E},async onTurnComplete(E,_){await t.appendTurn(E,_)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await OS(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:E=>b.push(E),setActiveCompositor:E=>{n.activeCompositor=E},setInterruptNotifier:E=>{n.notifyInterrupting=E},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:E=>a.setBackgroundHandler(E),setSoftStopHandler:E=>a.setSoftStopHandler(E),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(dr(e.stats,e.contextSampler))}},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(bc(e.stats.model,e.stats.planMode)))}}finally{if(u!==void 0)for(let h of u.running())u.cancel(h.id);n.tryAbortShellForeground=null,m?.drainOnExit(),d?.stop(),c?.dispose();let g=h=>console.log(h);e.completionWriter.fn=g,e.completionWriter.idleFn=g,await a.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}import{execFile as ZB}from"node:child_process";import{dirname as QB,isAbsolute as eW,resolve as tW}from"node:path";import{promisify as nW}from"node:util";var gE=nW(ZB),rW=3e3,oW=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function sW(){let t=(await gE("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=eW(t)?t:tW(process.cwd(),t);return QB(n)}async function hE(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await sW()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),rW)});try{let o=Gt({execFile:gE,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>oW.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as iW}from"node:fs";import{dirname as aW,join as wE}from"node:path";import{randomBytes as lW}from"node:crypto";var cW=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
2218
|
-
`),yE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Em=30,uW=1024,dW=8e3,pW="haiku";async function mW(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=yW(n,uW),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??dW),i=t.signal?bW([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await sc({token:t.token,model:t.model??pW,system:cW,user:r,maxTokens:32,signal:i})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(s)}let l=fW(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=aW(t.worktreePath);return await gW(l,c)}function fW(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(yE.test(t)&&t.length<=Em)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Em)break;o=i}return yE.test(o)?o:null}async function gW(e,t){if(!await hW(wE(t,e)))return e;let n=lW(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Em-5)}-${n}`}async function hW(e){try{return await iW.access(e),!0}catch{return!1}}function yW(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function bW(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function SE(e){let t,n,r=wE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await mW(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Ea(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return bE(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return bE(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function bE(e,t){e&&e.setCwd(t),wW(t)}function wW(e){try{process.chdir(e)}catch{}}B();import{spawn as kE}from"child_process";import{existsSync as EW,mkdirSync as xW,readFileSync as vE,unlinkSync as RW,writeFileSync as AW}from"fs";import{get as _W}from"https";import{join as TE}from"path";import{readFileSync as SW}from"fs";import{dirname as kW,join as vW}from"path";import{fileURLToPath as TW}from"url";function gn(){try{return"3.60.
|
|
2218
|
+
`),yE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Em=30,uW=1024,dW=8e3,pW="haiku";async function mW(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=yW(n,uW),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??dW),i=t.signal?bW([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await sc({token:t.token,model:t.model??pW,system:cW,user:r,maxTokens:32,signal:i})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(s)}let l=fW(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=aW(t.worktreePath);return await gW(l,c)}function fW(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(yE.test(t)&&t.length<=Em)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Em)break;o=i}return yE.test(o)?o:null}async function gW(e,t){if(!await hW(wE(t,e)))return e;let n=lW(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Em-5)}-${n}`}async function hW(e){try{return await iW.access(e),!0}catch{return!1}}function yW(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function bW(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function SE(e){let t,n,r=wE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await mW(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Ea(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return bE(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return bE(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function bE(e,t){e&&e.setCwd(t),wW(t)}function wW(e){try{process.chdir(e)}catch{}}B();import{spawn as kE}from"child_process";import{existsSync as EW,mkdirSync as xW,readFileSync as vE,unlinkSync as RW,writeFileSync as AW}from"fs";import{get as _W}from"https";import{join as TE}from"path";import{readFileSync as SW}from"fs";import{dirname as kW,join as vW}from"path";import{fileURLToPath as TW}from"url";function gn(){try{return"3.60.5"}catch{}try{let e=kW(TW(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(SW(vW(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var CW=64*1024,IW=1440*60*1e3,PW="update-check.json",MW="pending-update.json";function EE(){return TE(Ri(),PW)}function xm(){return TE(Ri(),MW)}function xE(){let e=Ri();EW(e)||xW(e,{recursive:!0})}function OW(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function $W(){try{let e=vE(EE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function DW(){try{xE();let e=`
|
|
2219
2219
|
const https = require('https');
|
|
2220
2220
|
const fs = require('fs');
|
|
2221
2221
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/index.mjs
CHANGED
|
@@ -1116,7 +1116,7 @@ ${s}`}}}return{...t,systemPrompt:r}}import pf from"openai";import{randomUUID as
|
|
|
1116
1116
|
${d.content}`,isError:!0,...d.truncated===!0?{truncated:!0}:{}}),i.push({call:l,result:d}),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...d.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(Mi(e.assistantText,r,e.reasoningText));for(let a of Oi(i))this.priorTurns.push(a)}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=Fi(e)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){try{return lt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Mt(this.currentModel),r;if(e&&n>0){let i=ct(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=mn(e);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Mr} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),D(`\u{1F7E2} ${Mr}: closed`)}};function hf(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),new pf(e)}function yf(t){if(!t||typeof t!="object")return"";let e=t,n=e.file_path??e.path??e.filePath;if(typeof n=="string")return" "+n;let r=e.command??e.cmd;if(typeof r=="string"){let s=r.split(`
|
|
1117
1117
|
`)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}function Li(t,e,n={}){let r=Pr(t.apiKey),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i={auth:r,model:s,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(i.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(i.toolDispatcher=n.toolDispatcher),n.mcpManager!==void 0&&(i.mcpManager=n.mcpManager),new gn(i)}var Dr="openai-compatible",le=class{name=Dr;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_presenceSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new be;let n=[...ae];e.subagentExecutor&&n.push(Pe),e.skillExecutor&&n.push(Ie),e.composeExecutor&&n.push(Ce),n.push(...Me),n.push(me),this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=Et({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:Dr,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof ce?o.toolDefs.map(p=>p.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?At(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{}});let a={};if(this.providerOpts.baseURL!==void 0&&(a.baseURL=this.providerOpts.baseURL),a.toolDispatcher=o,this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let p=n.sessionId,g=i.getWorkspace();xt({sessionId:p,surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Dr,name:s},workspace:g,pid:process.pid}),process.once("exit",()=>{ye(p)}),process.once("SIGINT",()=>{ye(p),process.exit(130)}),process.once("SIGTERM",()=>{ye(p),process.exit(143)})}let l=et({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),d=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,u={...n,systemPrompt:d!==void 0?`${d}
|
|
1118
1118
|
|
|
1119
|
-
${l}`:l};return Li(u,e.prompt,a)}buildDispatcher(e,n){let r=at(e,n.cwd),o=_t(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[c,l]of o)r.set(c,l);n.runtimeStateSource&&r.set("get_runtime_state",nt(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[c,l]of this.providerOpts.mcpManager.getMcpHandlers())r.set(c,l);let i=n.isSkillDispatch?this.schemas.filter(c=>c.name!=="ask_question"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new ce(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=Or.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=Or.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=Or.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=Ze();wf(Sf(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});bf(n,r+`
|
|
1119
|
+
${l}`:l};return Li(u,e.prompt,a)}buildDispatcher(e,n){let r=at(e,n.cwd),o=_t(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[c,l]of o)r.set(c,l);n.runtimeStateSource&&r.set("get_runtime_state",nt(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[c,l]of this.providerOpts.mcpManager.getMcpHandlers())r.set(c,l);let i=n.isSkillDispatch?this.schemas.filter(c=>c.name!=="ask_question"&&c.name!=="terminal_font_size"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new ce(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=Or.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=Or.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=Or.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=Ze();wf(Sf(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});bf(n,r+`
|
|
1120
1120
|
`)}catch{}}close(){this.memoryStore.close()}},Fr=new le;var kf=new Set(["Agent","Task","agent"]),vf=new Set(["Skill","skill"]),_f=new Set(["Compose","compose"]),xv=new Set([...kf,..._f,...vf]);var Ni=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...tt];U();U();var $v=300*1e3;var __=[...Zt,...tt,"memory_search","agent","skill"];function Ui(t,e){let n={allowedTools:[...Ni]};return de(typeof e=="string"?e:void 0)==="openai-compatible"?new le({permissions:n}):new we({permissions:n})}function Nr(t){let e=Tf(t);return e!==void 0?e:Rf(t)}function Tf(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return Bi(n.trim())}function Rf(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Pf(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=Bi(r);if(o!==void 0)return o}}function Pf(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function Bi(t){try{return JSON.parse(t)}catch{return}}function $r(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function Hi(t,e,n,r,o){if(!r)return{id:t,status:e,message:n,trace:o};let s=Nr(n.content),i=r.safeParse(s);return i.success?{id:t,status:e,message:n,output:i.data,trace:o}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${i.error.message}`,{cause:i.error}),schemaError:i.error,trace:o}}function ji(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function z(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var hn=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,g,m){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.progressSink=p,this.parentId=g}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=$r();lastStreamedContent="";get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=St(this.streamToFinalMessage(e,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;return this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",Ne(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")}),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(Ne(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Ne(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=$r();let s=n??this.progressSink??Re(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e)){if(s&&s(a,i),a.type==="chunk"){let c=a.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let c=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e,n){try{let r=await this.run(e,n);return Hi(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=ji(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Re();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{D("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Ne(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Uo(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)D(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){D(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var If=async(t,e)=>({action:"decline"}),F=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;abortGraph;rootId;rootController;counter=0;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentCwd=e.cwd,this.abortGraph=new bt(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await $o(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:e.config.apiKey||this.parentApiKey,baseUrl:e.config.baseUrl??this.parentBaseUrl,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!0?{onElicitation:If}:{},...e.phaseRole==="read-only"?{provider:Ui("read-only",e.config.model)}:{}},a;try{a=new We(i)}catch(f){throw this.abortGraph.dispose(n),f}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??Re(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,g=new hn(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??wt,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},c,l,u??e.idPrefix,d,p??e.parent.sessionId,e.config.traceWriter);this.active.set(n,g);let m=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return Ne(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:m,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await ie({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:m,parent_session_id:e.parent.sessionId}),g}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function yn(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,c)=>c)),i=t.map((a,c)=>a.handle.runToResult(a.prompt).then(l=>{if(o[c]=l,s.delete(c),n&&l.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as Cf}from"node:url";import{dirname as Mf}from"node:path";var Of=Cf(import.meta.url),V_=Mf(Of),ee={name:"research-agent",systemPrompt:`---
|
|
1121
1121
|
name: research-agent
|
|
1122
1122
|
description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
|
|
@@ -1622,7 +1622,7 @@ Save reusable multi-step workflows the user teaches you or that you discover wor
|
|
|
1622
1622
|
`;process.stderr.write(c);return}let i=dh(e),a=uh(i);try{ah(a,{recursive:!0});let l=(!lh(i)?ph:"")+JSON.stringify(s)+`
|
|
1623
1623
|
`;ch(i,l)}catch(c){let l=`[prompt-dump] Failed to write to ${i}: ${String(c)}
|
|
1624
1624
|
`;process.stderr.write(l)}}U();N();var Pn="anthropic-direct",kh="claude-sonnet-4-5-20250929",vh=t=>/opus-4-(7|[89])/.test(t),ic=null;var we=class{name=Pn;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;mcpManager;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(e={}){let n=[...ae];if(e.subagentExecutor&&n.push(Pe),e.skillExecutor&&n.push(Ie),e.composeExecutor&&n.push(Ce),n.push(...Me),n.push(me),this.memoryStore=e.memoryStore??new be,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){let r=at(e,n?.cwd),o=_t(this.memoryStore,void 0,this.surface);for(let[i,a]of o)r.set(i,a);if(n?.runtimeStateSource&&r.set("get_runtime_state",nt(n.runtimeStateSource)),this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[i,a]of this._mcpHandlersCache)r.set(i,a)}let s=this._mcpToolsCache??[];return new ce({handlers:r,schemas:[...this.schemas,...s],hookRegistry:this.hookRegistry,permissions:this.permissions,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{}})}close(){this.memoryStore.close()}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=oo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=oo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=oo.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=Ze();wh(Sh(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});bh(n,r+`
|
|
1625
|
-
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:_.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:_.ANTHROPIC_API_KEY||_.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Pn} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ao(o),i=qn(o,s,n.baseUrl),a=this.providerFactory??ic,c=a?a(i):new sc(i),l=r?null:xo(s),d=_h(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?Ke(n.model)??n.model:kh,p=Ah(n,u),g=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let m,f=Et({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:Pn,permissionMode:g,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>m instanceof ce?m.toolDefs.map(E=>E.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let E=n.sessionId,I=f.getWorkspace();xt({sessionId:E,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Pn,name:u},workspace:I,pid:process.pid}),process.once("exit",()=>{ye(E)}),process.once("SIGINT",()=>{ye(E),process.exit(130)}),process.once("SIGTERM",()=>{ye(E),process.exit(143)})}m=this.externalTools?At(this.externalTools,f):this.buildDispatcher(g,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:f});let w=m instanceof ce?[...m.toolDefs]:[...ae,me],k=n.isSkillDispatch?w.filter(E=>E.name!=="ask_question"):w,h=this.skillExecutor?Ha():"",y=n.cwd||process.cwd(),A=n.isSkillDispatch?Rn:`${Rn}
|
|
1625
|
+
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:_.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:_.ANTHROPIC_API_KEY||_.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Pn} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ao(o),i=qn(o,s,n.baseUrl),a=this.providerFactory??ic,c=a?a(i):new sc(i),l=r?null:xo(s),d=_h(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?Ke(n.model)??n.model:kh,p=Ah(n,u),g=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let m,f=Et({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:Pn,permissionMode:g,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>m instanceof ce?m.toolDefs.map(E=>E.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let E=n.sessionId,I=f.getWorkspace();xt({sessionId:E,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Pn,name:u},workspace:I,pid:process.pid}),process.once("exit",()=>{ye(E)}),process.once("SIGINT",()=>{ye(E),process.exit(130)}),process.once("SIGTERM",()=>{ye(E),process.exit(143)})}m=this.externalTools?At(this.externalTools,f):this.buildDispatcher(g,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:f});let w=m instanceof ce?[...m.toolDefs]:[...ae,me],k=n.isSkillDispatch?w.filter(E=>E.name!=="ask_question"&&E.name!=="terminal_font_size"):w,h=this.skillExecutor?Ha():"",y=n.cwd||process.cwd(),A=n.isSkillDispatch?Rn:`${Rn}
|
|
1626
1626
|
|
|
1627
1627
|
${eo}
|
|
1628
1628
|
|
package/dist/telegram.mjs
CHANGED
|
@@ -1133,7 +1133,7 @@ ${n.join(`
|
|
|
1133
1133
|
${d.content}`,isError:!0,...d.truncated===!0?{truncated:!0}:{}}),i.push({call:l,result:d}),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...d.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(xa(e.assistantText,r,e.reasoningText));for(let a of Ta(i))this.priorTurns.push(a)}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=Ia(e)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){try{return Ye().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Bt(this.currentModel),r;if(e&&n>0){let i=ut(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Nn(e);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${po} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),L(`\u{1F7E2} ${po}: closed`)}};function Qm(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),new Vm(e)}function Zm(t){if(!t||typeof t!="object")return"";let e=t,n=e.file_path??e.path??e.filePath;if(typeof n=="string")return" "+n;let r=e.command??e.cmd;if(typeof r=="string"){let s=r.split(`
|
|
1134
1134
|
`)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}function Pa(t,e,n={}){let r=co(t.apiKey),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i={auth:r,model:s,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(i.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(i.toolDispatcher=n.toolDispatcher),n.mcpManager!==void 0&&(i.mcpManager=n.mcpManager),new $n(i)}var mo="openai-compatible",be=class{name=mo;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_presenceSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new re;let n=[..._e];e.subagentExecutor&&n.push(qe),e.skillExecutor&&n.push(ze),e.composeExecutor&&n.push(Ve),n.push(...Pe),n.push(he),this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=Ot({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:mo,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Ae?o.toolDefs.map(p=>p.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Dt(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{}});let a={};if(this.providerOpts.baseURL!==void 0&&(a.baseURL=this.providerOpts.baseURL),a.toolDispatcher=o,this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let p=n.sessionId,h=i.getWorkspace();Ft({sessionId:p,surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:mo,name:s},workspace:h,pid:process.pid}),process.once("exit",()=>{Ee(p)}),process.once("SIGINT",()=>{Ee(p),process.exit(130)}),process.once("SIGTERM",()=>{Ee(p),process.exit(143)})}let l=st({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),d=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,u={...n,systemPrompt:d!==void 0?`${d}
|
|
1135
1135
|
|
|
1136
|
-
${l}`:l};return Pa(u,e.prompt,a)}buildDispatcher(e,n){let r=Ln(e,n.cwd),o=xt(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[c,l]of o)r.set(c,l);n.runtimeStateSource&&r.set("get_runtime_state",it(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[c,l]of this.providerOpts.mcpManager.getMcpHandlers())r.set(c,l);let i=n.isSkillDispatch?this.schemas.filter(c=>c.name!=="ask_question"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new Ae(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=fo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=fo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=fo.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=tt();tg(ng(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});eg(n,r+`
|
|
1136
|
+
${l}`:l};return Pa(u,e.prompt,a)}buildDispatcher(e,n){let r=Ln(e,n.cwd),o=xt(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[c,l]of o)r.set(c,l);n.runtimeStateSource&&r.set("get_runtime_state",it(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[c,l]of this.providerOpts.mcpManager.getMcpHandlers())r.set(c,l);let i=n.isSkillDispatch?this.schemas.filter(c=>c.name!=="ask_question"&&c.name!=="terminal_font_size"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),new Ae(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=fo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=fo.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=fo.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=tt();tg(ng(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});eg(n,r+`
|
|
1137
1137
|
`)}catch{}}close(){this.memoryStore.close()}},rg=new be;var og=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search"]),sg=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size"]),ig=new Set(["Bash","BashOutput","KillBash","bash"]),Ca=new Set(["Agent","Task","agent"]),Ma=new Set(["Skill","skill"]),Oa=new Set(["Compose","compose"]),cx=new Set([...Ca,...Oa,...Ma]),ag=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),cg=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),lg=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),dg=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Fe(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var Da=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...Oe];function Fa(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Fe(og,t)?"read":Fe(sg,t)?"write":Fe(ig,t)?"shell":Fe(Ca,t)?"subagent":Fe(Ma,t)?"skill":Fe(Oa,t)?"dag":Fe(ag,t)?"web":cg.has(t)?"browser":Fe(lg,t)?"planning":dg.has(t)?"schedule":"other"}import{isAbsolute as fg}from"node:path";B();B();var Sx=300*1e3;var Un=class extends Error{constructor(e,n){super(`Background job cap reached (${e}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}};function mg(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",c=e.id_prefix;if(c!==void 0){if(typeof c!="string")throw new Error("Agent tool id_prefix must be a string");a=c}let l="foreground",d=e.mode;if(d!==void 0){if(d!=="foreground"&&d!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(d)}`);l=d}let u,p=e.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!fg(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);u=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:l,...u!==void 0?{cwd:u}:{}}}function Bn(t){try{return X(t).catch(()=>{})}catch{return Promise.resolve()}}function pt(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Na(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}var gg=4096,La=1024;function hg(t){if(t==null)return;let e=Na(t);return e!==void 0&&e>gg?{truncated:!0,chars:e}:t}function yg(t){let e={status:t.status,error:pt(t.errorMessage,La),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=pt(t.schemaErrorMessage,La));let n=hg(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var ft=class t{constructor(e){this.ctx=e}ctx;getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=mg(e.input)}catch(g){return{content:`Agent tool input validation failed: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??mt,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=Z(i)==="openai-compatible",c={model:i,apiKey:a?void 0:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:a?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},l;if(this.ctx.childProviderFactory&&r<o){s=new F({parentAbortSignal:e.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),l=jt(e.signal);let g=new t({subagentManager:s,parentSession:l,defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),m=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;c.provider=this.ctx.childProviderFactory({childExecutor:g,...m!==void 0?{childSkillExecutor:m}:{},...c.model!==void 0?{model:c.model}:{}})}let d;try{d=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:c,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?ve(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":ve(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),l!==void 0&&(l.sessionId=d.id)}catch(g){let m=g instanceof Error?g.message:String(g);return Bn({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:pt(m),depth:r}),{content:`Failed to fork subagent: ${m}`,isError:!0}}if(n.mode==="background"){let g=this.ctx.backgroundRegistry;if(!g)return await d.teardown().catch(w=>L("subagent-executor: handle teardown failed: "+(w instanceof Error?w.message:String(w)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let m;try{m=g.register({handle:d,prompt:n.prompt,model:c.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(w){if(w instanceof Un)return await d.teardown().catch(S=>L("subagent-executor: handle teardown failed after cap error: "+(S instanceof Error?S.message:String(S)))),{content:w.message,isError:!0};throw w}let k={status:"running",jobId:m.jobId,subagentId:m.subagentId,label:m.label,message:`Background subagent started (jobId=${m.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${m.jobId} or ask the user to join.`};return{content:JSON.stringify(k)}}let u=()=>{d.cancel()};e.signal.addEventListener("abort",u,{once:!0});let p=Date.now(),h=this.ctx.parentSession.sessionId;try{let g=await d.runToResult(n.prompt);if(g.status==="succeeded"&&g.message){let S=g.message.content,y=typeof S=="string"?S:JSON.stringify(S),b=g.trace;return Bn({event:"subagent.completed",subagent_id:d.id,parent_session_id:h,status:g.status,duration_ms:Date.now()-p,content_chars:y.length,depth:r,tool_call_count:b?.toolCalls.length,thinking_present:b?.thinkingPresent,tool_names:b?.toolCalls.length?JSON.stringify([...new Set(b.toolCalls.map(A=>A.name))]):void 0}),{content:y}}let m=g.error?.message??"Subagent failed with no output",k=g.trace;Bn({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:h,status:g.status,duration_ms:Date.now()-p,error_message:pt(m),schema_error:g.schemaError?pt(g.schemaError.message):void 0,partial_output_chars:Na(g.partialOutput),depth:r,tool_call_count:k?.toolCalls.length,thinking_present:k?.thinkingPresent,tool_names:k?.toolCalls.length?JSON.stringify([...new Set(k.toolCalls.map(S=>S.name))]):void 0});let w=yg({status:g.status,errorMessage:m,schemaErrorMessage:g.schemaError?.message,partialOutput:g.partialOutput,subagentId:d.id});return{content:JSON.stringify(w),isError:!0}}catch(g){let m=g instanceof Error?g.message:String(g);throw Bn({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:h,status:"failed",duration_ms:Date.now()-p,error_message:pt(m),depth:r}),g}finally{e.signal.removeEventListener("abort",u),await s?.teardownAll(),await d.teardown()}}};var bg=new Set;function $a(t){return bg.has(t)}var wg=new Set,Sg=new Set;function Ua(t){for(let e of wg)e(t)}function Ba(t){for(let e of Sg)e(t)}var kg=240;function vg(t,e=kg){return t.length<=e?t:t.slice(0,e)+"\u2026"}function _g(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function Eg(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var gt=class{constructor(e){this.ctx=e}ctx;pluginBodies=null;async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??mt;if(n>=r){let c=_g(e.input);return X({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=Eg(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=Se(o.name);return await this.executeRegistrySkill(c,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,e);let a=Ye(this.ctx.pluginConfigs).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);let o=$a(e.name);o&&Ba(e.name);let s=this.ctx.depth??0;X({event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(d){a=d}finally{let d=Date.now()-i;o&&Ua({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;X({event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:vg(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}buildForkedChildConfig(e,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??mt,s={...e};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new F({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),a=new ft({subagentManager:i,parentSession:jt(n),defaultConfig:{model:s.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{}}),c=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:a,...c!==void 0?{childSkillExecutor:c}:{},...s.model!==void 0?{model:s.model}:{}}),{childConfig:s,childManager:i}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=G(e.name)["system.md"],!o)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(l){return{content:`Failed to load skill prompts: ${l instanceof Error?l.message:String(l)}`,isError:!0}}let s=new F({parentAbortSignal:r.signal,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ce(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:i,childManager:a}=this.buildForkedChildConfig({model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),c;try{c=await s.forkSubagent({parent:this.ctx.parentSession,config:i,idPrefix:`skill-fork-${e.name}`,parentId:r.id,agentType:e.name});let l=n&&n.length>0?n:`Run the ${e.name} skill now, following the instructions in your system prompt.`,d=await c.runToResult(l);return d.status==="succeeded"&&d.message?{content:d.message.content}:d.status==="cancelled"&&typeof d.partialOutput=="string"&&d.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1138
1138
|
|
|
1139
1139
|
${d.partialOutput}`}:{content:d.error?.message??"Forked skill failed with no output",isError:!0}}catch(l){return{content:`Forked skill execution error: ${l instanceof Error?l.message:String(l)}`,isError:!0}}finally{c&&await c.teardown().catch(L),await a?.teardownAll(),await s.teardownAll()}}substituteSkillArgs(e,n){let r=n??"";return e.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(e,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=new F({parentAbortSignal:s.signal,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ce(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:a,childManager:c}=this.buildForkedChildConfig({model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},s.signal),l;try{l=await i.forkSubagent({parent:this.ctx.parentSession,config:a,idPrefix:`skill-${e}`,parentId:s.id,agentType:e});let d=o&&o.length>0?o:`Run the ${e} skill now, following the instructions in your system prompt.`,u=await l.runToResult(d);return u.status==="succeeded"&&u.message?{content:u.message.content}:u.status==="cancelled"&&typeof u.partialOutput=="string"&&u.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
@@ -1644,7 +1644,7 @@ Save reusable multi-step workflows the user teaches you or that you discover wor
|
|
|
1644
1644
|
`;process.stderr.write(c);return}let i=hb(e),a=yb(i);try{fb(a,{recursive:!0});let l=(!gb(i)?bb:"")+JSON.stringify(s)+`
|
|
1645
1645
|
`;mb(i,l)}catch(c){let l=`[prompt-dump] Failed to write to ${i}: ${String(c)}
|
|
1646
1646
|
`;process.stderr.write(l)}}B();$();var nr="anthropic-direct",Tb="claude-sonnet-4-5-20250929",Rb=t=>/opus-4-(7|[89])/.test(t),gl=null;var de=class{name=nr;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;mcpManager;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(e={}){let n=[..._e];if(e.subagentExecutor&&n.push(qe),e.skillExecutor&&n.push(ze),e.composeExecutor&&n.push(Ve),n.push(...Pe),n.push(he),this.memoryStore=e.memoryStore??new re,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){let r=Ln(e,n?.cwd),o=xt(this.memoryStore,void 0,this.surface);for(let[i,a]of o)r.set(i,a);if(n?.runtimeStateSource&&r.set("get_runtime_state",it(n.runtimeStateSource)),this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[i,a]of this._mcpHandlersCache)r.set(i,a)}let s=this._mcpToolsCache??[];return new Ae({handlers:r,schemas:[...this.schemas,...s],hookRegistry:this.hookRegistry,permissions:this.permissions,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{}})}close(){this.memoryStore.close()}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=$o.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=$o.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=$o.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=tt();Ab(xb(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});Eb(n,r+`
|
|
1647
|
-
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:_.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:_.ANTHROPIC_API_KEY||_.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${nr} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=gn(o),i=Ar(o,s,n.baseUrl),a=this.providerFactory??gl,c=a?a(i):new ml(i),l=r?null:As(s),d=Ib(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?ke(n.model)??n.model:Tb,p=Cb(n,u),h=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,m=Ot({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:nr,permissionMode:h,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof Ae?g.toolDefs.map(T=>T.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let T=n.sessionId,O=m.getWorkspace();Ft({sessionId:T,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:nr,name:u},workspace:O,pid:process.pid}),process.once("exit",()=>{Ee(T)}),process.once("SIGINT",()=>{Ee(T),process.exit(130)}),process.once("SIGTERM",()=>{Ee(T),process.exit(143)})}g=this.externalTools?Dt(this.externalTools,m):this.buildDispatcher(h,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:m});let w=g instanceof Ae?[...g.toolDefs]:[..._e,he],S=n.isSkillDispatch?w.filter(T=>T.name!=="ask_question"):w,y=this.skillExecutor?Yc():"",b=n.cwd||process.cwd(),A=n.isSkillDispatch?tr:`${tr}
|
|
1647
|
+
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:_.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:_.ANTHROPIC_API_KEY||_.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${nr} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=gn(o),i=Ar(o,s,n.baseUrl),a=this.providerFactory??gl,c=a?a(i):new ml(i),l=r?null:As(s),d=Ib(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?ke(n.model)??n.model:Tb,p=Cb(n,u),h=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,m=Ot({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:nr,permissionMode:h,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof Ae?g.toolDefs.map(T=>T.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let T=n.sessionId,O=m.getWorkspace();Ft({sessionId:T,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:nr,name:u},workspace:O,pid:process.pid}),process.once("exit",()=>{Ee(T)}),process.once("SIGINT",()=>{Ee(T),process.exit(130)}),process.once("SIGTERM",()=>{Ee(T),process.exit(143)})}g=this.externalTools?Dt(this.externalTools,m):this.buildDispatcher(h,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:m});let w=g instanceof Ae?[...g.toolDefs]:[..._e,he],S=n.isSkillDispatch?w.filter(T=>T.name!=="ask_question"&&T.name!=="terminal_font_size"):w,y=this.skillExecutor?Yc():"",b=n.cwd||process.cwd(),A=n.isSkillDispatch?tr:`${tr}
|
|
1648
1648
|
|
|
1649
1649
|
${Do}
|
|
1650
1650
|
|