agent-afk 3.30.1 → 3.30.2
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 +4 -4
- package/dist/telegram.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1936,11 +1936,11 @@ Never end a turn mid-loop without one of these. The terminal-state heading must
|
|
|
1936
1936
|
`)}finally{h&&await h.close().catch(()=>{})}}async function d(){let h=await e.readMeta(t);if(!h||!(h.status!=="running"))return!1;try{let y=await $e.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await $e.stat(r)).size}catch{}if(await d())return;let p=null,f=null,g=()=>new Promise(h=>{f=h;let b=setTimeout(()=>{f=null,h()},c);p=()=>{clearTimeout(b),f=null,h()}});try{l=Wr.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{f?.(),l?.close()}}};N();var f0=300*1e3,cy=4096;function Ru(e){Ae(e).catch(()=>{})}var uy=5e3,g0=10,Xo=class extends Error{constructor(t,n){super(`Background job cap reached (${t}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}},Gi=class extends p0{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??g0,setTimeout(()=>this._sweepOldJobs().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
|
|
1937
1937
|
`)),5e3).unref()}register(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new Xo(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=t.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(d=>{i=d}),l={jobId:r,subagentId:t.handle.id,label:o,model:t.model,startedAt:s,status:"running",handle:t.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",parentSessionId:t.parentSessionId};this.jobs.set(r,l),vr(this.traceWriter,{transition:"started",jobId:r,subagentId:t.handle.id,label:o,model:t.model}),this.emit("started",this.snapshot(l));let c=new Ki(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:m0("sha256").update(t.prompt).digest("hex"),model:t.model,startedAt:s,status:"running",...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},schemaVersion:1};return c.writeMeta(u),t.handle.runInBackground(t.prompt,d=>{this.markTerminal(r,d,c,u)},d=>{c.write(d),d.type==="chunk"&&d.chunk.type==="content"&&this.appendTranscript(r,d.chunk.content)}),this.snapshot(l)}get(t){let n=this.jobs.get(t);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(t=>this.snapshot(t))}async join(t){let n=this.jobs.get(t);if(!n)throw new Error(`Background job not found: "${t}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return vr(this.traceWriter,{transition:"joined",jobId:t,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}async cancelJob(t){let n=this.jobs.get(t);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelAll(){let t=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of t)n.cancelSource="cascade";await Promise.allSettled(t.map(n=>n.handle.cancel())),await Promise.allSettled(t.map(n=>{let r=new Promise(o=>setTimeout(()=>{console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${uy}ms \u2014 continuing teardown`),o()},uy).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(t,n){let r=this.jobs.get(t);if(!r)return;let o=r.transcriptTail+n;o.length<=cy?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-cy)}getTranscript(t){return this.jobs.get(t)?.transcriptTail}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}markTerminal(t,n,r,o){let s=this.jobs.get(t);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let l=n.message?.content,c=typeof l=="string"?l:l!==void 0?JSON.stringify(l):"";vr(this.traceWriter,{transition:"completed",jobId:t,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(c,"utf8")}),Ru({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:c.length}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let l=n.error;vr(this.traceWriter,{transition:"failed",jobId:t,subagentId:s.subagentId,durationMs:i,errorClass:l?.name??"Error",errorMessage:l?.message??"unknown"}),Ru({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:l?.message}),this.emit("settled",this.snapshot(s))}else vr(this.traceWriter,{transition:"cancelled",jobId:t,subagentId:s.subagentId,source:s.cancelSource??"explicit"}),Ru({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let l=s.status,c=s.endedAt;r.writeMeta({...o,status:l,...c!==void 0?{endedAt:c}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(t)},f0).unref()}async _sweepOldJobs(){let n=To(),r;try{r=await hn.readdir(n)}catch{return}for(let o of r){let s=$n(o),i=dy.join(s,"meta.json");try{if(!(await hn.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
|
|
1938
1938
|
`);continue}let l=await hn.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await hn.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
|
|
1939
|
-
`)}}}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}:{}}}};var py=new Set;function my(e){py.add(e)}function fy(e){return py.has(e)}var Cu=new Set,_u=new Set;function gy(e){Cu.add(e)}function hy(e){Cu.delete(e)}function yy(e){_u.add(e)}function by(e){_u.delete(e)}function ky(e){for(let t of Cu)t(e)}function wy(e){for(let t of _u)t(e)}var h0=240;function y0(e,t=h0){return e.length<=t?e:e.slice(0,t)+"\u2026"}function b0(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 k0(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 yn=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??Hr;if(n>=r){let l=b0(t.input);return Ae({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=k0(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Le(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=Gn(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=fy(t.name);o&&wy(t.name);let s=this.ctx.depth??0;Ae({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;Ae({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:y0(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??Hr,s={...t};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new J({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}}),a=new bn({subagentManager:i,parentSession:Qo(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}),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=be(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 J({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:ct()}),{childConfig:i,childManager:a}=this.buildForkedChildConfig({model:t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,...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]
|
|
1939
|
+
`)}}}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}:{}}}};var py=new Set;function my(e){py.add(e)}function fy(e){return py.has(e)}var Cu=new Set,_u=new Set;function gy(e){Cu.add(e)}function hy(e){Cu.delete(e)}function yy(e){_u.add(e)}function by(e){_u.delete(e)}function ky(e){for(let t of Cu)t(e)}function wy(e){for(let t of _u)t(e)}var h0=240;function y0(e,t=h0){return e.length<=t?e:e.slice(0,t)+"\u2026"}function b0(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 k0(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 yn=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??Hr;if(n>=r){let l=b0(t.input);return Ae({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=k0(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Le(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=Gn(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=fy(t.name);o&&wy(t.name);let s=this.ctx.depth??0;Ae({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;Ae({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:y0(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??Hr,s={...t};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new J({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}}),a=new bn({subagentManager:i,parentSession:Qo(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.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=be(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 J({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:ct()}),{childConfig:i,childManager:a}=this.buildForkedChildConfig({model:t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,...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]
|
|
1940
1940
|
|
|
1941
1941
|
${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(H),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 J({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:ct()}),{childConfig:a,childManager:l}=this.buildForkedChildConfig({model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n,env:{PLUGIN_ROOT:r},...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]
|
|
1942
1942
|
|
|
1943
|
-
${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(H),await l?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=Pi(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 Hr=3;function Qo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}var w0=[...ln,"agent","skill"];function qi(e={}){return({childExecutor:t,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:w0},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{}};return Re(typeof r=="string"?r:void 0)==="openai-compatible"?new _t({...o,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{}}):new He(o)}}function zi(e,t,n,r,o){let s=(i,a,l)=>new yn({parentSession:Qo(l),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:i,maxDepth:a,childProviderFactory:n,childSkillExecutorFactory:s,...o!==void 0?{traceWriter:o}:{}});return s}function Sy(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}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c}}function Ji(e){try{return Ae(e).catch(()=>{})}catch{return Promise.resolve()}}function Kr(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ty(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}var v0=4096,vy=1024;function T0(e){if(e==null)return;let t=Ty(e);return t!==void 0&&t>v0?{truncated:!0,chars:t}:e}function E0(e){let t={status:e.status,error:Kr(e.errorMessage,vy),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=Kr(e.schemaErrorMessage,vy));let n=T0(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var bn=class e{constructor(t){this.ctx=t}ctx;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??0,o=this.ctx.maxDepth??Hr,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=Re(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},c;if(this.ctx.childProviderFactory&&r<o){s=new J({parentAbortSignal:t.signal}),c=Qo(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}),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"?Sy(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Sy(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 Ji({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Kr(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=>H("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 Xo)return await u.teardown().catch(k=>H("subagent-executor: handle teardown failed after cap error: "+(k instanceof Error?k.message:String(k)))),{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 k=g.message.content,T=typeof k=="string"?k:JSON.stringify(k),x=g.trace;return Ji({event:"subagent.completed",subagent_id:u.id,parent_session_id:f,status:g.status,duration_ms:Date.now()-p,content_chars:T.length,depth:r,tool_call_count:x?.toolCalls.length,thinking_present:x?.thinkingPresent,tool_names:x?.toolCalls.length?JSON.stringify([...new Set(x.toolCalls.map(S=>S.name))]):void 0}),{content:T}}let h=g.error?.message??"Subagent failed with no output",b=g.trace;Ji({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:Kr(h),schema_error:g.schemaError?Kr(g.schemaError.message):void 0,partial_output_chars:Ty(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(k=>k.name))]):void 0});let y=E0({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 Ji({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:Kr(h),depth:r}),g}finally{t.signal.removeEventListener("abort",d),await s?.teardownAll(),await u.teardown()}}};K();N();import{randomUUID as z0}from"node:crypto";import{createHash as H0}from"crypto";import{mkdir as K0,open as G0,writeFile as q0}from"fs/promises";import{join as Dy}from"path";import{z as w}from"zod";var x0=w.object({phase:w.literal("started"),toolUseId:w.string(),name:w.string(),inputBytes:w.number().int().nonnegative(),subagentId:w.string().optional()}),A0=w.object({phase:w.literal("completed"),toolUseId:w.string(),name:w.string(),resultBytes:w.number().int().nonnegative(),isError:w.boolean(),truncated:w.boolean(),durationMs:w.number().nonnegative(),subagentId:w.string().optional()}),Ey=w.discriminatedUnion("phase",[x0,A0]),R0=w.enum(["PreToolUse","PostToolUse","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),xy=w.object({hookEvent:R0,decision:w.union([w.literal("block"),w.literal("approve"),w.undefined()]),reason:w.string().optional(),blockedTool:w.string().optional(),injectedContextBytes:w.number().int().nonnegative().optional()}),C0=w.object({transition:w.literal("started"),subagentId:w.string(),parentId:w.string(),model:w.string(),allowedTools:w.array(w.string()).readonly().optional(),systemPromptHash:w.string().optional()}),_0=w.object({transition:w.literal("succeeded"),subagentId:w.string(),durationMs:w.number().nonnegative(),turnCount:w.number().int().nonnegative(),totalCostUsd:w.number().nonnegative().optional(),outputBytes:w.number().int().nonnegative()}),I0=w.object({transition:w.literal("failed"),subagentId:w.string(),errorClass:w.string(),errorMessage:w.string(),partialOutputBytes:w.number().int().nonnegative()}),P0=w.object({transition:w.literal("cancelled"),subagentId:w.string(),source:w.enum(["cascade","explicit"])}),Ay=w.discriminatedUnion("transition",[C0,_0,I0,P0]),M0=w.object({transition:w.literal("started"),jobId:w.string(),subagentId:w.string(),label:w.string(),model:w.string()}),$0=w.object({transition:w.literal("completed"),jobId:w.string(),subagentId:w.string(),durationMs:w.number().nonnegative(),outputBytes:w.number().int().nonnegative()}),O0=w.object({transition:w.literal("failed"),jobId:w.string(),subagentId:w.string(),durationMs:w.number().nonnegative(),errorClass:w.string(),errorMessage:w.string()}),D0=w.object({transition:w.literal("cancelled"),jobId:w.string(),subagentId:w.string(),source:w.enum(["explicit","cascade"])}),L0=w.object({transition:w.literal("joined"),jobId:w.string(),subagentId:w.string(),jobStatus:w.enum(["completed","failed","cancelled"])}),Ry=w.discriminatedUnion("transition",[M0,$0,O0,D0,L0]),Cy=w.object({kind:w.literal("monetary"),runningCostUsd:w.number().nonnegative(),maxBudgetUsd:w.number().nonnegative(),lastTurnCostUsd:w.number().nonnegative()}),F0=w.enum(["user_signal","cascade","timeout","budget","hook_block"]),_y=w.object({origin:F0,cascadedTo:w.array(w.string()).readonly(),reason:w.string().optional()}),Iy=w.enum(["manual","token_threshold","turn_count"]),N0=w.object({path:w.string(),sizeBytes:w.number().int().nonnegative(),sha256:w.string().regex(/^[0-9a-f]{64}$/)}),j0=w.object({trigger:Iy,preCompactionMessages:w.array(w.unknown()),summary:w.string(),keptTailCount:w.number().int().nonnegative(),keepLastNConfig:w.number().int().nonnegative(),messagesBefore:w.number().int().nonnegative(),messagesAfter:w.number().int().nonnegative(),tokensSavedEstimate:w.number().nonnegative().optional(),summarizationTokens:w.object({input:w.number().int().nonnegative(),output:w.number().int().nonnegative()}).optional()}),U0=w.object({trigger:Iy,preCompactionMessagesRef:N0,summary:w.string(),keptTailCount:w.number().int().nonnegative(),keepLastNConfig:w.number().int().nonnegative(),messagesBefore:w.number().int().nonnegative(),messagesAfter:w.number().int().nonnegative(),tokensSavedEstimate:w.number().nonnegative().optional(),summarizationTokens:w.object({input:w.number().int().nonnegative(),output:w.number().int().nonnegative()}).optional()}),B0=w.enum(["model_end_turn","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),Py=w.object({reason:B0,finalTurnCount:w.number().int().nonnegative(),finalCostUsd:w.number().nonnegative(),finalTokens:w.object({input:w.number().int().nonnegative().optional(),output:w.number().int().nonnegative().optional(),cacheRead:w.number().int().nonnegative().optional(),cacheCreation:w.number().int().nonnegative().optional()}),lastStopReason:w.string().optional()}),My=w.object({source:w.string(),assertion:w.string(),evidence:w.array(w.string()).readonly(),confidence:w.number().min(0).max(1),dissent:w.string().optional()}),W0=w.object({status:w.enum(["succeeded","failed","cancelled"]),finalCostUsd:w.number().nonnegative(),finalTurnCount:w.number().int().nonnegative(),closedAt:w.string().datetime()}),$y=w.discriminatedUnion("kind",[w.object({kind:w.literal("tool_call"),payload:Ey}),w.object({kind:w.literal("hook_decision"),payload:xy}),w.object({kind:w.literal("subagent_lifecycle"),payload:Ay}),w.object({kind:w.literal("background_agent"),payload:Ry}),w.object({kind:w.literal("budget"),payload:Cy}),w.object({kind:w.literal("abort"),payload:_y}),w.object({kind:w.literal("compaction"),payload:j0}),w.object({kind:w.literal("closure"),payload:Py}),w.object({kind:w.literal("claim"),payload:My})]),Oy=w.discriminatedUnion("kind",[w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("tool_call"),payload:Ey}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("hook_decision"),payload:xy}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("subagent_lifecycle"),payload:Ay}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("background_agent"),payload:Ry}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("budget"),payload:Cy}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("abort"),payload:_y}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("compaction"),payload:U0}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("closure"),payload:Py}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("claim"),payload:My}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("session_sealed"),payload:W0})]);var Vi=class{traceDir;tracePath;seq=0;sealed=!1;fh=null;writeQueue=Promise.resolve();constructor(t){this.traceDir=t.traceDir,this.tracePath=Dy(this.traceDir,"trace.jsonl")}getTracePath(){return this.tracePath}async write(t){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return $y.parse(t),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(t);await this.appendLine(n)})}async seal(t){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{await this.ensureOpen();let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:t};await this.appendLine(n),this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(t){let n=this.writeQueue.then(t,t);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await K0(this.traceDir,{recursive:!0}),this.fh=await G0(this.tracePath,"a"))}async closeHandle(){if(!this.fh)return;let t=this.fh;this.fh=null,await t.close()}async appendLine(t){if(!this.fh)throw new Error("NdjsonTraceWriter: file handle missing");await this.fh.appendFile(`${JSON.stringify(t)}
|
|
1943
|
+
${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(H),await l?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=Pi(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 Hr=3;function Qo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}var w0=[...ln,"agent","skill"];function qi(e={}){return({childExecutor:t,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:w0},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{}};return Re(typeof r=="string"?r:void 0)==="openai-compatible"?new _t({...o,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{}}):new He(o)}}function zi(e,t,n,r,o,s){let i=(a,l,c)=>new yn({parentSession:Qo(c),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:a,maxDepth:l,childProviderFactory:n,childSkillExecutorFactory:i,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{}});return i}function Sy(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}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c}}function Ji(e){try{return Ae(e).catch(()=>{})}catch{return Promise.resolve()}}function Kr(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ty(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}var v0=4096,vy=1024;function T0(e){if(e==null)return;let t=Ty(e);return t!==void 0&&t>v0?{truncated:!0,chars:t}:e}function E0(e){let t={status:e.status,error:Kr(e.errorMessage,vy),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=Kr(e.schemaErrorMessage,vy));let n=T0(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var bn=class e{constructor(t){this.ctx=t}ctx;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??0,o=this.ctx.maxDepth??Hr,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=Re(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},c;if(this.ctx.childProviderFactory&&r<o){s=new J({parentAbortSignal:t.signal}),c=Qo(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}),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"?Sy(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Sy(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 Ji({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Kr(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=>H("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 Xo)return await u.teardown().catch(k=>H("subagent-executor: handle teardown failed after cap error: "+(k instanceof Error?k.message:String(k)))),{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 k=g.message.content,T=typeof k=="string"?k:JSON.stringify(k),x=g.trace;return Ji({event:"subagent.completed",subagent_id:u.id,parent_session_id:f,status:g.status,duration_ms:Date.now()-p,content_chars:T.length,depth:r,tool_call_count:x?.toolCalls.length,thinking_present:x?.thinkingPresent,tool_names:x?.toolCalls.length?JSON.stringify([...new Set(x.toolCalls.map(S=>S.name))]):void 0}),{content:T}}let h=g.error?.message??"Subagent failed with no output",b=g.trace;Ji({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:Kr(h),schema_error:g.schemaError?Kr(g.schemaError.message):void 0,partial_output_chars:Ty(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(k=>k.name))]):void 0});let y=E0({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 Ji({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:Kr(h),depth:r}),g}finally{t.signal.removeEventListener("abort",d),await s?.teardownAll(),await u.teardown()}}};K();N();import{randomUUID as z0}from"node:crypto";import{createHash as H0}from"crypto";import{mkdir as K0,open as G0,writeFile as q0}from"fs/promises";import{join as Dy}from"path";import{z as w}from"zod";var x0=w.object({phase:w.literal("started"),toolUseId:w.string(),name:w.string(),inputBytes:w.number().int().nonnegative(),subagentId:w.string().optional()}),A0=w.object({phase:w.literal("completed"),toolUseId:w.string(),name:w.string(),resultBytes:w.number().int().nonnegative(),isError:w.boolean(),truncated:w.boolean(),durationMs:w.number().nonnegative(),subagentId:w.string().optional()}),Ey=w.discriminatedUnion("phase",[x0,A0]),R0=w.enum(["PreToolUse","PostToolUse","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),xy=w.object({hookEvent:R0,decision:w.union([w.literal("block"),w.literal("approve"),w.undefined()]),reason:w.string().optional(),blockedTool:w.string().optional(),injectedContextBytes:w.number().int().nonnegative().optional()}),C0=w.object({transition:w.literal("started"),subagentId:w.string(),parentId:w.string(),model:w.string(),allowedTools:w.array(w.string()).readonly().optional(),systemPromptHash:w.string().optional()}),_0=w.object({transition:w.literal("succeeded"),subagentId:w.string(),durationMs:w.number().nonnegative(),turnCount:w.number().int().nonnegative(),totalCostUsd:w.number().nonnegative().optional(),outputBytes:w.number().int().nonnegative()}),I0=w.object({transition:w.literal("failed"),subagentId:w.string(),errorClass:w.string(),errorMessage:w.string(),partialOutputBytes:w.number().int().nonnegative()}),P0=w.object({transition:w.literal("cancelled"),subagentId:w.string(),source:w.enum(["cascade","explicit"])}),Ay=w.discriminatedUnion("transition",[C0,_0,I0,P0]),M0=w.object({transition:w.literal("started"),jobId:w.string(),subagentId:w.string(),label:w.string(),model:w.string()}),$0=w.object({transition:w.literal("completed"),jobId:w.string(),subagentId:w.string(),durationMs:w.number().nonnegative(),outputBytes:w.number().int().nonnegative()}),O0=w.object({transition:w.literal("failed"),jobId:w.string(),subagentId:w.string(),durationMs:w.number().nonnegative(),errorClass:w.string(),errorMessage:w.string()}),D0=w.object({transition:w.literal("cancelled"),jobId:w.string(),subagentId:w.string(),source:w.enum(["explicit","cascade"])}),L0=w.object({transition:w.literal("joined"),jobId:w.string(),subagentId:w.string(),jobStatus:w.enum(["completed","failed","cancelled"])}),Ry=w.discriminatedUnion("transition",[M0,$0,O0,D0,L0]),Cy=w.object({kind:w.literal("monetary"),runningCostUsd:w.number().nonnegative(),maxBudgetUsd:w.number().nonnegative(),lastTurnCostUsd:w.number().nonnegative()}),F0=w.enum(["user_signal","cascade","timeout","budget","hook_block"]),_y=w.object({origin:F0,cascadedTo:w.array(w.string()).readonly(),reason:w.string().optional()}),Iy=w.enum(["manual","token_threshold","turn_count"]),N0=w.object({path:w.string(),sizeBytes:w.number().int().nonnegative(),sha256:w.string().regex(/^[0-9a-f]{64}$/)}),j0=w.object({trigger:Iy,preCompactionMessages:w.array(w.unknown()),summary:w.string(),keptTailCount:w.number().int().nonnegative(),keepLastNConfig:w.number().int().nonnegative(),messagesBefore:w.number().int().nonnegative(),messagesAfter:w.number().int().nonnegative(),tokensSavedEstimate:w.number().nonnegative().optional(),summarizationTokens:w.object({input:w.number().int().nonnegative(),output:w.number().int().nonnegative()}).optional()}),U0=w.object({trigger:Iy,preCompactionMessagesRef:N0,summary:w.string(),keptTailCount:w.number().int().nonnegative(),keepLastNConfig:w.number().int().nonnegative(),messagesBefore:w.number().int().nonnegative(),messagesAfter:w.number().int().nonnegative(),tokensSavedEstimate:w.number().nonnegative().optional(),summarizationTokens:w.object({input:w.number().int().nonnegative(),output:w.number().int().nonnegative()}).optional()}),B0=w.enum(["model_end_turn","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),Py=w.object({reason:B0,finalTurnCount:w.number().int().nonnegative(),finalCostUsd:w.number().nonnegative(),finalTokens:w.object({input:w.number().int().nonnegative().optional(),output:w.number().int().nonnegative().optional(),cacheRead:w.number().int().nonnegative().optional(),cacheCreation:w.number().int().nonnegative().optional()}),lastStopReason:w.string().optional()}),My=w.object({source:w.string(),assertion:w.string(),evidence:w.array(w.string()).readonly(),confidence:w.number().min(0).max(1),dissent:w.string().optional()}),W0=w.object({status:w.enum(["succeeded","failed","cancelled"]),finalCostUsd:w.number().nonnegative(),finalTurnCount:w.number().int().nonnegative(),closedAt:w.string().datetime()}),$y=w.discriminatedUnion("kind",[w.object({kind:w.literal("tool_call"),payload:Ey}),w.object({kind:w.literal("hook_decision"),payload:xy}),w.object({kind:w.literal("subagent_lifecycle"),payload:Ay}),w.object({kind:w.literal("background_agent"),payload:Ry}),w.object({kind:w.literal("budget"),payload:Cy}),w.object({kind:w.literal("abort"),payload:_y}),w.object({kind:w.literal("compaction"),payload:j0}),w.object({kind:w.literal("closure"),payload:Py}),w.object({kind:w.literal("claim"),payload:My})]),Oy=w.discriminatedUnion("kind",[w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("tool_call"),payload:Ey}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("hook_decision"),payload:xy}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("subagent_lifecycle"),payload:Ay}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("background_agent"),payload:Ry}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("budget"),payload:Cy}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("abort"),payload:_y}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("compaction"),payload:U0}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("closure"),payload:Py}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("claim"),payload:My}),w.object({ts:w.string().datetime(),seq:w.number().int().nonnegative(),kind:w.literal("session_sealed"),payload:W0})]);var Vi=class{traceDir;tracePath;seq=0;sealed=!1;fh=null;writeQueue=Promise.resolve();constructor(t){this.traceDir=t.traceDir,this.tracePath=Dy(this.traceDir,"trace.jsonl")}getTracePath(){return this.tracePath}async write(t){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return $y.parse(t),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(t);await this.appendLine(n)})}async seal(t){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{await this.ensureOpen();let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:t};await this.appendLine(n),this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(t){let n=this.writeQueue.then(t,t);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await K0(this.traceDir,{recursive:!0}),this.fh=await G0(this.tracePath,"a"))}async closeHandle(){if(!this.fh)return;let t=this.fh;this.fh=null,await t.close()}async appendLine(t){if(!this.fh)throw new Error("NdjsonTraceWriter: file handle missing");await this.fh.appendFile(`${JSON.stringify(t)}
|
|
1944
1944
|
`)}async materializePersistedEvent(t){let n=new Date().toISOString(),r=this.seq++;if(t.kind==="compaction"){let o=await this.persistCompactionSidecar(t.payload,r,n);return{ts:n,seq:r,kind:"compaction",payload:o}}return{ts:n,seq:r,kind:t.kind,payload:t.payload}}async persistCompactionSidecar(t,n,r){let o=r.replace(/[:.]/g,"-"),s=Dy(this.traceDir,`${String(n).padStart(6,"0")}-${o}-pre-compaction.json`),i=JSON.stringify(t.preCompactionMessages),a=Buffer.byteLength(i,"utf8"),l=H0("sha256").update(i).digest("hex");await q0(s,i,{encoding:"utf8",flag:"w"});let c={path:s,sizeBytes:a,sha256:l};return{trigger:t.trigger,preCompactionMessagesRef:c,summary:t.summary,keptTailCount:t.keptTailCount,keepLastNConfig:t.keepLastNConfig,messagesBefore:t.messagesBefore,messagesAfter:t.messagesAfter,...t.tokensSavedEstimate!==void 0?{tokensSavedEstimate:t.tokensSavedEstimate}:{},...t.summarizationTokens!==void 0?{summarizationTokens:t.summarizationTokens}:{}}}};function Yi(e={}){if(E.AFK_TRACE_DISABLED==="1")return null;let t=e.sessionLabel??z0(),n=Yp(t),r=new Vi({traceDir:n});return{writer:r,tracePath:r.getTracePath(),sessionLabel:t}}N();import{readFileSync as J0,writeFileSync as V0,existsSync as Xi,mkdirSync as Y0,readdirSync as X0,statSync as Q0,realpathSync as Ly}from"fs";import{join as Ny,basename as jy,resolve as Fy,sep as Z0}from"path";function Zo(){return tm(),Xt()}function eM(e){return Ny(Zo(),`${e}.json`)}function Iu(e,{write:t=!1}={}){let n=e.includes("/")?e:eM(e),r,o;if(!t&&Xi(n)?(r=Ly(n),o=Ly(Zo())):(r=Fy(n),o=Fy(Zo())),!r.startsWith(o+Z0)&&r!==o)throw new Error(`Session path escapes sessions directory: ${e}`);return r}function Gr(e,t){let n=Zo();Xi(n)||Y0(n,{recursive:!0});let r=t??e.sessionId??`session-${Date.now()}`,o={sessionId:e.sessionId,model:e.model,startedAt:e.sessionStartTime,savedAt:Date.now(),totalTurns:e.totalTurns,totalCostUsd:e.totalCostUsd,totalTokens:e.totalTokens,totalDurationMs:e.totalDurationMs,turns:e.turns},s=Iu(r,{write:!0});return V0(s,JSON.stringify(o,null,2)),s}function es(e){let t;try{t=Iu(e)}catch{return}if(Xi(t))try{let n=J0(t,"utf-8");return JSON.parse(n)}catch{return}}function qr(e){let t;try{t=Iu(e)}catch{return}let n=es(t);if(n)return{path:t,id:jy(t,".json"),data:n};for(let r of ts()){if(r.id!==e&&r.sessionId!==e)continue;let o=es(r.path);if(o)return{path:r.path,id:r.id,data:o}}}function ts(){let e=Zo();if(!Xi(e))return[];let t=[];for(let n of X0(e)){if(!n.endsWith(".json"))continue;let r=Ny(e,n);try{if(!Q0(r).isFile())continue;let s=es(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;t.push({path:r,id:jy(n,".json"),sessionId:s.sessionId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd})}catch{}}return t.sort((n,r)=>r.savedAt-n.savedAt),t}function Qi(e){if(e.resume&&e.continue)throw new Error("Use either --resume <id> or --continue, not both.");if(e.resume){let t=qr(e.resume);return t?{id:t.id,resumeId:t.data.sessionId??t.id,stored:t.data}:{id:e.resume,resumeId:e.resume}}if(e.continue){let t=ts()[0];if(!t)throw new Error("No saved sessions found for --continue. Run a session first or use /save.");let n=es(t.path);if(!n)throw new Error(`Could not load latest saved session: ${t.id}`);return{id:t.id,resumeId:n.sessionId??t.id,stored:n}}}function zr(e){return e?{resume:e.resumeId,sessionId:e.resumeId,...e.stored?{resumeHistory:e.stored.turns.map(t=>({user:t.user,assistant:t.assistant}))}:{}}:{}}function Zi(e){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:e,planMode:!1}}function Uy(e){e.totalTurns=0,e.totalCostUsd=0,e.totalTokens=0,e.totalDurationMs=0,e.sessionStartTime=Date.now(),e.turnCosts.length=0,e.turnTokens.length=0,e.turns.length=0,delete e.sessionId,delete e.pendingPlanExit}function Jn(e,t,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),c=a,u=l,d=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let g=p[p.length-1];if(g&&typeof g=="object"){let h=g;c=Number(h.input_tokens??0),u=Number(h.output_tokens??0),d=Number(h.cache_read_input_tokens??0)+Number(h.cache_creation_input_tokens??0)}}e.totalTurns+=1,e.totalCostUsd+=s,e.totalDurationMs+=i,e.totalTokens+=a+l,e.turnCosts.push(s),e.turnTokens.push({input:c,output:u,cache:d}),r?.sessionId&&!e.sessionId&&(e.sessionId=String(r.sessionId));let f={user:t,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return e.turns.push(f),f}function nM(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var Wy=10*1024*1024;function Hy(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>Wy){process.stdin.destroy(new Error(`stdin exceeds ${Wy}-byte limit`));return}n.push(s)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",s=>{process.stdin.removeListener("data",o),t(s)}),process.stdin.resume()})}function Ky(e,t){return new Promise((n,r)=>{let o=e.write(t,s=>{s?r(s):o&&n()});if(!o){let s=()=>{e.removeListener("error",i),n()},i=a=>{e.removeListener("drain",s),r(a)};e.once("drain",s),e.once("error",i)}})}function zy(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",We()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
|
|
1945
1945
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&(n.resume||n.continue)){process.stderr.write(`Error: --session-id is mutually exclusive with --resume and --continue
|
|
1946
1946
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&!nM(n.sessionId)){process.stderr.write(`Error: --session-id must be a UUID (got: ${n.sessionId})
|
|
@@ -2073,7 +2073,7 @@ ${XL(i)}
|
|
|
2073
2073
|
`),this.client=a,this.connected=!0,this.pendingAuthTransport=void 0;let l=await ml(this.client.listTools(),s,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${s}ms`),()=>a.close().catch(()=>{})),c=this.client.getServerVersion();return{tools:l.tools,serverInfo:c?{name:c.name,version:c.version}:void 0}}async listTools(){if(!this.client)throw new Error(`McpClient(${this.serverName}): not connected`);let t=this.config.timeout??_d;return(await ml(this.client.listTools(),t,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${t}ms`))).tools}async refreshTools(){return this.listTools()}async callTool(t,n,r){if(!this.client)return{content:`MCP server "${this.serverName}" is not connected`,isError:!0};if(r.aborted)return{content:"Tool call aborted",isError:!0};let o=this.config.timeout??_d,s;try{s=await this.client.callTool({name:t,arguments:n??{}},oF,{signal:r,timeout:o})}catch(i){let a=i instanceof Error?i.message:String(i);return{content:`MCP tool "${this.serverName}.${t}" failed: ${a}`,isError:!0}}return sF(s)}async finishAuth(t){if(!this.pendingAuthTransport)throw new Error(`McpClient(${this.serverName}): no pending OAuth transport \u2014 server is not in oauth_pending state`);await this.pendingAuthTransport.finishAuth(t)}async disconnect(){if(this.pendingAuthTransport=void 0,!this.client)return;let t=this.client;this.client=void 0,this.connected=!1;try{await t.close()}catch{}}};function sF(e){let t=[];for(let r of e.content??[])if(r.type==="text")t.push(r.text);else if(r.type==="image")t.push(`[image block: mimeType=${r.mimeType}, ${r.data.length} bytes base64]`);else if(r.type==="resource"){let o="resource"in r&&typeof r.resource=="object"?r.resource.uri??"(unknown)":"(unknown)";t.push(`[resource block: ${o}]`)}else t.push(`[unknown block: ${JSON.stringify(r)}]`);let n=t.join(`
|
|
2074
2074
|
`);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function iF(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:pl(e,t,n),fallback:r==="streamable-http"?()=>pl(e,{...t,type:"sse"},n):null}}function aF(e){return e instanceof zw&&(e.code===404||e.code===405)}function lF(e){return e instanceof zw?e.code:void 0}function ml(e,t,n,r){let o=null,s=new Promise((i,a)=>{o=setTimeout(()=>{if(r!==void 0)try{let l=r();l&&typeof l.then=="function"&&l.catch(()=>{})}catch{}a(n())},t)});return Promise.race([e,s]).finally(()=>{o!==null&&clearTimeout(o)})}import{createHash as cF}from"node:crypto";var Jw="mcp__",Vw="__",Pd=64,uF=6;function gs(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function dF(e){return cF("sha256").update(e).digest("hex").slice(0,uF)}function Yw(e,t){let n=gs(e),r=gs(t),o=`${Jw}${n}${Vw}${r}`;if(o.length<=Pd)return o;let i=`${`${Jw}${dF(e)}${Vw}`}${r}`;return i.length<=Pd?i:i.slice(0,Pd)}function hs(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=Yw(o,i),l={serverName:o,originalToolName:i},c=t.get(a);if(c===void 0){t.set(a,l);continue}if(c.serverName===o&&c.originalToolName===i)continue;let u=n.get(a)??[c];u.push(l),n.set(a,u)}let r=[];for(let[o,s]of n)r.push({wireName:o,pairs:s});return{tools:t,conflicts:r}}var ys=class e{records;nameRegistry;onToolsRefreshed;constructor(t){this.records=t;let n=[];for(let[o,s]of t)s.state.status==="connected"&&n.push({serverName:o,toolNames:s.tools.map(i=>i.name)});let r=hs(n);if(r.conflicts.length>0){let o=r.conflicts.map(s=>{let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");return` ${s.wireName} \u2190 ${i}`});throw new Error(`MCP tool name conflicts (rename one of the servers in mcp.json):
|
|
2075
2075
|
${o.join(`
|
|
2076
|
-
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=gs(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,f);let g=new lo(c,u);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=fl(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{try{let{tools:b,serverInfo:y}=await g.connect();f.tools=b,f.state.status="connected",f.state.toolCount=b.length,f.state.lastListedAt=Date.now();let k=y?`${y.name}@${y.version}`:"unknown";console.log(`[mcp:${c}] connected (${k}) \u2014 ${b.length} tool(s)`)}catch(b){if(b instanceof Id){f.state.status="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let y=b instanceof Error?b.message:String(b);if(f.state.status="error",f.state.error=fl(y,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${y}`);console.warn(`[mcp:${c}] connect failed: ${y}`)}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(pF(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=hs([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new lo(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=fl(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=fl(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=hs([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function pF(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function fl(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}K();N();import{existsSync as ws,lstatSync as mF,readFileSync as fF,readdirSync as gF}from"node:fs";import{join as ks}from"node:path";function gl(){return ks(Mn(),"mcp.json")}function Xw(e=process.cwd()){return ks(e,".mcp.json")}var hF=5;function Md(e=De()){if(!ws(e))return[];let t=[];return Qw(e,e,0,t,new Set),t}function Qw(e,t,n,r,o){if(n>hF||o.has(t))return;o.add(t);let s=ks(t,".claude-plugin","plugin.json");if(ws(s)){let a=ks(t,".claude-plugin","mcp.json");ws(a)&&r.push(a);return}let i;try{i=gF(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ks(t,a),c;try{c=mF(l)}catch{continue}c.isDirectory()&&Qw(e,l,n+1,r,o)}}function yF(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function bs(e){if(!ws(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(fF(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=yF(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function $d(e={}){let t=[],n=[];if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?Md(a):Md();for(let c of l)t.push({path:c,loaded:bs(c)})}if(!e.skipUserGlobal){let a=gl();t.push({path:a,loaded:bs(a)})}if(!e.skipProjectLocal&&E.AFK_ALLOW_PROJECT_MCP!=="0"){let a=Xw(e.cwd);ws(a)&&(t.push({path:a,loaded:bs(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:bs(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}da();function Od(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Ss(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(m.warning(`\u26A0 [resume-swap] ${t}: ${Od(r)}`))}async function Zw(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${Od(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=Od(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Ss(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(m.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Ss(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Ss(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(ia(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.planMode=!1,delete t.stats.pendingPlanExit;try{t.onSwapped(e)}catch(i){Ss(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await qa(n).catch(i=>{Ss(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(Ke(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(Z(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(m.brand(s.join(" \xB7 "))),t.statusLine.repaint(ns(t.stats,t.contextSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function eS(e){return new et(Kn({model:e.model,apiKey:se(),maxTurns:e.maxTurns,hookRegistry:e.hookRegistry,...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.systemPromptSource!==void 0?{systemPromptSource:e.systemPromptSource}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.resumeConfig,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{},...e.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:e.autoResumeOnUsageLimit}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},provider:e.provider}))}async function nS(e,t){let n=Qi(e),r=zr(n),o=n?.stored?.model??e.model,s,i,a;s=pn(e.thinking)??Pr(),i=mn(e.effort)??Mr(),a=Or(e.maxOutputTokens)??Jo();let l=Ir()??_r(),c=Xe(),u=c.systemPromptSource,d=c.autoRouting?.interactive??!0,p=Wi(l,d,"repl"),f={current:null},g=se(),h=new J({apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),b=n?.stored?.sessionId,y=Yi(b?{sessionLabel:b}:{}),k=new Gi(y?{traceWriter:y.writer}:{});Ob(k);let x=c.bgSummaries===!0&&g?new ul({registry:k,apiKey:g,maxCallsPerSession:c.maxSummaryCallsPerSession??200}):void 0;x?.start(),Db(x);let S=qi(c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{}),v={get sessionId(){return f.current?.sessionId},getInputStreamRef(){return f.current?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return f.current?.abortSignal??new AbortController().signal}},R=zi(o,g,S,c.baseUrl,y?.writer),A=new bn({subagentManager:h,parentSession:v,defaultConfig:{apiKey:g,systemPrompt:l,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{}},defaultSubagentModel:dn(o),childProviderFactory:S,childSkillExecutorFactory:R,backgroundRegistry:k}),O=new yn({parentSession:v,defaultModel:o,defaultSubagentModel:dn(o),apiKey:g,childProviderFactory:S,childSkillExecutorFactory:R,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...y?.writer!==void 0?{traceWriter:y.writer}:{}}),C=new jr({parentSession:v,defaultModel:o,defaultSubagentModel:dn(o),apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},systemPrompt:l??""}),I=new Be,P;{let Me=t?.cwd??process.cwd(),je=$d({cwd:Me,...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),Ns=Object.values(je.mcpServers).filter(ko=>!ko.disabled).length;if(Ns>0){let ko=je.sources.length===1?je.sources[0]:`${je.sources.length} source(s)`;console.log(m.dim(` mcp: ${Ns} server(s) from ${ko??gl()}`)),P=await ys.fromConfig(je.mcpServers,{warnings:je.warnings})}else if(je.warnings.length>0)for(let ko of je.warnings)console.warn(`[mcp] ${ko}`)}let D=Ii(e.provider,{subagentExecutor:A,skillExecutor:O,composeExecutor:C,memoryStore:I,model:String(o),...c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{},...P!==void 0?{mcpManager:P}:{}})??new He({permissions:{allowedTools:[...ln,...Un,"agent","skill","compose",...P?.getMcpToolWireNames()??[]]},subagentExecutor:A,skillExecutor:O,composeExecutor:C,memoryStore:I,surface:"cli",...P!==void 0?{mcpManager:P}:{}}),F=Zi(o);n?.stored&&ia(F,n.stored,n.resumeId),F.cwd=t?.cwd??process.cwd(),y&&console.log(m.dim(` trace: ${y.tracePath}`));let U={fn:Me=>console.log(Me)},z=new sa,V=Bw(process.stdout,{statusLine:z}),M=Ur(Me=>{U.fn(Hi(Me))},"cli",I,()=>F.planMode?"plan":"default").registry,L={model:o,resumeConfig:r,systemPrompt:p,systemPromptSource:u,thinking:s,effort:i,maxOutputTokens:a,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},provider:D,hookRegistry:M,traceWriter:y?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:c.autoResumeOnUsageLimit},W=eS(L);f.current=W;let re=new al,B=no(U),$=new ll(W),ee={session:f,stats:F,out:B,ui:{clearScreen:()=>{z.stop(),$.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),z.start(),z.repaint(ns(F,$))},repaintStatusLine:()=>z.repaint(ns(F,$))},ledger:re,...P!==void 0?{mcpManager:P}:{}},ve=Me=>(re.clear(),Zw(Me,{sessionRef:f,stats:F,contextSampler:$,statusLine:z,backgroundRegistry:k,completionWriter:U,isInFlight:()=>Oe.getInFlight?.()??!1,onSwapped:je=>{Oe.resumeTarget=je,Oe.clearVerdictLedger?.()},buildSession:je=>eS({...L,model:je.stored?.model??L.model,resumeConfig:zr(je)})})),Oe={session:f,memoryStore:I,stats:F,statusLine:z,contextSampler:$,completionWriter:U,replRenderer:V,slashCtx:ee,rl:null,options:e,...n!==void 0?{resumeTarget:n}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:k,...x!==void 0?{bgSummarizer:x}:{},requestResume:ve,getInFlight:()=>!1,...P!==void 0?{mcpManager:P}:{}},_e=Me=>{U.fn(Kk(Me,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},it=Me=>{U.fn(Hk(Me,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),re.record(Me)};yy(_e),gy(it),Oe.teardownTrustedSkillEvents=()=>{by(_e),hy(it)},Uw(),D instanceof He&&zk(D);let hr=tS.createInterface({input:process.stdin,output:process.stdout,terminal:!1});return Oe.rl=hr,Hn.install(Vy({readLine:Me=>new Promise((je,Ns)=>{hr.question(Me,je),hr.once("close",()=>Ns(new Error("readline closed")))}),writer:{line:(Me="")=>process.stdout.write(Me+`
|
|
2076
|
+
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=gs(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,f);let g=new lo(c,u);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=fl(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{try{let{tools:b,serverInfo:y}=await g.connect();f.tools=b,f.state.status="connected",f.state.toolCount=b.length,f.state.lastListedAt=Date.now();let k=y?`${y.name}@${y.version}`:"unknown";console.log(`[mcp:${c}] connected (${k}) \u2014 ${b.length} tool(s)`)}catch(b){if(b instanceof Id){f.state.status="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let y=b instanceof Error?b.message:String(b);if(f.state.status="error",f.state.error=fl(y,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${y}`);console.warn(`[mcp:${c}] connect failed: ${y}`)}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(pF(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=hs([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new lo(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=fl(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=fl(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=hs([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function pF(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function fl(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}K();N();import{existsSync as ws,lstatSync as mF,readFileSync as fF,readdirSync as gF}from"node:fs";import{join as ks}from"node:path";function gl(){return ks(Mn(),"mcp.json")}function Xw(e=process.cwd()){return ks(e,".mcp.json")}var hF=5;function Md(e=De()){if(!ws(e))return[];let t=[];return Qw(e,e,0,t,new Set),t}function Qw(e,t,n,r,o){if(n>hF||o.has(t))return;o.add(t);let s=ks(t,".claude-plugin","plugin.json");if(ws(s)){let a=ks(t,".claude-plugin","mcp.json");ws(a)&&r.push(a);return}let i;try{i=gF(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ks(t,a),c;try{c=mF(l)}catch{continue}c.isDirectory()&&Qw(e,l,n+1,r,o)}}function yF(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function bs(e){if(!ws(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(fF(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=yF(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function $d(e={}){let t=[],n=[];if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?Md(a):Md();for(let c of l)t.push({path:c,loaded:bs(c)})}if(!e.skipUserGlobal){let a=gl();t.push({path:a,loaded:bs(a)})}if(!e.skipProjectLocal&&E.AFK_ALLOW_PROJECT_MCP!=="0"){let a=Xw(e.cwd);ws(a)&&(t.push({path:a,loaded:bs(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:bs(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}da();function Od(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Ss(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(m.warning(`\u26A0 [resume-swap] ${t}: ${Od(r)}`))}async function Zw(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${Od(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=Od(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Ss(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(m.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Ss(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Ss(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(ia(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.planMode=!1,delete t.stats.pendingPlanExit;try{t.onSwapped(e)}catch(i){Ss(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await qa(n).catch(i=>{Ss(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(Ke(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(Z(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(m.brand(s.join(" \xB7 "))),t.statusLine.repaint(ns(t.stats,t.contextSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function eS(e){return new et(Kn({model:e.model,apiKey:se(),maxTurns:e.maxTurns,hookRegistry:e.hookRegistry,...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.systemPromptSource!==void 0?{systemPromptSource:e.systemPromptSource}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.resumeConfig,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{},...e.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:e.autoResumeOnUsageLimit}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},provider:e.provider}))}async function nS(e,t){let n=Qi(e),r=zr(n),o=n?.stored?.model??e.model,s,i,a;s=pn(e.thinking)??Pr(),i=mn(e.effort)??Mr(),a=Or(e.maxOutputTokens)??Jo();let l=Ir()??_r(),c=Xe(),u=c.systemPromptSource,d=c.autoRouting?.interactive??!0,p=Wi(l,d,"repl"),f={current:null},g=se(),h=new J({apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),b=n?.stored?.sessionId,y=Yi(b?{sessionLabel:b}:{}),k=new Gi(y?{traceWriter:y.writer}:{});Ob(k);let x=c.bgSummaries===!0&&g?new ul({registry:k,apiKey:g,maxCallsPerSession:c.maxSummaryCallsPerSession??200}):void 0;x?.start(),Db(x);let S=qi(c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{}),v={get sessionId(){return f.current?.sessionId},getInputStreamRef(){return f.current?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return f.current?.abortSignal??new AbortController().signal}},R=zi(o,g,S,c.baseUrl,y?.writer,k),A=new bn({subagentManager:h,parentSession:v,defaultConfig:{apiKey:g,systemPrompt:l,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{}},defaultSubagentModel:dn(o),childProviderFactory:S,childSkillExecutorFactory:R,backgroundRegistry:k}),O=new yn({parentSession:v,defaultModel:o,defaultSubagentModel:dn(o),apiKey:g,childProviderFactory:S,childSkillExecutorFactory:R,backgroundRegistry:k,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...y?.writer!==void 0?{traceWriter:y.writer}:{}}),C=new jr({parentSession:v,defaultModel:o,defaultSubagentModel:dn(o),apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},systemPrompt:l??""}),I=new Be,P;{let Me=t?.cwd??process.cwd(),je=$d({cwd:Me,...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),Ns=Object.values(je.mcpServers).filter(ko=>!ko.disabled).length;if(Ns>0){let ko=je.sources.length===1?je.sources[0]:`${je.sources.length} source(s)`;console.log(m.dim(` mcp: ${Ns} server(s) from ${ko??gl()}`)),P=await ys.fromConfig(je.mcpServers,{warnings:je.warnings})}else if(je.warnings.length>0)for(let ko of je.warnings)console.warn(`[mcp] ${ko}`)}let D=Ii(e.provider,{subagentExecutor:A,skillExecutor:O,composeExecutor:C,memoryStore:I,model:String(o),...c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{},...P!==void 0?{mcpManager:P}:{}})??new He({permissions:{allowedTools:[...ln,...Un,"agent","skill","compose",...P?.getMcpToolWireNames()??[]]},subagentExecutor:A,skillExecutor:O,composeExecutor:C,memoryStore:I,surface:"cli",...P!==void 0?{mcpManager:P}:{}}),F=Zi(o);n?.stored&&ia(F,n.stored,n.resumeId),F.cwd=t?.cwd??process.cwd(),y&&console.log(m.dim(` trace: ${y.tracePath}`));let U={fn:Me=>console.log(Me)},z=new sa,V=Bw(process.stdout,{statusLine:z}),M=Ur(Me=>{U.fn(Hi(Me))},"cli",I,()=>F.planMode?"plan":"default").registry,L={model:o,resumeConfig:r,systemPrompt:p,systemPromptSource:u,thinking:s,effort:i,maxOutputTokens:a,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},provider:D,hookRegistry:M,traceWriter:y?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:c.autoResumeOnUsageLimit},W=eS(L);f.current=W;let re=new al,B=no(U),$=new ll(W),ee={session:f,stats:F,out:B,ui:{clearScreen:()=>{z.stop(),$.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),z.start(),z.repaint(ns(F,$))},repaintStatusLine:()=>z.repaint(ns(F,$))},ledger:re,...P!==void 0?{mcpManager:P}:{}},ve=Me=>(re.clear(),Zw(Me,{sessionRef:f,stats:F,contextSampler:$,statusLine:z,backgroundRegistry:k,completionWriter:U,isInFlight:()=>Oe.getInFlight?.()??!1,onSwapped:je=>{Oe.resumeTarget=je,Oe.clearVerdictLedger?.()},buildSession:je=>eS({...L,model:je.stored?.model??L.model,resumeConfig:zr(je)})})),Oe={session:f,memoryStore:I,stats:F,statusLine:z,contextSampler:$,completionWriter:U,replRenderer:V,slashCtx:ee,rl:null,options:e,...n!==void 0?{resumeTarget:n}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:k,...x!==void 0?{bgSummarizer:x}:{},requestResume:ve,getInFlight:()=>!1,...P!==void 0?{mcpManager:P}:{}},_e=Me=>{U.fn(Kk(Me,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},it=Me=>{U.fn(Hk(Me,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),re.record(Me)};yy(_e),gy(it),Oe.teardownTrustedSkillEvents=()=>{by(_e),hy(it)},Uw(),D instanceof He&&zk(D);let hr=tS.createInterface({input:process.stdin,output:process.stdout,terminal:!1});return Oe.rl=hr,Hn.install(Vy({readLine:Me=>new Promise((je,Ns)=>{hr.question(Me,je),hr.once("close",()=>Ns(new Error("readline closed")))}),writer:{line:(Me="")=>process.stdout.write(Me+`
|
|
2077
2077
|
`)},pendingCount:()=>Hn.pendingCount()})),ee.requestResume=ve,Oe}K();import{promises as vs}from"node:fs";import*as oS from"node:os";import*as hl from"node:path";async function rS(e,t,n=!1){await vs.mkdir(e,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),o=hl.join(e,`${r}.md`),s=n?" (continued)":"";return await vs.writeFile(o,`# Session \u2014 ${new Date().toISOString()}${s}
|
|
2078
2078
|
|
|
2079
2079
|
- model: ${t}
|
|
@@ -2125,7 +2125,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2125
2125
|
`)}function $F(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 hS(e,t,n){let r=[];return n&&n.trim().length>0&&r.push({type:"text",text:n}),e&&r.push({type:"text",text:e}),Ha(r,t),r}async function yS(e,t,n,r,o="summary",s,i,a){let l=ok(e.text,e.attachments);r.setInFlight(!0);let c="",u=!1,d=!1,p=!1,f=!1,g,h=!1,b=[],y=new Map,k=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,T=r.getCompositor?r.getCompositor():null,x=()=>new to({out:no(s),thinkingMode:o,...k?{activeSkillName:k}:{},onCancel:()=>{t.interrupt().catch(A=>{Ve()&&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}:{},...T?{compositor:T}:{}}),S=x(),v=async()=>{if(!p){p=!0;try{await S.dispose()}catch{}}},R=async()=>{await S.arm();let A=S.getCompositor();if(s&&A){let O=A;s.fn=C=>O.commitAbove(C)}r.setActiveCompositor?.(A),r.rearmStatus?.()};try{T?T.commitAbove(""):console.log(),await R(),i&&r.setBackgroundHandler&&r.setBackgroundHandler(()=>{h=!0});let A=e.attachments.length===0?e.text:hS(e.text,e.attachments),O=t.sendMessageStream(A);if(await Tr((I,P)=>{S.process(I,P)},async()=>{for await(let I of O){if(h&&i){let P=k??e.text.slice(0,40),D=i.register(P),F=ga(D,i);ha(O,c,l,D,i,F,n,r.onTurnComplete,t.abortSignal),await v(),(s??{fn:console.log}).fn(m.dim(` \u2192 backgrounded as ${D.id}: ${D.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(I.type==="chunk"&&I.chunk.type==="content"?(c+=I.chunk.content,u=!0):I.type==="message"&&!u&&(c=I.message.content),I.type==="chunk"&&I.chunk.type==="tool_use_detail"){let P=I.chunk,D={toolName:P.toolName,toolUseId:P.toolUseId,input:P.toolInput};y.set(P.toolUseId,D),b.push(D)}else if(I.type==="chunk"&&I.chunk.type==="tool_result"){let P=I.chunk,D=y.get(P.toolUseId);D&&(D.result=P.content,D.isError=P.isError,y.delete(P.toolUseId))}if(I.type==="paused"){await v(),(s??{fn:console.log}).fn(Am({reason:I.reason,...I.resetsAt!==void 0?{resetsAt:I.resetsAt}:{},...I.accountId!==void 0?{accountId:I.accountId}:{},...I.autoResume!==void 0?{autoResume:I.autoResume}:{}}));continue}if(I.type==="resumed"){let P=I.hotSwapped&&I.accountId?`\u25B6 Resumed on ${I.accountId}`:"\u25B6 Resumed";c="",u=!1,b.length=0,y.clear(),f=!1,g=void 0,d=!1,h=!1,S=x(),p=!1,await R(),(s??{fn:console.log}).fn(m.success(P));continue}if(I.type==="error"){await v(),wr(kr(I.error)),d=!0;continue}S.process(I),I.type==="done"&&(f=!0,g=I.metadata)}}),await v(),f){Jn(n,l,c,g,b),r.onTurnComplete&&await r.onTurnComplete(l,c).catch(()=>{});let I=D=>{s?s.fn(D):console.log(D)};(u||b.length>0)&&I(`
|
|
2126
2126
|
`);let P=fS(c);if(P&&(I(gS(P)),I(""),r.onTerminalState))try{r.onTerminalState(P)}catch{}if(OF(g,n,I),r.onAfterTurn){let D=r.onAfterTurn();D instanceof Promise&&await D.catch(()=>{})}}}catch(A){await v(),d||wr(kr(A))}finally{await v(),s&&(s.fn=A=>console.log(A)),r.setActiveCompositor?.(null),r.setBackgroundHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function OF(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ie(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Ke(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(Z(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=Du(t),a=nt(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 ~${Z(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 ${Z(a)}`))}n("")}function bS(e={}){let t=e.load??pa,n=e.onResize??(i=>Je.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=Sb(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:ma(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Ud={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 kS(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=Ud[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,ne()-2);if(q(a)<=l)return a;let c=r+n.map(u=>Ud[u].color(Ud[u].glyph)).join(m.dim(" "))+i;return ce(c,l)}}}var Bd=["\u25D0","\u25D1","\u25D2","\u25D3"],wl=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=Je.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%Bd.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(Bd[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(`${Z(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return a.push(ie(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(Bd[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(ie(a))),ce(" "+i.join(" "),n)}};function Sl(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function wS(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async p=>{Ve()&&(o=la(p)),await qa(e.session.current),Ve()&&(s=pw())}).catch(()=>{});let i=await cS(),a=new kl({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d;try{await a.armCompositor({promptFn:()=>Sl(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let h=e.slashCtx;h.stats.planMode&&h.stats.pendingPlanExit?(h.stats.pendingPlanExit=!1,wt(h,!1,{closureSummarySkipped:!0}).catch(()=>{})):wt(h).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine}),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor(),c=bS();let p=kS();e.clearVerdictLedger=()=>p.reset(),u=new fa,Mb(u),Nb(u),Bb(u),jb(e.backgroundRegistry),d=new wl(u,e.backgroundRegistry),d.setRowCountChangeHandler(h=>{e.statusLine.setExtraRows(h)}),d.start();let f=50,g=[];for(u.on("complete",h=>{g.length>=f&&g.shift(),g.push(h)});;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let v of s)e.replRenderer.writeLine(v);e.replRenderer.writeLine(""),s=[]}for(;g.length>0;){let v=g.shift(),R=v.status==="succeeded"?"\u2713":"\u2717",A=[];if(v.resultText){let C=v.resultText.trim().split(`
|
|
2127
2127
|
`)[0]?.slice(0,80)??"";C&&A.push(C)}v.error&&A.push(v.error.message);let O=[v.stats.toolUses>0?`${v.stats.toolUses} tools`:"",v.stats.tokens>0?`${Math.round(v.stats.tokens/1e3)}k tok`:"",v.stats.durationMs>0?`${Math.round(v.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");O&&A.push(O),e.replRenderer.writeLine(tn({kind:v.status==="succeeded"?"checkpoint":"diagnosis",title:`${R} ${v.id} ${v.label}`,body:A})),e.replRenderer.writeLine("")}let h=c.renderIfChanged(e.stats.sessionId);if(h.length>0){for(let v of h)e.replRenderer.writeLine(v);e.replRenderer.writeLine("")}let b=p.render();b&&e.replRenderer.writeLine(b);let y,k;if(l!==void 0){let v=l;l=void 0;let R=Sl(e.stats.model,e.stats.planMode),A=Xn({buffer:v.text,promptText:R,isTTY:!!process.stdout.isTTY,attachmentSummary:Xr([...v.attachments])});e.replRenderer.writeLine(A),y=v.text.trim(),k=v.attachments}else{let v=await a.readLine({promptFn:()=>Sl(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let R=e.slashCtx;R.stats.planMode&&R.stats.pendingPlanExit?(R.stats.pendingPlanExit=!1,wt(R,!1,{closureSummarySkipped:!0}).catch(()=>{})):wt(R).catch(()=>{}),e.statusLine.rearm()}});y=v.text.trim(),k=v.attachments}if(!y&&k.length===0)continue;let T=!1;if(y.startsWith("/")){let v=await eb(y,e.slashCtx,k);if(v.handled){if(v.result==="exit"){e.rl.close();return}if((y==="/clear"||y.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),p.reset()),v.result!==null&&typeof v.result=="object"&&"kind"in v.result&&v.result.kind==="submit"){l={text:v.result.message,attachments:k??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}T=!0}i.push(y);let x=y;if(T){let v=Ou(y);if(v){let R=v.name.replace(/^\//,"").split(":").pop()??"";if(R&&hd(R)){let A={skillName:R,rawArgs:v.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},O=e.session.current.sessionId,C=ps(O),I=Date.now();H(`[afk trace] preflight.start commandName=${R}`);let P=!1,D=await ds(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:C},F=>{Ve()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${R}) failed: `)+(F instanceof Error?F.message:String(F)))});P=D!==null,H(`[afk trace] preflight.end commandName=${R} durationMs=${Date.now()-I} success=${P}`),x=kd(D?.manifestBlock,y)}}}let S;if(e.firstTurnHook&&e.stats.totalTurns===0){let v=e.firstTurnHook;e.firstTurnHook=void 0,S=Promise.resolve().then(()=>v(y)).catch(R=>{e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(R instanceof Error?R.message:String(R)))})}await yS({text:x,attachments:k},e.session.current,e.stats,{setInFlight(v){n.turnInFlight=v},async onTurnComplete(v,R){await t.appendTurn(v,R)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await pb(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:v=>p.push(v),setActiveCompositor:v=>{n.activeCompositor=v},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:v=>a.setBackgroundHandler(v)},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(Sl(e.stats.model,e.stats.planMode))),S!==void 0&&await S}}finally{if(u!==void 0)for(let p of u.running())u.cancel(p.id);d?.stop(),c?.dispose(),await a.dispose()}}import{execFile as DF}from"node:child_process";import{dirname as LF,isAbsolute as FF,resolve as NF}from"node:path";import{promisify as jF}from"node:util";var SS=jF(DF),UF=3e3,BF=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function WF(){let t=(await SS("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=FF(t)?t:NF(process.cwd(),t);return LF(n)}async function vS(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await WF()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),UF)});try{let o=Ot({execFile:SS,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=>BF.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as HF}from"node:fs";import{dirname as KF,join as GF}from"node:path";import{randomBytes as qF}from"node:crypto";var zF=["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(`
|
|
2128
|
-
`),TS=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wd=30,JF=1024,VF=8e3,YF="haiku";async function XF(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=tN(n,JF),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??VF),i=t.signal?nN([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await cl({token:t.token,model:t.model??YF,system:zF,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=QF(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=KF(t.worktreePath);return await ZF(l,c)}function QF(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(TS.test(t)&&t.length<=Wd)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>Wd)break;o=i}return TS.test(o)?o:null}async function ZF(e,t){if(!await eN(GF(t,e)))return e;let n=qF(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wd-5)}-${n}`}async function eN(e){try{return await HF.access(e),!0}catch{return!1}}function tN(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 nN(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 xS(e){let t,n,r=await XF(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??zg)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ES(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),ES(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ES(e){try{process.chdir(e)}catch{}}N();import{spawn as AS}from"child_process";import{existsSync as aN,mkdirSync as lN,readFileSync as RS,unlinkSync as cN,writeFileSync as uN}from"fs";import{get as dN}from"https";import{join as CS}from"path";import{readFileSync as rN}from"fs";import{dirname as oN,join as sN}from"path";import{fileURLToPath as iN}from"url";function zt(){try{return"3.30.
|
|
2128
|
+
`),TS=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wd=30,JF=1024,VF=8e3,YF="haiku";async function XF(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=tN(n,JF),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??VF),i=t.signal?nN([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await cl({token:t.token,model:t.model??YF,system:zF,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=QF(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=KF(t.worktreePath);return await ZF(l,c)}function QF(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(TS.test(t)&&t.length<=Wd)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>Wd)break;o=i}return TS.test(o)?o:null}async function ZF(e,t){if(!await eN(GF(t,e)))return e;let n=qF(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wd-5)}-${n}`}async function eN(e){try{return await HF.access(e),!0}catch{return!1}}function tN(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 nN(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 xS(e){let t,n,r=await XF(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??zg)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ES(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),ES(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ES(e){try{process.chdir(e)}catch{}}N();import{spawn as AS}from"child_process";import{existsSync as aN,mkdirSync as lN,readFileSync as RS,unlinkSync as cN,writeFileSync as uN}from"fs";import{get as dN}from"https";import{join as CS}from"path";import{readFileSync as rN}from"fs";import{dirname as oN,join as sN}from"path";import{fileURLToPath as iN}from"url";function zt(){try{return"3.30.2"}catch{}try{let e=oN(iN(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(rN(sN(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var pN=64*1024,mN=1440*60*1e3,fN="update-check.json",gN="pending-update.json";function _S(){return CS(Us(),fN)}function Hd(){return CS(Us(),gN)}function IS(){let e=Us();aN(e)||lN(e,{recursive:!0})}function hN(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 yN(){try{let e=RS(_S(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function bN(){try{IS();let e=`
|
|
2129
2129
|
const https = require('https');
|
|
2130
2130
|
const fs = require('fs');
|
|
2131
2131
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/telegram.mjs
CHANGED
|
@@ -1718,11 +1718,11 @@ Every turn must end in one externally identifiable terminal state. AFK users nee
|
|
|
1718
1718
|
|
|
1719
1719
|
Never end a turn mid-loop without one of these. The terminal-state heading must be the last block of the response, with no trailing prose after it.`,ah=new Set(["repl","telegram"]);function Vr(t,e,n="one-shot"){if(!t)return t;let r=[t];return e&&r.push(sh),ah.has(n)&&r.push(ih),r.join(`
|
|
1720
1720
|
|
|
1721
|
-
`)}var XR=300*1e3;var On=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"}};var dh=new Set;function gc(t){return dh.has(t)}var uh=new Set,ph=new Set;function hc(t){for(let e of uh)e(t)}function yc(t){for(let e of ph)e(t)}var fh=240;function mh(t,e=fh){return t.length<=e?t:t.slice(0,e)+"\u2026"}function gh(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 hh(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 Xe=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??Qe;if(n>=r){let a=gh(e.input);return q({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:a}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=hh(e.input)}catch(a){return{content:`Skill tool input validation failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}try{let a=pe(o.name);return await this.executeRegistrySkill(a,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 c=Le(this.ctx.pluginConfigs).map(a=>a.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${c||"(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=gc(e.name);o&&yc(e.name);let s=this.ctx.depth??0;q({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(),c,a;try{a=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){c=d}finally{let d=Date.now()-i;o&&hc({skillName:e.name,durationMs:d,...c!==void 0?{isError:!0}:{}});let u=c!==void 0?c instanceof Error?c.message:String(c):void 0,p=c===void 0?typeof a=="string"?a.length:a!=null?JSON.stringify(a).length:0:void 0;q({event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:c!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:mh(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return c!==void 0?{content:`Skill execution error: ${c instanceof Error?c.message:String(c)}`,isError:!0}:{content:typeof a=="string"?a:a!=null?JSON.stringify(a):"Skill completed successfully."}}buildForkedChildConfig(e,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??Qe,s={...e};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new C({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}}),c=new Ze({subagentManager:i,parentSession:Tt(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}),a=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:c,...a!==void 0?{childSkillExecutor:a}:{},...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=$(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 C({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:re()}),{childConfig:i,childManager:c}=this.buildForkedChildConfig({model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),a;try{a=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 a.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]
|
|
1721
|
+
`)}var XR=300*1e3;var On=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"}};var dh=new Set;function gc(t){return dh.has(t)}var uh=new Set,ph=new Set;function hc(t){for(let e of uh)e(t)}function yc(t){for(let e of ph)e(t)}var fh=240;function mh(t,e=fh){return t.length<=e?t:t.slice(0,e)+"\u2026"}function gh(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 hh(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 Xe=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??Qe;if(n>=r){let a=gh(e.input);return q({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:a}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=hh(e.input)}catch(a){return{content:`Skill tool input validation failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}try{let a=pe(o.name);return await this.executeRegistrySkill(a,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 c=Le(this.ctx.pluginConfigs).map(a=>a.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${c||"(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=gc(e.name);o&&yc(e.name);let s=this.ctx.depth??0;q({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(),c,a;try{a=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){c=d}finally{let d=Date.now()-i;o&&hc({skillName:e.name,durationMs:d,...c!==void 0?{isError:!0}:{}});let u=c!==void 0?c instanceof Error?c.message:String(c):void 0,p=c===void 0?typeof a=="string"?a.length:a!=null?JSON.stringify(a).length:0:void 0;q({event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:c!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:mh(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return c!==void 0?{content:`Skill execution error: ${c instanceof Error?c.message:String(c)}`,isError:!0}:{content:typeof a=="string"?a:a!=null?JSON.stringify(a):"Skill completed successfully."}}buildForkedChildConfig(e,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??Qe,s={...e};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new C({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}}),c=new Ze({subagentManager:i,parentSession:Tt(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.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{}}),a=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:c,...a!==void 0?{childSkillExecutor:a}:{},...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=$(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 C({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:re()}),{childConfig:i,childManager:c}=this.buildForkedChildConfig({model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),a;try{a=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 a.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]
|
|
1722
1722
|
|
|
1723
1723
|
${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{a&&await a.teardown().catch(O),await c?.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 C({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:re()}),{childConfig:c,childManager:a}=this.buildForkedChildConfig({model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n,env:{PLUGIN_ROOT:r},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},s.signal),l;try{l=await i.forkSubagent({parent:this.ctx.parentSession,config:c,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]
|
|
1724
1724
|
|
|
1725
|
-
${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(O),await a?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=yn(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 Qe=3;function Tt(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var yh=[...ft,"agent","skill"];function bc(t={}){return({childExecutor:e,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:yh},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{}};return ee(typeof r=="string"?r:void 0)==="openai-compatible"?new ye({...o,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}}):new ce(o)}}function wc(t,e,n,r,o){let
|
|
1725
|
+
${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(O),await a?.teardownAll(),await i.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=yn(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 Qe=3;function Tt(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var yh=[...ft,"agent","skill"];function bc(t={}){return({childExecutor:e,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:yh},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{}};return ee(typeof r=="string"?r:void 0)==="openai-compatible"?new ye({...o,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}}):new ce(o)}}function wc(t,e,n,r,o,s){let i=(c,a,l)=>new Xe({parentSession:Tt(l),defaultModel:t,apiKey:e,...r!==void 0?{baseUrl:r}:{},depth:c,maxDepth:a,childProviderFactory:n,childSkillExecutorFactory:i,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{}});return i}function kc(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function bh(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 c="agent-tool",a=e.id_prefix;if(a!==void 0){if(typeof a!="string")throw new Error("Agent tool id_prefix must be a string");c=a}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}return{prompt:n,model:r,max_turns:s,id_prefix:c,mode:l}}function Dn(t){try{return q(t).catch(()=>{})}catch{return Promise.resolve()}}function et(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function vc(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}var wh=4096,Sc=1024;function kh(t){if(t==null)return;let e=vc(t);return e!==void 0&&e>wh?{truncated:!0,chars:e}:t}function Sh(t){let e={status:t.status,error:et(t.errorMessage,Sc),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=et(t.schemaErrorMessage,Sc));let n=kh(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var Ze=class t{constructor(e){this.ctx=e}ctx;async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=bh(e.input)}catch(f){return{content:`Agent tool input validation failed: ${f instanceof Error?f.message:String(f)}`,isError:!0}}let r=this.ctx.depth??0,o=this.ctx.maxDepth??Qe,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",c=ee(i)==="openai-compatible",a={model:i,apiKey:c?void 0:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:c?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns},l;if(this.ctx.childProviderFactory&&r<o){s=new C({parentAbortSignal:e.signal}),l=Tt(e.signal);let f=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}),m=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;a.provider=this.ctx.childProviderFactory({childExecutor:f,...m!==void 0?{childSkillExecutor:m}:{},...a.model!==void 0?{model:a.model}:{}})}let d;try{d=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:a,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?kc(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":kc(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),l!==void 0&&(l.sessionId=d.id)}catch(f){let m=f instanceof Error?f.message:String(f);return Dn({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:et(m),depth:r}),{content:`Failed to fork subagent: ${m}`,isError:!0}}if(n.mode==="background"){let f=this.ctx.backgroundRegistry;if(!f)return await d.teardown().catch(b=>O("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 m;try{m=f.register({handle:d,prompt:n.prompt,model:a.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(b){if(b instanceof On)return await d.teardown().catch(S=>O("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: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(w)}}let u=()=>{d.cancel()};e.signal.addEventListener("abort",u,{once:!0});let p=Date.now(),g=this.ctx.parentSession.sessionId;try{let f=await d.runToResult(n.prompt);if(f.status==="succeeded"&&f.message){let S=f.message.content,y=typeof S=="string"?S:JSON.stringify(S),h=f.trace;return Dn({event:"subagent.completed",subagent_id:d.id,parent_session_id:g,status:f.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(k=>k.name))]):void 0}),{content:y}}let m=f.error?.message??"Subagent failed with no output",w=f.trace;Dn({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:f.status,duration_ms:Date.now()-p,error_message:et(m),schema_error:f.schemaError?et(f.schemaError.message):void 0,partial_output_chars:vc(f.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=Sh({status:f.status,errorMessage:m,schemaErrorMessage:f.schemaError?.message,partialOutput:f.partialOutput,subagentId:d.id});return{content:JSON.stringify(b),isError:!0}}catch(f){let m=f instanceof Error?f.message:String(f);throw Dn({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:et(m),depth:r}),f}finally{e.signal.removeEventListener("abort",u),await s?.teardownAll(),await d.teardown()}}};var Tc="unknown";try{let t=Ac(_c(Ec(import.meta.url)),"..","package.json"),e=JSON.parse(Jr(t,"utf8"));e.version&&(Tc=e.version)}catch{console.warn("\u26A0\uFE0F [daemon] Could not read package.json at startup \u2014 version drift check disabled.")}async function Eh(){let t;try{t=Pr()}catch(l){console.error("\u274C Configuration error:",l.message),process.exit(1)}let e=ee(t.model);if(e==="openai-compatible"||e==="openai-codex"){let l=v.OPENAI_API_KEY||v.CODEX_API_KEY;console.log(l?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for OpenAI auth":"\u{1F4DD} Will attempt API key from ~/.codex/auth.json (run `afk provider auth diagnose` for details)")}else{let l=kt();(!l||l.length===0)&&(console.error("\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."),console.error(" Set one in your environment, run `afk login`, or sign in to Claude Code."),process.exit(1)),Ht(l)==="oauth"?(process.env.CLAUDE_CODE_OAUTH_TOKEN=l,console.log("\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth (OAuth, auto-refresh on 401)")):(process.env.ANTHROPIC_API_KEY=l,console.log("\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth")),t.apiKey=l}Th(rt());let n=v.TELEGRAM_BOT_TOKEN;n||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN environment variable is required"),console.error(`
|
|
1726
1726
|
How to get a bot token:`),console.error(" 1. Open Telegram and search for @BotFather"),console.error(" 2. Send /newbot and follow the instructions"),console.error(" 3. Run: afk telegram setup"),process.exit(1));let r=mt(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS,console.warn);r.size===0&&(console.error("\u274C Error: AFK_TELEGRAM_ALLOWED_CHAT_IDS must list at least one chat ID"),console.error(`
|
|
1727
1727
|
This is an allowlist that gates who can message the bot.`),console.error("Run `afk telegram setup` to set it interactively, or set it manually:"),console.error(" AFK_TELEGRAM_ALLOWED_CHAT_IDS=123456789,-100987654321"),process.exit(1)),console.log("\u{1F50E} Validating bot token...");let o=await Qa(n);o||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN was rejected by Telegram (getMe failed)"),console.error(" The token may be revoked, malformed, or your network may be unreachable."),console.error(" Re-run `afk telegram setup` to refresh it."),process.exit(1));let s=o.username?`@${o.username}`:o.firstName;console.log(""),console.log(`\u{1F916} Starting Agent AFK Telegram Bot as ${s} (id ${o.id})`),console.log(`\u{1F4E1} Model: ${t.model} \xB7 Provider: ${e}`),console.log(`\u{1F512} Allowlist: ${r.size} chat ID(s)`);let i=new X,c=v.AFK_TELEGRAM_CWD,a=new In({botToken:n,apiKey:t.apiKey??"",dataDir:v.TELEGRAM_DATA_DIR||"./data/telegram-sessions",defaultModel:t.model,verbose:v.TELEGRAM_VERBOSE==="true",allowedChatIds:r,settingSources:["user","project"],...c!==void 0&&c.length>0?{botCwd:c}:{},createSession:async l=>{let d=Ie(l.model)??l.model;console.log(`Creating session with model: ${l.model} -> ${d}`);let u=ee(d),p=u==="openai-compatible"||u==="openai-codex",g=p?void 0:Wi(),f;if(!p){let h,k=l.apiKey??t.apiKey??"",E=t.baseUrl,_=l.cwd??c,T=new C({apiKey:k,...E!==void 0?{baseUrl:E}:{},..._!==void 0&&_.length>0?{cwd:_}:{}}),I={get sessionId(){return h?.sessionId},getInputStreamRef(){return h?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h?.abortSignal??new AbortController().signal}},A=bc(),M=wc(l.model,k,A,E),x=new Ze({subagentManager:T,parentSession:I,defaultConfig:{apiKey:k,systemPrompt:l.systemPrompt??t.systemPrompt,...E!==void 0?{baseUrl:E}:{}},defaultSubagentModel:hn(l.model),childProviderFactory:A,childSkillExecutorFactory:M}),R=new Xe({parentSession:I,defaultModel:l.model,defaultSubagentModel:hn(l.model),apiKey:k,childProviderFactory:A,childSkillExecutorFactory:M,...E!==void 0?{baseUrl:E}:{}}),F=l.systemPrompt??t.systemPrompt,D=new Mn({parentSession:I,defaultModel:l.model,defaultSubagentModel:hn(l.model),apiKey:k,...E!==void 0?{baseUrl:E}:{},systemPrompt:typeof F=="string"?F:""}),B=[...ft,...Ft,"agent","skill","compose"];f=new ce({permissions:{allowedTools:B},subagentExecutor:x,skillExecutor:R,composeExecutor:D});let W=l.systemPrompt??t.systemPrompt,V=t.autoRouting?.telegram??!1,le=typeof W=="string"?Vr(W,V,"telegram"):W,K=new Se({...l.apiKey!==void 0?{apiKey:l.apiKey}:{},model:l.model,...le!==void 0?{systemPrompt:le}:{},maxTurns:100,...g!==void 0?{maxOutputTokens:g}:{},...E!==void 0?{baseUrl:E}:{},..._!==void 0&&_.length>0?{cwd:_}:{},provider:f,hookRegistry:zr(void 0,"telegram",i).registry});return h=K,K}let m=l.systemPrompt??t.systemPrompt,w=t.autoRouting?.telegram??!1,b=typeof m=="string"?Vr(m,w,"telegram"):m,S=l.cwd??c;return new Se({...l.apiKey!==void 0?{apiKey:l.apiKey}:{},model:l.model,...b!==void 0?{systemPrompt:b}:{},maxTurns:100,...g!==void 0?{maxOutputTokens:g}:{},...S!==void 0&&S.length>0?{cwd:S}:{},hookRegistry:zr(void 0,"telegram",i).registry})}});try{a.start(),console.log("\u2705 Bot started successfully!"),console.log(`
|
|
1728
1728
|
\u{1F4DD} Slash commands (Agent SDK):`),console.log(" /start - Welcome and command list"),console.log(" /help - Show command list"),console.log(" /clear - Clear conversation history"),console.log(" /compact - Compact history (summarize older messages)"),console.log(" /model - Switch model (opus/sonnet/haiku/gpt-5.4/...)"),console.log(`
|