agent-afk 3.53.4 → 3.53.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 CHANGED
@@ -1193,7 +1193,7 @@ ${c}`:c};return sy(d,t.prompt,a)}buildDispatcher(t,n){let r=ea(t,n.cwd),o=ts(thi
1193
1193
  `);continue}let l=await Cn.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Cn.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
1194
1194
  `)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}};function dy(e){return e.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function S0(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.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=t.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=t.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",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.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(!w0(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)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function aa(e){try{return Ie(e).catch(()=>{})}catch{return Promise.resolve()}}function Vr(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function my(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}var k0=4096,py=1024;function v0(e){if(e==null)return;let t=my(e);return t!==void 0&&t>k0?{truncated:!0,chars:t}:e}function T0(e){let t={status:e.status,error:Vr(e.errorMessage,py),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=Vr(e.schemaErrorMessage,py));let n=v0(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var jt=class e{constructor(t){this.ctx=t}ctx;getSubagentsLite(){let t=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:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=S0(t.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??Yr,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=Te(i)==="openai-compatible",l={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}:{}},c;if(this.ctx.childProviderFactory&&r<o){s=new X({parentAbortSignal:t.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),c=sr(t.signal);let g=new e({subagentManager:s,parentSession:c,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}:{}}),h=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;l.provider=this.ctx.childProviderFactory({childExecutor:g,...h!==void 0?{childSkillExecutor:h}:{},...l.model!==void 0?{model:l.model}:{}})}let u;try{u=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:l,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?dy(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":dy(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),c!==void 0&&(c.sessionId=u.id)}catch(g){let h=g instanceof Error?g.message:String(g);return aa({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Vr(h),depth:r}),{content:`Failed to fork subagent: ${h}`,isError:!0}}if(n.mode==="background"){let g=this.ctx.backgroundRegistry;if(!g)return await u.teardown().catch(y=>J("subagent-executor: handle teardown failed: "+(y instanceof Error?y.message:String(y)))),{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 h;try{h=g.register({handle:u,prompt:n.prompt,model:l.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(y){if(y instanceof gs)return await u.teardown().catch(w=>J("subagent-executor: handle teardown failed after cap error: "+(w instanceof Error?w.message:String(w)))),{content:y.message,isError:!0};throw y}let b={status:"running",jobId:h.jobId,subagentId:h.subagentId,label:h.label,message:`Background subagent started (jobId=${h.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${h.jobId} or ask the user to join.`};return{content:JSON.stringify(b)}}let d=()=>{u.cancel()};t.signal.addEventListener("abort",d,{once:!0});let p=Date.now(),f=this.ctx.parentSession.sessionId;try{let g=await u.runToResult(n.prompt);if(g.status==="succeeded"&&g.message){let w=g.message.content,k=typeof w=="string"?w:JSON.stringify(w),E=g.trace;return aa({event:"subagent.completed",subagent_id:u.id,parent_session_id:f,status:g.status,duration_ms:Date.now()-p,content_chars:k.length,depth:r,tool_call_count:E?.toolCalls.length,thinking_present:E?.thinkingPresent,tool_names:E?.toolCalls.length?JSON.stringify([...new Set(E.toolCalls.map(T=>T.name))]):void 0}),{content:k}}let h=g.error?.message??"Subagent failed with no output",b=g.trace;aa({event:"subagent.failed",subagent_id:u.id,id_prefix:n.id_prefix,parent_session_id:f,status:g.status,duration_ms:Date.now()-p,error_message:Vr(h),schema_error:g.schemaError?Vr(g.schemaError.message):void 0,partial_output_chars:my(g.partialOutput),depth:r,tool_call_count:b?.toolCalls.length,thinking_present:b?.thinkingPresent,tool_names:b?.toolCalls.length?JSON.stringify([...new Set(b.toolCalls.map(w=>w.name))]):void 0});let y=T0({status:g.status,errorMessage:h,schemaErrorMessage:g.schemaError?.message,partialOutput:g.partialOutput,subagentId:u.id});return{content:JSON.stringify(y),isError:!0}}catch(g){let h=g instanceof Error?g.message:String(g);throw aa({event:"subagent.failed",subagent_id:u.id,id_prefix:n.id_prefix,parent_session_id:f,status:"failed",duration_ms:Date.now()-p,error_message:Vr(h),depth:r}),g}finally{t.signal.removeEventListener("abort",d),await s?.teardownAll(),await u.teardown()}}};var fy=new Set;function gy(e){fy.add(e)}function hy(e){return fy.has(e)}var od=new Set,sd=new Set;function yy(e){od.add(e)}function by(e){od.delete(e)}function wy(e){sd.add(e)}function Sy(e){sd.delete(e)}function ky(e){for(let t of od)t(e)}function vy(e){for(let t of sd)t(e)}var E0=240;function x0(e,t=E0){return e.length<=t?e:e.slice(0,t)+"\u2026"}function R0(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function A0(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.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=t.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 Bt=class{constructor(t){this.ctx=t}ctx;pluginBodies=null;async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Yr;if(n>=r){let l=R0(t.input);return Ie({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=A0(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ue(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t);let a=or(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return this.executeForkedRegistrySkill(t,n,r);let o=hy(t.name);o&&vy(t.name);let s=this.ctx.depth??0;Ie({event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await t.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(u){a=u}finally{let u=Date.now()-i;o&&ky({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Ie({event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:x0(d)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}buildForkedChildConfig(t,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??Yr,s={...t};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new X({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),a=new jt({subagentManager:i,parentSession:sr(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}:{}}),l=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:a,...l!==void 0?{childSkillExecutor:l}:{},...s.model!==void 0?{model:s.model}:{}}),{childConfig:s,childManager:i}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=Se(t.name)["system.md"],!o)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(c){return{content:`Failed to load skill prompts: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let s=new X({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:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:i,childManager:a}=this.buildForkedChildConfig({model:t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),l;try{l=await s.forkSubagent({parent:this.ctx.parentSession,config:i,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let c=n&&n.length>0?n:"Run the skill.",u=await l.runToResult(c);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]
1195
1195
 
1196
- ${u.partialOutput}`}:{content:u.error?.message??"Forked skill failed with no output",isError:!0}}catch(c){return{content:`Forked skill execution error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}finally{l&&await l.teardown().catch(J),await a?.teardownAll(),await s.teardownAll()}}async executePluginSkill(t,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=new X({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:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:a,childManager:l}=this.buildForkedChildConfig({model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n,env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},s.signal),c;try{c=await i.forkSubagent({parent:this.ctx.parentSession,config:a,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let u=o&&o.length>0?o:"Run the skill.",d=await c.runToResult(u);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]
1196
+ ${u.partialOutput}`}:{content:u.error?.message??"Forked skill failed with no output",isError:!0}}catch(c){return{content:`Forked skill execution error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}finally{l&&await l.teardown().catch(J),await a?.teardownAll(),await s.teardownAll()}}substituteSkillArgs(t,n){let r=n??"";return t.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(t,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=new X({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:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:a,childManager:l}=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),c;try{c=await i.forkSubagent({parent:this.ctx.parentSession,config:a,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let u=o&&o.length>0?o:"Run the skill.",d=await c.runToResult(u);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]
1197
1197
 
1198
1198
  ${d.partialOutput}`}:{content:d.error?.message??"Plugin skill failed with no output",isError:!0}}catch(u){return{content:`Plugin skill execution error: ${u instanceof Error?u.message:String(u)}`,isError:!0}}finally{c&&await c.teardown().catch(J),await l?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=la(this.ctx.pluginConfigs)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}};var Yr=3;function sr(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}var _0=[...Dt,...st,"memory_search","agent","skill"];function Xr(e={}){return({childExecutor:t,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:_0},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{}};return Te(typeof r=="string"?r:void 0)==="openai-compatible"?new Et({...o,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{}}):new Le(o)}}function Zr(e,t,n,r,o,s,i){let a=(l,c,u)=>new Bt({parentSession:sr(u),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:l,maxDepth:c,childProviderFactory:n,childSkillExecutorFactory:a,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{}});return a}function Ty(e,t){let n={allowedTools:[...iy]};return Te(typeof t=="string"?t:void 0)==="openai-compatible"?new Et({permissions:n}):new Le({permissions:n})}function Ey(e){let t=C0(e);return t!==void 0?t:I0(e)}function C0(e){let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=t.exec(e))!==null;)n=r[1];if(n)return xy(n.trim())}function I0(e){for(let t=e.length-1;t>=0;t--){if(e[t]!=="}")continue;let n=P0(e,t);if(n===-1)continue;let r=e.slice(n,t+1),o=xy(r);if(o!==void 0)return o}}function P0(e,t){let n=0,r=!1,o=!1;for(let s=t;s>=0;s--){let i=e[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 xy(e){try{return JSON.parse(e)}catch{return}}function id(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function Ry(e,t,n,r,o){if(!r)return{id:e,status:t,message:n,trace:o};let s=Ey(n.content),i=r.safeParse(s);return i.success?{id:e,status:t,message:n,output:i.data,trace:o}:{id:e,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 Ay(e,t,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:e,status:t,error:o,trace:r}}function Ee(e){return`${e.status}${e.error?`: ${e.error.message}`:""}`}function _y(e,t){let n=e;return t.partialOutput!==void 0&&t.partialOutput!==null&&(n.partialOutput=t.partialOutput),t.subagentId!==void 0&&(n.subagentId=t.subagentId),n}var ca=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,f,g){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=id();lastStreamedContent="";get status(){return this.currentStatus}async run(t,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=ji(this.streamToFinalMessage(t,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",Xn(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?(Xn(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Xn(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(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=id();let s=n??this.progressSink??ft(),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(t)){if(s&&s(a,i),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.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 l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.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(t,n){try{let r=await this.run(t,n);return Ry(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Ay(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??ft();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{J("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Xn(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(t)}}async teardown(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Sg(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,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)J(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){J(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var M0=async(e,t)=>({action:"decline"}),X=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;abortGraph;rootId;rootController;counter=0;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentCwd=t.cwd,this.abortGraph=new Ni(t.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),t.parentAbortSignal){let n=t.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(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.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=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry;o&&await wg(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},hookRegistry:t.config.hookRegistry??this.hookRegistry,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!0?{onElicitation:M0}:{},...t.phaseRole==="read-only"?{provider:Ty("read-only",t.config.model)}:{}},a;try{a=new Ve(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??ft(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,f=new ca(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??Ui,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter);this.active.set(n,f);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return Xn(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await Ie({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),f}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}};async function ua(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}import{fileURLToPath as O0}from"node:url";import{dirname as $0}from"node:path";var D0=O0(import.meta.url),S5=$0(D0),at={name:"research-agent",systemPrompt:`---
1199
1199
  name: research-agent
@@ -2204,7 +2204,7 @@ _ended: ${new Date().toISOString()}_
2204
2204
  `)}function dB(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}function KT(e,t,n){let r=[];return n&&n.trim().length>0&&r.push({type:"text",text:n}),e&&r.push({type:"text",text:e}),Dl(r,t),r}async function GT(e,t,n,r,o="summary",s,i,a){let l=wk(e.text,e.attachments);r.setInFlight(!0);let c="",u=!1,d=!1,p=!1,f=!1,g,h=!1,b=!1,y=[],w=new Map,k=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,E=r.getCompositor?r.getCompositor():null,T=()=>new Co({out:Io(s),thinkingMode:o,...k?{activeSkillName:k}:{},onCancel:()=>{t.interrupt().catch(A=>{Be()&&console.error(" "+m.error("session.interrupt() failed:"),A)})},...i?{onBackground:()=>{h=!0}}:{},...a?.history?{history:a.history}:{},...a?.autocompleteState?{autocompleteState:a.autocompleteState}:{},...a?.promptText!==void 0?{promptText:a.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...E?{compositor:E}:{}}),C=T(),M=async()=>{if(!p){p=!0;try{await C.dispose()}catch{}}},R=async()=>{await C.arm();let A=C.getCompositor();if(s&&A){let I=A;s.fn=P=>I.commitAbove(P)}r.setActiveCompositor?.(A),r.setInterruptNotifier?.(I=>C.setInterrupting(I)),r.rearmStatus?.()};try{E?E.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0}),await R(),i&&r.setBackgroundHandler&&r.setBackgroundHandler(()=>{h=!0});let A=e.attachments.length===0?e.text:KT(e.text,e.attachments),I=t.sendMessageStream(A);if(await Br((x,_)=>{C.process(x,_)},async()=>{for await(let x of I){if(b){t.interrupt().catch(_=>{Be()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),_)});break}if(h&&i){let _=k??e.text.slice(0,40),O=i.register(_),N=nl(O,i);rl(I,c,l,O,i,N,n,r.onTurnComplete,t.abortSignal),await M(),(s??{fn:console.log}).fn(m.dim(` \u2192 backgrounded as ${O.id}: ${O.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(x.type==="chunk"&&x.chunk.type==="content"?(c+=x.chunk.content,u=!0):x.type==="message"&&!u&&(c=x.message.content),x.type==="chunk"&&x.chunk.type==="tool_use_detail"){let _=x.chunk,O={toolName:_.toolName,toolUseId:_.toolUseId,input:_.toolInput};w.set(_.toolUseId,O),y.push(O)}else if(x.type==="chunk"&&x.chunk.type==="tool_result"){let _=x.chunk,O=w.get(_.toolUseId);O&&(O.result=_.content,O.isError=_.isError,w.delete(_.toolUseId))}if(x.type==="paused"){await M(),(s??{fn:console.log}).fn(Jf({reason:x.reason,...x.resetsAt!==void 0?{resetsAt:x.resetsAt}:{},...x.accountId!==void 0?{accountId:x.accountId}:{},...x.autoResume!==void 0?{autoResume:x.autoResume}:{}}));continue}if(x.type==="resumed"){let _=x.hotSwapped&&x.accountId?`\u25B6 Resumed on ${x.accountId}`:"\u25B6 Resumed";c="",u=!1,y.length=0,w.clear(),f=!1,g=void 0,d=!1,h=!1,C=T(),p=!1,await R(),(s??{fn:console.log}).fn(m.success(_));continue}if(x.type==="error"){await M(),Nr(Lr(x.error)),d=!0;continue}C.process(x),x.type==="done"&&(f=!0,g=x.metadata)}}),await M(),b){let x=s?s.fn:console.log;x(m.warning("\u23F8 Stopped \u2014 work so far kept.")+m.dim(" Use /resume or --resume to continue.")),x("")}if(f&&!b){ar(n,l,c,g,y),r.onTurnComplete&&await r.onTurnComplete(l,c).catch(()=>{}),Wa(process.stdout);let x=O=>{s?s.fn(O):console.log(O)},_=WT(c);if(_&&(x(HT(_)),x(""),r.onTerminalState))try{r.onTerminalState(_)}catch{}if(pB(g,n,x),r.onAfterTurn){let O=r.onAfterTurn();O instanceof Promise&&await O.catch(()=>{})}}}catch(A){await M(),d||Nr(Lr(A))}finally{await M(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function pB(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(se(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Fe(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(te(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=qd(t),a=it(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);console.log(m.error(` context OVER ${c}k tok by ~${te(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?m.error:m.warning;n(l(` context ${Math.round(i*100)}% used of ${te(a)}`))}n("")}function zT(e={}){let t=e.load??Qa,n=e.onResize??(i=>ze.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=$S(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:el(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var fm={done:{glyph:"\u2713",color:m.success,label:"done"},blocked:{glyph:"\u2298",color:m.error,label:"blocked"},asking:{glyph:"?",color:m.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:m.meta,label:"interrupted"}};function qT(e={}){let t=Math.max(2,e.capacity??8),n=[];return{push(r){n.push(r.kind),n.length>t&&(n=n.slice(n.length-t))},reset(){n=[]},entries(){return n},render(){if(n.length===0)return null;let r=m.dim(" ledger "),o=m.dim(" \xB7 "),s=n.map(u=>{let d=fm[u];return d.color(`${d.glyph} ${d.label}`)}),i=m.dim(` (${n.length} turn${n.length===1?"":"s"})`),a=r+s.join(o)+i,l=Math.max(20,Y()-2);if(z(a)<=l)return a;let c=r+n.map(u=>fm[u].color(fm[u].glyph)).join(m.dim(" "))+i;return ce(c,l)}}}var gm=["\u25D0","\u25D1","\u25D2","\u25D3"],pc=class{stream;manager;registry;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;updateHandler=null;registryStartedHandler=null;registrySettledHandler=null;rowCount=0;onRowCountChange;constructor(t,n,r={}){this.manager=t,this.registry=n,this.stream=r.stream??process.stdout,this.throttleMs=r.throttleMs??200}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||(this.started=!0,this.updateHandler=()=>this.scheduleRepaint(),this.manager.on("update",this.updateHandler),this.manager.on("complete",this.updateHandler),this.registry&&(this.registryStartedHandler=t=>{this.scheduleRepaint()},this.registrySettledHandler=t=>{this.scheduleRepaint()},this.registry.on("started",this.registryStartedHandler),this.registry.on("settled",this.registrySettledHandler)),this.resizeUnsub=ze.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%gm.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.updateHandler&&(this.manager.removeListener("update",this.updateHandler),this.manager.removeListener("complete",this.updateHandler),this.updateHandler=null),this.registry&&(this.registryStartedHandler&&(this.registry.off("started",this.registryStartedHandler),this.registryStartedHandler=null),this.registrySettledHandler&&(this.registry.off("settled",this.registrySettledHandler),this.registrySettledHandler=null)),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=[...this.manager.running().map(s=>({kind:"turn",task:s})),...(this.registry?.list()??[]).filter(s=>s.status==="running").map(s=>({kind:"subagent",job:s}))],n=this.stream.rows??24,r=Math.max(0,Math.min(t.length,n-1));if(r!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=r,this.onRowCountChange?.(r)),r===0)return;let o=Math.max(1,n-r);this.stream.write("\x1B[s");for(let s=0;s<r;s++){let i=t[s],a=o+s;this.stream.write(`\x1B[${a};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatItemLine(i))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=Math.min(this.rowCount,t-1),r=Math.max(1,t-n);this.stream.write("\x1B[s");for(let o=0;o<n;o++)this.stream.write(`\x1B[${r+o};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}formatItemLine(t){return t.kind==="turn"?this.formatTaskLine(t.task):this.formatJobLine(t.job)}formatTaskLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=m.brand(gm[this.spinnerIndex]),o=m.dim(t.id),s=m.bold(t.label),i=[r,o,s];t.progressDescription&&i.push(m.dim(t.progressDescription));let a=[];t.stats.toolUses>0&&a.push(`${t.stats.toolUses} tool${t.stats.toolUses===1?"":"s"}`),t.stats.tokens>0&&a.push(`${te(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return a.push(se(l)),a.length>0&&i.push(m.dim(a.join(" \xB7 "))),ce(" "+i.join(" "),n)}formatJobLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=m.brand(gm[this.spinnerIndex]),o=m.dim(t.jobId),s=m.bold(t.label||t.jobId),i=[r,o,s],a=Date.now()-t.startedAt;return i.push(m.dim(se(a))),ce(" "+i.join(" "),n)}};function mc(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function JT(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async p=>{Be()&&(o=Va(p)),await jl(e.session.current),Be()&&(s=zv())}).catch(()=>{});let i=await DT(),a=new dc({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d;try{await a.armCompositor({promptFn:()=>mc(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let y=e.slashCtx;y.stats.planMode&&y.stats.pendingPlanExit?(y.stats.pendingPlanExit=!1,Rt(y,!1,{closureSummarySkipped:!0}).catch(()=>{})):Rt(y).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{}});let p=a.getCompositor();Ft.install(Ka({readLine:y=>a.readLine({promptFn:()=>y}).then(w=>w.text),writer:{line:(y="")=>{let w=a.getCompositor();w?w.commitAbove(y):process.stdout.write(y+`
2205
2205
  `)}},pendingCount:()=>Ft.pendingCount(),...p?{pickFromList:y=>jT(p,y),readTextOverlay:y=>BT(p,y)}:{}})),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor();let f=a.getCompositor();if(f){let y=w=>f.commitAbove(w);e.completionWriter.fn=y,e.completionWriter.idleFn=y}e.slashCtx.setSoftStopHandler=y=>a.setSoftStopHandler(y),e.inputSurfaceRef&&(e.inputSurfaceRef.current=a),c=zT();let g=qT();e.clearVerdictLedger=()=>g.reset(),u=new tl,GS(u),XS(u),ek(u),ZS(e.backgroundRegistry),d=new pc(u,e.backgroundRegistry),d.setRowCountChangeHandler(y=>{e.statusLine.setExtraRows(y)}),d.start();let h=50,b=[];for(u.on("complete",y=>{b.length>=h&&b.shift(),b.push(y)});;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let R of s)e.replRenderer.writeLine(R);e.replRenderer.writeLine(""),s=[]}for(;b.length>0;){let R=b.shift(),A=R.status==="succeeded"?"\u2713":"\u2717",I=[];if(R.resultText){let x=R.resultText.trim().split(`
2206
2206
  `)[0]?.slice(0,80)??"";x&&I.push(x)}R.error&&I.push(R.error.message);let P=[R.stats.toolUses>0?`${R.stats.toolUses} tools`:"",R.stats.tokens>0?`${Math.round(R.stats.tokens/1e3)}k tok`:"",R.stats.durationMs>0?`${Math.round(R.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");P&&I.push(P),e.replRenderer.writeLine(kn({kind:R.status==="succeeded"?"checkpoint":"diagnosis",title:`${A} ${R.id} ${R.label}`,body:I})),e.replRenderer.writeLine("")}let y=c.renderIfChanged(e.stats.sessionId);if(y.length>0){for(let R of y)e.replRenderer.writeLine(R);e.replRenderer.writeLine("")}let w=g.render();w&&e.replRenderer.writeLine(w);let k,E;if(l!==void 0){let R=l;l=void 0;let A=mc(e.stats.model,e.stats.planMode),I=dr({buffer:R.text,promptText:A,isTTY:!!process.stdout.isTTY,attachmentSummary:vo([...R.attachments])});e.replRenderer.writeLine(I),k=R.text.trim(),E=R.attachments}else{let R=await a.readLine({promptFn:()=>mc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let A=e.slashCtx;A.stats.planMode&&A.stats.pendingPlanExit?(A.stats.pendingPlanExit=!1,Rt(A,!1,{closureSummarySkipped:!0}).catch(()=>{})):Rt(A).catch(()=>{}),e.statusLine.rearm()}});k=R.text.trim(),E=R.attachments}if(!k&&E.length===0)continue;let T=!1;if(k.startsWith("/")){let R=await dS(k,e.slashCtx,E);if(R.handled){if(R.result==="exit"){e.rl.close();return}if((k==="/clear"||k.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),g.reset()),R.result!==null&&typeof R.result=="object"&&"kind"in R.result&&R.result.kind==="submit"){l={text:R.result.message,attachments:E??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}T=!0}i.push(k);let C=k;if(T){let R=zd(k);if(R){let A=R.name.replace(/^\//,"").split(":").pop()??"";if(A&&Kp(A)){let I={skillName:A,rawArgs:R.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},P=e.session.current.sessionId,x=Sr(P),_=Date.now();J(`[afk trace] preflight.start commandName=${A}`);let O=!1,N=await wr(I,{cwd:e.stats.cwd??process.cwd(),artifactDir:x},K=>{Be()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${A}) failed: `)+(K instanceof Error?K.message:String(K)))});O=N!==null,J(`[afk trace] preflight.end commandName=${A} durationMs=${Date.now()-_} success=${O}`),C=qp(N?.manifestBlock,k)}}}let M;if(e.firstTurnHook&&e.stats.totalTurns===0){let R=e.firstTurnHook;e.firstTurnHook=void 0,M=Promise.resolve().then(()=>R(k)).catch(A=>{e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(A instanceof Error?A.message:String(A)))})}await GT({text:C,attachments:E},e.session.current,e.stats,{setInFlight(R){n.turnInFlight=R},async onTurnComplete(R,A){await t.appendTurn(R,A)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await xS(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:R=>g.push(R),setActiveCompositor:R=>{n.activeCompositor=R},setInterruptNotifier:R=>{n.notifyInterrupting=R},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:R=>a.setBackgroundHandler(R),setSoftStopHandler:R=>a.setSoftStopHandler(R)},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(mc(e.stats.model,e.stats.planMode))),M!==void 0&&await M}}finally{if(u!==void 0)for(let f of u.running())u.cancel(f.id);d?.stop(),c?.dispose();let p=f=>console.log(f);e.completionWriter.fn=p,e.completionWriter.idleFn=p,await a.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}import{execFile as mB}from"node:child_process";import{dirname as fB,isAbsolute as gB,resolve as hB}from"node:path";import{promisify as yB}from"node:util";var VT=yB(mB),bB=3e3,wB=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function SB(){let t=(await VT("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=gB(t)?t:hB(process.cwd(),t);return fB(n)}async function YT(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await SB()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),bB)});try{let o=Gt({execFile:VT,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=>wB.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as kB}from"node:fs";import{dirname as vB,join as TB}from"node:path";import{randomBytes as EB}from"node:crypto";var xB=["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(`
2207
- `),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,RB=1024,AB=8e3,_B="haiku";async function CB(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=OB(n,RB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??AB),i=t.signal?$B([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await tc({token:t.token,model:t.model??_B,system:xB,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=IB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vB(t.worktreePath);return await PB(l,c)}function IB(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XT.test(t)&&t.length<=hm)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>hm)break;o=i}return XT.test(o)?o:null}async function PB(e,t){if(!await MB(TB(t,e)))return e;let n=EB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function MB(e){try{return await kB.access(e),!0}catch{return!1}}function OB(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 $B(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 QT(e){let t,n,r=await CB(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(i,a)=>{t=i,n=a}});if(r===null)return{status:"skipped",reason:t??"unknown",...n!==void 0?{detail:n}:{}};let s=await(e.renameFn??bb)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ZT(s.newPath),{status:"renamed",oldPath:s.oldPath,newPath:s.newPath,oldBranch:s.oldBranch,newBranch:s.newBranch}):(s.partial==="branch"&&(e.session&&e.session.setCwd(e.handle.path),ZT(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ZT(e){try{process.chdir(e)}catch{}}j();import{spawn as eE}from"child_process";import{existsSync as UB,mkdirSync as jB,readFileSync as tE,unlinkSync as BB,writeFileSync as WB}from"fs";import{get as HB}from"https";import{join as nE}from"path";import{readFileSync as DB}from"fs";import{dirname as LB,join as FB}from"path";import{fileURLToPath as NB}from"url";function mn(){try{return"3.53.4"}catch{}try{let e=LB(NB(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(DB(FB(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}H();var KB=64*1024,GB=1440*60*1e3,zB="update-check.json",qB="pending-update.json";function rE(){return nE(ki(),zB)}function ym(){return nE(ki(),qB)}function oE(){let e=ki();UB(e)||jB(e,{recursive:!0})}function JB(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 VB(){try{let e=tE(rE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function YB(){try{oE();let e=`
2207
+ `),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,RB=1024,AB=8e3,_B="haiku";async function CB(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=OB(n,RB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??AB),i=t.signal?$B([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await tc({token:t.token,model:t.model??_B,system:xB,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=IB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vB(t.worktreePath);return await PB(l,c)}function IB(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XT.test(t)&&t.length<=hm)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>hm)break;o=i}return XT.test(o)?o:null}async function PB(e,t){if(!await MB(TB(t,e)))return e;let n=EB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function MB(e){try{return await kB.access(e),!0}catch{return!1}}function OB(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 $B(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 QT(e){let t,n,r=await CB(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(i,a)=>{t=i,n=a}});if(r===null)return{status:"skipped",reason:t??"unknown",...n!==void 0?{detail:n}:{}};let s=await(e.renameFn??bb)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ZT(s.newPath),{status:"renamed",oldPath:s.oldPath,newPath:s.newPath,oldBranch:s.oldBranch,newBranch:s.newBranch}):(s.partial==="branch"&&(e.session&&e.session.setCwd(e.handle.path),ZT(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ZT(e){try{process.chdir(e)}catch{}}j();import{spawn as eE}from"child_process";import{existsSync as UB,mkdirSync as jB,readFileSync as tE,unlinkSync as BB,writeFileSync as WB}from"fs";import{get as HB}from"https";import{join as nE}from"path";import{readFileSync as DB}from"fs";import{dirname as LB,join as FB}from"path";import{fileURLToPath as NB}from"url";function mn(){try{return"3.53.5"}catch{}try{let e=LB(NB(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(DB(FB(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}H();var KB=64*1024,GB=1440*60*1e3,zB="update-check.json",qB="pending-update.json";function rE(){return nE(ki(),zB)}function ym(){return nE(ki(),qB)}function oE(){let e=ki();UB(e)||jB(e,{recursive:!0})}function JB(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 VB(){try{let e=tE(rE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function YB(){try{oE();let e=`
2208
2208
  const https = require('https');
2209
2209
  const fs = require('fs');
2210
2210
  const url = 'https://registry.npmjs.org/agent-afk/latest';
package/dist/telegram.mjs CHANGED
@@ -1136,7 +1136,7 @@ ${d.content}`,isError:!0,...d.truncated===!0?{truncated:!0}:{}}),i.push({call:l,
1136
1136
  ${l}`:l};return _a(u,e.prompt,a)}buildDispatcher(e,n){let r=On(e,n.cwd),o=vt(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[a,c]of o)r.set(a,c);n.runtimeStateSource&&r.set("get_runtime_state",rt(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[a,c]of this.providerOpts.mcpManager.getMcpHandlers())r.set(a,c);let i={handlers:r,schemas:[...this.schemas,...s]};return this.providerOpts.hookRegistry!==void 0&&(i.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(i.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(i.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(i.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(i.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(i.cwd=n.cwd),n.readRoots!==void 0&&(i.readRoots=n.readRoots),n.writeRoots!==void 0&&(i.writeRoots=n.writeRoots),n.sessionId!==void 0&&(i.sessionId=n.sessionId),n.traceWriter!==void 0&&(i.traceWriter=n.traceWriter),new ve(i)}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=ao.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=ao.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=ao.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();Nm($m(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});Lm(n,r+`
1137
1137
  `)}catch{}}close(){this.memoryStore.close()}},Um=new ye;var Bm=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search"]),Hm=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size"]),jm=new Set(["Bash","BashOutput","KillBash","bash"]),Ea=new Set(["Agent","Task","agent"]),Aa=new Set(["Skill","skill"]),xa=new Set(["Compose","compose"]),fA=new Set([...Ea,...xa,...Aa]),Wm=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),Km=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),Gm=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),qm=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Oe(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var Ta=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...Ce];function Ra(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Oe(Bm,t)?"read":Oe(Hm,t)?"write":Oe(jm,t)?"shell":Oe(Ea,t)?"subagent":Oe(Aa,t)?"skill":Oe(xa,t)?"dag":Oe(Wm,t)?"web":Km.has(t)?"browser":Oe(Gm,t)?"planning":qm.has(t)?"schedule":"other"}import{isAbsolute as Jm}from"node:path";U();U();var AA=300*1e3;var Fn=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 Ia(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function Ym(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(!Jm(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 Ln(t){try{return Y(t).catch(()=>{})}catch{return Promise.resolve()}}function ct(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Ca(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}var Xm=4096,Pa=1024;function Qm(t){if(t==null)return;let e=Ca(t);return e!==void 0&&e>Xm?{truncated:!0,chars:e}:t}function Zm(t){let e={status:t.status,error:ct(t.errorMessage,Pa),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=ct(t.schemaErrorMessage,Pa));let n=Qm(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var lt=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=Ym(e.input)}catch(m){return{content:`Agent tool input validation failed: ${m instanceof Error?m.message:String(m)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??dt,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=Q(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 D({parentAbortSignal:e.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),l=Nt(e.signal);let m=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}:{}}),f=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;c.provider=this.ctx.childProviderFactory({childExecutor:m,...f!==void 0?{childSkillExecutor:f}:{},...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"?Ia(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Ia(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),l!==void 0&&(l.sessionId=d.id)}catch(m){let f=m instanceof Error?m.message:String(m);return Ln({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:ct(f),depth:r}),{content:`Failed to fork subagent: ${f}`,isError:!0}}if(n.mode==="background"){let m=this.ctx.backgroundRegistry;if(!m)return await d.teardown().catch(b=>F("subagent-executor: handle teardown failed: "+(b instanceof Error?b.message:String(b)))),{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 f;try{f=m.register({handle:d,prompt:n.prompt,model:c.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(b){if(b instanceof Fn)return await d.teardown().catch(S=>F("subagent-executor: handle teardown failed after cap error: "+(S instanceof Error?S.message:String(S)))),{content:b.message,isError:!0};throw b}let w={status:"running",jobId:f.jobId,subagentId:f.subagentId,label:f.label,message:`Background subagent started (jobId=${f.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${f.jobId} or ask the user to join.`};return{content:JSON.stringify(w)}}let u=()=>{d.cancel()};e.signal.addEventListener("abort",u,{once:!0});let p=Date.now(),g=this.ctx.parentSession.sessionId;try{let m=await d.runToResult(n.prompt);if(m.status==="succeeded"&&m.message){let S=m.message.content,y=typeof S=="string"?S:JSON.stringify(S),h=m.trace;return Ln({event:"subagent.completed",subagent_id:d.id,parent_session_id:g,status:m.status,duration_ms:Date.now()-p,content_chars:y.length,depth:r,tool_call_count:h?.toolCalls.length,thinking_present:h?.thinkingPresent,tool_names:h?.toolCalls.length?JSON.stringify([...new Set(h.toolCalls.map(v=>v.name))]):void 0}),{content:y}}let f=m.error?.message??"Subagent failed with no output",w=m.trace;Ln({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:m.status,duration_ms:Date.now()-p,error_message:ct(f),schema_error:m.schemaError?ct(m.schemaError.message):void 0,partial_output_chars:Ca(m.partialOutput),depth:r,tool_call_count:w?.toolCalls.length,thinking_present:w?.thinkingPresent,tool_names:w?.toolCalls.length?JSON.stringify([...new Set(w.toolCalls.map(S=>S.name))]):void 0});let b=Zm({status:m.status,errorMessage:f,schemaErrorMessage:m.schemaError?.message,partialOutput:m.partialOutput,subagentId:d.id});return{content:JSON.stringify(b),isError:!0}}catch(m){let f=m instanceof Error?m.message:String(m);throw Ln({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:"failed",duration_ms:Date.now()-p,error_message:ct(f),depth:r}),m}finally{e.signal.removeEventListener("abort",u),await s?.teardownAll(),await d.teardown()}}};var eg=new Set;function Ma(t){return eg.has(t)}var tg=new Set,ng=new Set;function Oa(t){for(let e of tg)e(t)}function Da(t){for(let e of ng)e(t)}var rg=240;function og(t,e=rg){return t.length<=e?t:t.slice(0,e)+"\u2026"}function sg(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 ig(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 ut=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??dt;if(n>=r){let c=sg(e.input);return Y({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=ig(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=we(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=Ve(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=Ma(e.name);o&&Da(e.name);let s=this.ctx.depth??0;Y({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&&Oa({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;Y({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:og(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??dt,s={...e};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new D({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),a=new lt({subagentManager:i,parentSession:Nt(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=W(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 D({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:ae(),...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 skill.",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
- ${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(F),await a?.teardownAll(),await s.teardownAll()}}async executePluginSkill(e,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=new D({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:ae(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:a,childManager:c}=this.buildForkedChildConfig({model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n,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 skill.",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]
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(F),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 D({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:ae(),...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 skill.",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]
1140
1140
 
1141
1141
  ${u.partialOutput}`}:{content:u.error?.message??"Plugin skill failed with no output",isError:!0}}catch(d){return{content:`Plugin skill execution error: ${d instanceof Error?d.message:String(d)}`,isError:!0}}finally{l&&await l.teardown().catch(F),await c?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Nn(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}};var dt=3;function Nt(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var ag=[...Tt,...Ce,"memory_search","agent","skill"];function Fa(t={}){return({childExecutor:e,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:ag},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{}};return Q(typeof r=="string"?r:void 0)==="openai-compatible"?new ye({...o,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}}):new le(o)}}function La(t,e,n,r,o,s,i){let a=(c,l,d)=>new ut({parentSession:Nt(d),defaultModel:t,apiKey:e,...r!==void 0?{baseUrl:r}:{},depth:c,maxDepth:l,childProviderFactory:n,childSkillExecutorFactory:a,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{}});return a}function Na(t,e){let n={allowedTools:[...Ta]};return Q(typeof e=="string"?e:void 0)==="openai-compatible"?new ye({permissions:n}):new le({permissions:n})}function $a(t){let e=cg(t);return e!==void 0?e:lg(t)}function cg(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return Ua(n.trim())}function lg(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=dg(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=Ua(r);if(o!==void 0)return o}}function dg(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 Ua(t){try{return JSON.parse(t)}catch{return}}function lo(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function Ba(t,e,n,r,o){if(!r)return{id:t,status:e,message:n,trace:o};let s=$a(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 Ha(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function q(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}function ja(t,e){let n=t;return e.partialOutput!==void 0&&e.partialOutput!==null&&(n.partialOutput=e.partialOutput),e.subagentId!==void 0&&(n.subagentId=e.subagentId),n}var $n=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=lo();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=bn(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",Be(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?(Be(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Be(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=lo();let s=n??this.progressSink??ae(),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 Ba(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Ha(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??ae();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{F("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",Be(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 zs(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)F(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){F(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var ug=async(t,e)=>({action:"decline"}),D=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 hn(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;o&&await qs(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:e.config.hookRegistry??this.hookRegistry,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!0?{onElicitation:ug}:{},...e.phaseRole==="read-only"?{provider:Na("read-only",e.config.model)}:{}},a;try{a=new Ie(i)}catch(f){throw this.abortGraph.dispose(n),f}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??ae(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,g=new $n(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??yn,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 Be(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:m,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await Y({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 Un(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 pg}from"node:url";import{dirname as fg}from"node:path";var mg=pg(import.meta.url),Ix=fg(mg),oe={name:"research-agent",systemPrompt:`---
1142
1142
  name: research-agent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "3.53.4",
3
+ "version": "3.53.5",
4
4
  "description": "CLI tool for interacting with AI agents via multiple interfaces",
5
5
  "main": "dist/index.mjs",
6
6
  "type": "module",