agent-afk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +3 -2
- package/dist/index.mjs +34 -33
- package/dist/telegram.mjs +3 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1361,9 +1361,10 @@ ${u}`}}catch(a){return{content:`Error: ${a instanceof Error?a.message:String(a)}
|
|
|
1361
1361
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1362
1362
|
- Use absolute paths for file operations.
|
|
1363
1363
|
|
|
1364
|
-
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var ji="anthropic-direct",Lp=8192,Fp="claude-sonnet-4-5-20250929",Up=null;var ge=class{name=ji;tools;providerFactory;skillExecutor;constructor(t={}){let n=[...xn];t.subagentExecutor&&n.push(ti),t.skillExecutor&&n.push(ni),this.tools=t.tools??new Gt({handlers:Ui(),schemas:n,hookRegistry:t.hookRegistry,permissions:t.permissions,subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor}),this.skillExecutor=t.skillExecutor,t.clientFactory&&(this.providerFactory=t.clientFactory)}query(t){let n=t.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${ji} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=Yo(r),s=qo(r,o),a=this.providerFactory??Up,i=a?a(s):new Dp(s),l=Jo(o),c=Np(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?jt(n.model)??n.model:Fp,p=jp(n),m=this.tools instanceof Gt?[...this.tools.toolDefs]:[...xn],f=[...Ee(Mt()),...Ee()],g=n.plugins??[],y=[...f,...g],h=this.skillExecutor?Ci(y):"",b=
|
|
1364
|
+
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var ji="anthropic-direct",Lp=8192,Fp="claude-sonnet-4-5-20250929",Up=null;var ge=class{name=ji;tools;providerFactory;skillExecutor;constructor(t={}){let n=[...xn];t.subagentExecutor&&n.push(ti),t.skillExecutor&&n.push(ni),this.tools=t.tools??new Gt({handlers:Ui(),schemas:n,hookRegistry:t.hookRegistry,permissions:t.permissions,subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor}),this.skillExecutor=t.skillExecutor,t.clientFactory&&(this.providerFactory=t.clientFactory)}query(t){let n=t.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${ji} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=Yo(r),s=qo(r,o),a=this.providerFactory??Up,i=a?a(s):new Dp(s),l=Jo(o),c=Np(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?jt(n.model)??n.model:Fp,p=jp(n),m=this.tools instanceof Gt?[...this.tools.toolDefs]:[...xn],f=[...Ee(Mt()),...Ee()],g=n.plugins??[],y=[...f,...g],h=this.skillExecutor?Ci(y):"",b=n.cwd||process.cwd(),v=[Ni];v.push(`# Environment
|
|
1365
|
+
- Working directory: ${b}`),h.length>0&&v.push(h),c&&v.push(c);let w=v.join(`
|
|
1365
1366
|
|
|
1366
|
-
`);return new Rn({client:i,authMode:o,promptStream:t.prompt,toolDispatcher:this.tools,model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:m,userSystem:
|
|
1367
|
+
`);return new Rn({client:i,authMode:o,promptStream:t.prompt,toolDispatcher:this.tools,model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:m,userSystem:w,systemPrefix:l})}};function Np(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}function jp(e){let t=e.maxOutputTokens;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):Lp}var Bi=new ge;import{Codex as Wi}from"@openai/codex-sdk";import{mkdtempSync as Bp,rmSync as Hp,writeFileSync as Wp}from"node:fs";import{tmpdir as Kp}from"node:os";import{join as Hi}from"node:path";var zt="openai-codex",Gp=[{value:"gpt-5.4",displayName:"GPT-5.4",description:"Codex default"},{value:"gpt-5.4-mini",displayName:"GPT-5.4 mini",description:"Faster, cheaper Codex variant"}];function zp(e){let t=[];if(e.continue&&t.push("continue"),e.resumeSessionAt!==void 0&&t.push("resumeSessionAt"),e.forkSession&&t.push("forkSession"),e.persistSession===!1&&t.push("persistSession=false"),e.enableFileCheckpointing&&t.push("enableFileCheckpointing"),e.thinking!==void 0&&t.push("thinking"),e.maxBudgetUsd!==void 0&&t.push("maxBudgetUsd"),e.taskBudget!==void 0&&t.push("taskBudget"),e.plugins&&e.plugins.length>0&&t.push("plugins"),e.agents&&t.push("agents"),e.agent!==void 0&&t.push("agent"),e.onElicitation&&t.push("onElicitation"),e.hooks&&t.push("hooks"),e.canUseTool&&t.push("canUseTool"),e.mcpServers&&t.push("mcpServers"),e.includeHookEvents&&t.push("includeHookEvents"),e.agentProgressSummaries&&t.push("agentProgressSummaries"),e.includePartialMessages&&t.push("includePartialMessages"),t.length>0)throw new Ot(zt,t.join(", "),`${zt} provider does not support AgentConfig fields: ${t.join(", ")}`)}function Ki(e){return e==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function Vp(e){if(e)switch(e){case"minimal":case"low":case"medium":case"high":case"xhigh":return e;case"max":return"xhigh";default:return}}function Yp(e){let t=e.systemPrompt;if(t!==void 0){if(typeof t=="string")return t.length>0?t:void 0;if(typeof t=="object"&&t!==null&&"append"in t){let n=t.append;return n&&n.length>0?n:void 0}}}function qp(e){let t=Bp(Hi(Kp(),"afk-codex-instr-")),n=Hi(t,"instructions.md");return Wp(n,e,"utf-8"),{path:n,dispose:()=>{try{Hp(t,{recursive:!0,force:!0})}catch{}}}}function Jp(e){if(e.apiKey)return e.apiKey;let t=process.env.OPENAI_API_KEY??process.env.CODEX_API_KEY;return t&&t.length>0?t:void 0}function*Qp(e,t,n,r){if(e.type!=="thread.started"&&e.type!=="turn.started"){if(e.type==="turn.completed"){let o=e.usage;yield{type:"turn.completed",usage:{inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,totalTokens:o.input_tokens+o.output_tokens+o.cached_input_tokens,resultSubtype:"success",isError:!1,raw:{input_tokens:o.input_tokens,output_tokens:o.output_tokens,cached_input_tokens:o.cached_input_tokens}},...t!==void 0?{sessionId:t}:{}};return}if(e.type==="turn.failed"){yield{type:"error",error:new Error(e.error.message)};return}if(e.type==="error"){yield{type:"error",error:new Error(e.message)};return}(e.type==="item.started"||e.type==="item.updated"||e.type==="item.completed")&&(yield*Xp(e.item,e.type==="item.completed",t,n,r))}}function*Xp(e,t,n,r,o){if(e.type==="agent_message"){let s=r.get(e.id)??"";if(e.text!==s){let a=e.text.startsWith(s)?e.text.slice(s.length):e.text;r.set(e.id,e.text),a.length>0&&(yield{type:"delta.text",text:a,...n!==void 0?{sessionId:n}:{}})}t&&(yield{type:"assistant.message",text:e.text,...n!==void 0?{sessionId:n}:{}},r.delete(e.id));return}if(e.type==="reasoning"){let s=o.get(e.id)??"";if(e.text!==s){let a=e.text.startsWith(s)?e.text.slice(s.length):e.text;o.set(e.id,e.text),a.length>0&&(yield{type:"delta.reasoning",text:a,...n!==void 0?{sessionId:n}:{}})}t&&o.delete(e.id);return}if(e.type==="command_execution"){if(t){let s=e.status==="failed",a=e.exit_code!==void 0?` (exit ${e.exit_code})`:"",i=`$ ${e.command}${a}
|
|
1367
1368
|
`+(e.aggregated_output??"");yield{type:"tool.output",toolUseId:e.id,content:i,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(e.type==="file_change"){if(t){let s=e.changes.map(a=>`${a.kind} ${a.path}`).join(`
|
|
1368
1369
|
`);yield{type:"tool.output",toolUseId:e.id,content:s,isError:e.status==="failed",...n!==void 0?{sessionId:n}:{}}}return}if(e.type==="mcp_tool_call"){if(t){let s=e.status==="failed",a;e.error?a=e.error.message:e.result?a=JSON.stringify(e.result,null,2):a="",yield{type:"tool.output",toolUseId:e.id,content:a,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(e.type==="web_search"){t&&(yield{type:"tool.output",toolUseId:e.id,content:`web_search: ${e.query}`,...n!==void 0?{sessionId:n}:{}});return}if(e.type!=="todo_list"&&e.type==="error"){t&&(yield{type:"error",error:new Error(e.message)});return}}var Yr=class{startOpts;promptStream;codex;thread;currentModel;currentSandbox;currentApproval;abortController=null;pendingAbortReason=null;closed=!1;initSessionId;dispose;closeResolve=null;closedPromise;constructor(t,n,r){this.startOpts=t,this.promptStream=n,this.initSessionId=r,this.codex=new Wi(t.codexOptions),this.thread=t.resumeId?this.codex.resumeThread(t.resumeId,t.threadOptions):this.codex.startThread(t.threadOptions),this.currentModel=t.threadOptions.model,this.currentSandbox=t.threadOptions.sandboxMode??"workspace-write",this.currentApproval=t.threadOptions.approvalPolicy??"never",t.instructionsDispose!==void 0&&(this.dispose=t.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let a=await Promise.race([s.next(),this.closedPromise]);if(a==="__closed__")break;let i=a;if(i.done)break;let l=i.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let u;try{let p=typeof l.content=="string"?l.content:l.content.map(m=>{if(typeof m=="object"&&m&&"type"in m){if(m.type==="text")return m.text;if(m.type==="image")return"[image omitted]"}return""}).join(`
|
|
1369
1370
|
`);u=await this.thread.runStreamed(p,{signal:c.signal})}catch(p){if(c.signal.aborted)return;yield{type:"error",error:p instanceof Error?p:new Error(String(p))};return}try{for await(let p of u.events){if(this.closed)return;p.type==="thread.started"&&(o=p.thread_id),yield*Qp(p,o,n,r)}}catch(p){if(c.signal.aborted)return;yield{type:"error",error:p instanceof Error?p:new Error(String(p))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(a){yield{type:"error",error:a instanceof Error?a:new Error(String(a))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let t=this.abortController;if(t&&!t.signal.aborted){t.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(t){this.currentModel=t;let n={...this.startOpts.threadOptions,...t!==void 0?{model:t}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(t){let{sandboxMode:n,approvalPolicy:r}=Ki(t);this.currentSandbox=n,this.currentApproval=r;let o={...this.startOpts.threadOptions,sandboxMode:n,approvalPolicy:r},s=this.thread.id;this.thread=s?this.codex.resumeThread(s,o):this.codex.startThread(o),this.startOpts.threadOptions=o}async supportedCommands(){return[]}async supportedModels(){return Gp.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:null}}async mcpServerStatus(){return[]}async accountInfo(){return{}}async rewindFiles(t,n){throw new Ot(zt,"rewindFiles",`${zt} provider does not support file checkpoint rewind.`)}close(){this.closed=!0;let t=this.abortController;t&&!t.signal.aborted?t.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),this.dispose?.()}getThread(){return this.thread}},Zp=null;var _n=class{name=zt;query(t){zp(t.config);let n=Jp(t.config),r=Vp(t.config.effort),{sandboxMode:o,approvalPolicy:s}=Ki(t.config.permissionMode),a={...t.config.model!==void 0?{model:t.config.model}:{},sandboxMode:o,approvalPolicy:s,...r!==void 0?{modelReasoningEffort:r}:{},skipGitRepoCheck:!0,workingDirectory:process.cwd()},i=Yp(t.config),l={};n!==void 0&&(l.apiKey=n);let c;if(i!==void 0){let{path:g,dispose:y}=qp(i);l.config={...l.config??{},model_instructions_file:g},c=y}W(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(t.config.model)}, sandbox=${o}, approval=${s})`);let u=Zp,p=u??(g=>new Wi(g)),m=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new Yr({threadOptions:a,codexOptions:l,...t.config.resume!==void 0?{resumeId:t.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},t.prompt,m);if(u){let g=p(l);f.codex=g,f.thread=t.config.resume?g.resumeThread(t.config.resume,a):g.startThread(a)}return f}},Gi=new _n;var em=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function Pe(e){if(!e)return"anthropic-direct";let t=e.trim().toLowerCase();return!t||em.has(t)||t.startsWith("claude-")||t.startsWith("claude_")?"anthropic-direct":t.startsWith("gpt-")||t.startsWith("gpt_")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")||t.startsWith("codex-")||t.startsWith("codex_")||t==="codex"?"openai-codex":"anthropic-direct"}function zi(e){return Pe(e)==="openai-codex"?Gi:Bi}async function Vi(e,t,n={}){e&&await e.dispatch(t,n.signal)}async function Yi(e,t,n={}){if(e)try{await e.dispatch(t,n.signal)}catch(r){if(r instanceof fe||r instanceof ke){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var $n=class{pendingResolve=null;bufferedMessage=null;getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessage=t}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessage!==null){let n=t.bufferedMessage;t.bufferedMessage=null;let r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function tm(e){let t=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=e.match(t);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],a=parseFloat(r),i=a;o==="KB"?i=a*1024:o==="MB"?i=a*1024*1024:o==="GB"&&(i=a*1024*1024*1024);let l=r;return a%1===0&&(l=String(Math.floor(a))),l+=o,{sizeLabel:l,sizeBytes:Math.round(i),absolutePath:s.trim()}}function nm(e){if(e<1024)return`${e}B`;let t=e/1024;if(t<1024)return t%1===0?`${Math.floor(t)}KB`:`${t.toFixed(1)}KB`;let n=t/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function rm(e){let t=Buffer.byteLength(e,"utf8"),n=nm(t),r=e.split(`
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
function Ir(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){Ir()&&console.log(...t)}var B=class extends Error{constructor(e){super(e),this.name="AbortError"}},Me=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},U=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var ge=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field};var ae=class{queue=[];waiters=[];closed=!1;error=null;push(e){if(this.closed)throw new Error("Cannot push to closed queue");if(process.env.AFK_CODEX_DEBUG&&console.log("[queue] push:",e.type),A("\u{1F4E6} MessageQueue.push: event type=",e.type,"waiters=",this.waiters.length,"queue size=",this.queue.length),this.waiters.length>0){let n=this.waiters.shift();A("\u{1F4E6} MessageQueue.push: Resolving waiter immediately"),n?.({value:e,done:!1})}else this.queue.push(e),A("\u{1F4E6} MessageQueue.push: Added to queue, new size=",this.queue.length)}complete(){for(this.closed=!0;this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0})}fail(e){this.error=e,this.closed=!0;let n={type:"error",error:e};if(this.waiters.length>0)for(this.waiters.shift()?.({value:n,done:!1});this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0});else this.queue.push(n)}isClosed(){return this.closed}hasError(){return this.error}size(){return this.queue.length}async*[Symbol.asyncIterator](){for(A("\u{1F4E6} MessageQueue: Iterator started");;){if(this.queue.length>0){let n=this.queue.shift();if(A("\u{1F4E6} MessageQueue: Yielding queued event, type=",n?.type),n&&(yield n,n.type==="error")){A("\u{1F4E6} MessageQueue: Stopping after error");return}continue}if(this.closed){A("\u{1F4E6} MessageQueue: Closed and empty, stopping");return}A("\u{1F4E6} MessageQueue: Waiting for next event...");let e=await new Promise(n=>{this.waiters.push(n)});if(A("\u{1F4E6} MessageQueue: Got result, done=",e.done,"type=",e.value?.type),e.done)return;if(yield e.value,e.value.type==="error"){A("\u{1F4E6} MessageQueue: Stopping after error");return}}}};import xi from"@anthropic-ai/sdk";var Mr="claude-code-20250219,oauth-2025-04-20",Rr="claude-cli/1.0.0 (external, cli)",_r="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function At(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Tt(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function et(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":Mr,"x-app":"cli","User-Agent":Rr,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Ct(t){return t!=="oauth"?null:[{type:"text",text:_r}]}import{randomUUID as ft}from"node:crypto";function Re(){let t=process.env.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let e=t.toLowerCase();return!(e==="1"||e==="true"||e==="yes"||e==="on")}function _e(){let t=process.env.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":"1h"}function It(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Rt(n,e);return r===n?t:[...t.slice(0,-1),r]}function Mt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Dr(n,e);return r===n?t:[...t.slice(0,-1),r]}function Dr(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=Rt(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Rt(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}import{randomUUID as Fr}from"node:crypto";function _t(t,e){if(!t)return{stopReason:e??null};let n={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};return t.cache_read_input_tokens!=null&&(n.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(n.cacheCreationTokens=t.cache_creation_input_tokens),n.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n}function Dt(t,e){let n=(c,d)=>{if(!(c==null&&d==null))return(c??0)+(d??0)},r={stopReason:e.stopReason??t.stopReason??null},o=n(t.inputTokens,e.inputTokens);o!==void 0&&(r.inputTokens=o);let s=n(t.outputTokens,e.outputTokens);s!==void 0&&(r.outputTokens=s);let i=n(t.cachedInputTokens,e.cachedInputTokens);i!==void 0&&(r.cachedInputTokens=i);let a=n(t.cacheCreationTokens,e.cacheCreationTokens);a!==void 0&&(r.cacheCreationTokens=a);let l=n(t.totalTokens,e.totalTokens);return l!==void 0&&(r.totalTokens=l),r}function Or(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function $r(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):r.push({type:"tool_use",id:a.id,name:a.name,input:Or(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*Ot(t,e){let n=[],r=null,o=null,s=!1;try{for await(let i of t){switch(i.type){case"message_start":{let a=i.message?.usage;a&&(o={...a});break}case"content_block_start":{let a=i.content_block;a.type==="text"?n[i.index]={kind:"text",text:""}:a.type==="thinking"?n[i.index]={kind:"thinking",thinking:"",signature:""}:a.type==="tool_use"&&(n[i.index]={kind:"tool_use",id:a.id,name:a.name,partialJson:""});break}case"content_block_delta":{let a=n[i.index],l=i.delta;l.type==="text_delta"?(a&&a.kind==="text"&&(a.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?a&&a.kind==="tool_use"&&(a.partialJson+=l.partial_json):l.type==="thinking_delta"?(a&&a.kind==="thinking"&&(a.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&a&&a.kind==="thinking"&&(a.signature=l.signature);break}case"content_block_stop":{let a=n[i.index];a&&a.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:a.name,toolUseIds:[a.id],sessionId:e.sessionId}});break}case"message_delta":{i.delta&&i.delta.stop_reason!==void 0&&(r=i.delta.stop_reason);let a=i.usage;a&&(o!==null?(o.output_tokens=a.output_tokens,a.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=a.cache_creation_input_tokens),a.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=a.cache_read_input_tokens),a.input_tokens!=null&&(o.input_tokens=a.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:a.cache_creation_input_tokens??null,cache_read_input_tokens:a.cache_read_input_tokens??null,inference_geo:null,input_tokens:a.input_tokens??0,output_tokens:a.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}}catch(i){yield{kind:"event",event:{type:"error",error:i instanceof Error?i:new Error(String(i))}};return}yield{kind:"turn-result",result:$r(n,r,o)}}var jr=0;function Hr(t){if(!t||typeof t!="object")return"";let e=t,n=e.file_path??e.path??e.filePath;if(typeof n=="string")return" "+n;let r=e.command??e.cmd;if(typeof r=="string"){let s=r.split(`
|
|
2
|
-
`)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}async function*$t(t){let e=t.maxToolUseIterations??jr,n={stopReason:null},r=0,o=Fr(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Re()?Mt(t.messages,_e()):t.messages,a={model:t.model,max_tokens:t.maxTokens,messages:i,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools}:{}},l;try{l=await Promise.resolve(t.client.messages.create(a,{headers:t.headers,signal:t.signal}))}catch(f){if(t.signal.aborted)return;yield{type:"error",error:f instanceof Error?f:new Error(String(f))};return}let c=null,d=!1;try{for await(let f of Ot(l,t.ctx))if(f.kind==="event"){if(f.event.type==="error"){yield f.event,d=!0;break}yield f.event}else{c=f.result;break}}catch(f){if(t.signal.aborted)return;yield{type:"error",error:f instanceof Error?f:new Error(String(f))};return}if(d)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=Dt(n,_t(c.usage,c.stopReason)),c.stopReason!=="tool_use"){c.text.length>0&&(yield{type:"assistant.message",text:c.text,sessionId:t.ctx.sessionId},c.text.length<=200&&(yield{type:"suggestion",suggestion:c.text,sessionId:t.ctx.sessionId})),yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}t.messages.push({role:"assistant",content:c.assistantBlocks});let u=[];for(let f of c.toolUseBlocks)u.push({id:f.id,name:f.name,input:f.input,signal:t.signal}),yield{type:"tool.use.start",toolUseId:f.id,toolName:f.name,toolInput:Hr(f.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(u);else{p=[];for(let f of u){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(f))}catch(
|
|
2
|
+
`)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}async function*$t(t){let e=t.maxToolUseIterations??jr,n={stopReason:null},r=0,o=Fr(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Re()?Mt(t.messages,_e()):t.messages,a={model:t.model,max_tokens:t.maxTokens,messages:i,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools}:{}},l;try{l=await Promise.resolve(t.client.messages.create(a,{headers:t.headers,signal:t.signal}))}catch(f){if(t.signal.aborted)return;yield{type:"error",error:f instanceof Error?f:new Error(String(f))};return}let c=null,d=!1;try{for await(let f of Ot(l,t.ctx))if(f.kind==="event"){if(f.event.type==="error"){yield f.event,d=!0;break}yield f.event}else{c=f.result;break}}catch(f){if(t.signal.aborted)return;yield{type:"error",error:f instanceof Error?f:new Error(String(f))};return}if(d)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=Dt(n,_t(c.usage,c.stopReason)),c.stopReason!=="tool_use"){c.text.length>0&&(yield{type:"assistant.message",text:c.text,sessionId:t.ctx.sessionId},c.text.length<=200&&(yield{type:"suggestion",suggestion:c.text,sessionId:t.ctx.sessionId})),yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}t.messages.push({role:"assistant",content:c.assistantBlocks});let u=[];for(let f of c.toolUseBlocks)u.push({id:f.id,name:f.name,input:f.input,signal:t.signal}),yield{type:"tool.use.start",toolUseId:f.id,toolName:f.name,toolInput:Hr(f.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(u);else{p=[];for(let f of u){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(f))}catch(w){let k=w instanceof Error?w.message:String(w);p.push({content:`Tool execution threw: ${k}`,isError:!0})}}}let m=[];for(let f=0;f<u.length;f++){let w=u[f],k=p[f];yield{type:"tool.output",toolUseId:w.id,content:k.content,...k.isError===!0?{isError:!0}:{},sessionId:t.ctx.sessionId},m.push({type:"tool_result",tool_use_id:w.id,content:k.content,...k.isError===!0?{is_error:!0}:{}})}let g={role:"user",content:m};t.messages.push(g),r+=1;let y=c.toolUseBlocks[c.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${r}: used ${y?.name??"unknown"}`,lastToolName:y?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-s},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:{...n,stopReason:"tool_use_loop_capped"},sessionId:t.ctx.sessionId};return}}}var Lr=["You are a conversation-summarization assistant. The user will paste a","prior conversation between a user and an AI assistant that includes tool","calls and tool results. Produce a concise but complete summary that lets","the AI continue the conversation without losing track.","","Preserve, in this priority order:","1. The user's original intent, explicit asks, constraints, corrections,"," and preferences stated during the conversation.","2. Tool decisions and their outcomes \u2014 file paths read or written, shell"," commands run, search queries, URLs fetched, code edits made, tests"," run, errors observed, and whether each action succeeded or failed.","3. Current state: what has been completed, what remains unresolved, and"," the safest next action.","4. Open questions, pending decisions, blockers, and assumptions.","5. Key facts the assistant discovered (function locations, schemas,"," observed behaviors, important external findings).","","Drop prose narration, conversational filler, and exploratory dead-ends.","Drop verbatim tool output unless an exact snippet, error, path, command,","or result is needed for continuation.","Do not invent details. If something is uncertain, mark it explicitly.","Output plain text, no markdown headers. Aim for ~250 words; use up to","~400 only when needed to preserve tool state or unresolved tasks."].join(`
|
|
3
3
|
`),Ft="[Compacted summary of earlier conversation]",jt="Acknowledged. Continuing from the summary above.";function Ur(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function Ht(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&Ur(o)&&(n+=1,n===e))return r}return-1}function Lt(t,e,n){let r=Nr(t);return{model:e,max_tokens:n,system:Lr,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
4
4
|
|
|
5
5
|
<transcript>
|
|
@@ -801,7 +801,7 @@ Field semantics:
|
|
|
801
801
|
- \`summary\` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.
|
|
802
802
|
`}};function I(t){let e=zt[t];if(!e){let n=Object.keys(zt).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var De=new Map;function G(t){De.set(t.name,t)}function z(t){let e=De.get(t);if(e)return e;let n=Array.from(De.keys()).sort(),r=n.length>0?`
|
|
803
803
|
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function qt(){return Array.from(De.keys()).sort()}var he=class{nodes=new Map;register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,r.children.add(n),r.controller.signal.aborted){o.controller.signal.aborted||(o.cascading=!0,o.controller.abort(r.controller.signal.reason));return}r.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);!s||s.parentId!==e||s.controller.signal.aborted||(s.cascading=!0,s.controller.abort(r.controller.signal.reason))},{once:!0}),o.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);if(!s||s.parentId!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let l of i.listeners)try{l(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n){let r=this.nodes.get(e);if(!r||r.controller.signal.aborted)return;let o=[],s=[...r.children],i=new Set;for(;s.length;){let a=s.shift();if(i.has(a))continue;i.add(a);let l=this.nodes.get(a);if(l){l.cascading=!0,o.push(a);for(let c of l.children)s.push(c)}}r.controller.abort(n);for(let a of o){let l=this.nodes.get(a);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};var ye=0,Oe=5e3;async function be(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new Me(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),i(l)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}async function Vt(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function Kt(t,e,n={}){if(!t)return{};try{return await t.dispatch(e,n.signal)}catch(r){return r instanceof U||r instanceof B?(A(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(A(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{})}}import{mkdir as Gr,writeFile as zr}from"fs/promises";import{join as Wt}from"path";function Yt(){return process.env.HOME||process.env.USERPROFILE||"~"}function qr(){return Wt(Yt(),".claude","agent-framework","routing-decisions.jsonl")}async function Qt(t){if(!(process.env.VITEST||process.env.NODE_ENV==="test"))try{let e=Wt(Yt(),".claude","agent-framework");await Gr(e,{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,surface:"afk",...t})+`
|
|
804
|
-
`;await zr(qr(),r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Vr}from"node:async_hooks";var Kr=new Vr;function le(){return Kr.getStore()}function tt(t){let e=Wr(t);return e!==void 0?e:Yr(t)}function Wr(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return Jt(n.trim())}function Yr(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Qr(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=Jt(r);if(o!==void 0)return o}}function Qr(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function Jt(t){try{return JSON.parse(t)}catch{return}}function Xt(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=tt(n.content),s=r.safeParse(o);return s.success?{id:t,status:e,message:n,output:s.data}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${s.error.message}`,{cause:s.error}),schemaError:s.error}}function Zt(t,e,n){let r=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:r}}function C(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var $e=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,m){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;get status(){return this.currentStatus}async run(e){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let n=Date.now(),r=be(this.streamToFinalMessage(e),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=r;try{let o=await r;return this.lastMessage=o.content,this.lastDurationMs=Date.now()-n,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",this.onTerminal(),o}catch(o){throw this.lastDurationMs=Date.now()-n,this.currentStatus!=="cancelled"&&(this.currentStatus="failed",this.latestTerminalStatus="failed"),this.onTerminal(),o}finally{this.inFlight=null}}async streamToFinalMessage(e){let n,r="",o,s=this.progressSink??le(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e))if(s&&s(a,i),a.type==="chunk"&&a.chunk.type==="content"&&(r+=a.chunk.content),a.type==="message")n=a.message;else if(a.type==="error"){o=a.error;break}else if(a.type==="done")break;if(o)throw o;if(n)return n;if(r.length>0)return{role:"assistant",content:r,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e){try{let n=await this.run(e);return Xt(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return Zt(this.id,this.currentStatus,n)}}runInBackground(e,n){this.runToResult(e).then(r=>{n?.(r)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled";try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Kt(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)A(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){A(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var
|
|
804
|
+
`;await zr(qr(),r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Vr}from"node:async_hooks";var Kr=new Vr;function le(){return Kr.getStore()}function tt(t){let e=Wr(t);return e!==void 0?e:Yr(t)}function Wr(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return Jt(n.trim())}function Yr(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Qr(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=Jt(r);if(o!==void 0)return o}}function Qr(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function Jt(t){try{return JSON.parse(t)}catch{return}}function Xt(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=tt(n.content),s=r.safeParse(o);return s.success?{id:t,status:e,message:n,output:s.data}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${s.error.message}`,{cause:s.error}),schemaError:s.error}}function Zt(t,e,n){let r=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:r}}function C(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var $e=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,m){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;get status(){return this.currentStatus}async run(e){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let n=Date.now(),r=be(this.streamToFinalMessage(e),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=r;try{let o=await r;return this.lastMessage=o.content,this.lastDurationMs=Date.now()-n,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",this.onTerminal(),o}catch(o){throw this.lastDurationMs=Date.now()-n,this.currentStatus!=="cancelled"&&(this.currentStatus="failed",this.latestTerminalStatus="failed"),this.onTerminal(),o}finally{this.inFlight=null}}async streamToFinalMessage(e){let n,r="",o,s=this.progressSink??le(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e))if(s&&s(a,i),a.type==="chunk"&&a.chunk.type==="content"&&(r+=a.chunk.content),a.type==="message")n=a.message;else if(a.type==="error"){o=a.error;break}else if(a.type==="done")break;if(o)throw o;if(n)return n;if(r.length>0)return{role:"assistant",content:r,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e){try{let n=await this.run(e);return Xt(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return Zt(this.id,this.currentStatus,n)}}runInBackground(e,n){this.runToResult(e).then(r=>{n?.(r)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled";try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Kt(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)A(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){A(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var x=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;abortGraph=new he;rootId;rootController;counter=0;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}abortAll(e){this.abortGraph.abort(this.rootId,e)}async forkSubagent(e){let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry;o&&await Vt(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,hookRegistry:e.config.hookRegistry??this.hookRegistry,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0)},a=new ne(i),l=e.parent.getInputStreamRef?.(),c=e.parent.abortSignal,d=this.progressSink??le(),u=new $e(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??ye,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,e.idPrefix,d,e.parent.sessionId);return this.active.set(n,u),await Qt({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,parent_session_id:e.parent.sessionId}),u}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function Fe(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,l)=>l)),i=t.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as Jr}from"node:url";import{dirname as Xr}from"node:path";var Zr=Jr(import.meta.url),Za=Xr(Zr),j={name:"research-agent",systemPrompt:`---
|
|
805
805
|
name: research-agent
|
|
806
806
|
description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
|
|
807
807
|
model: sonnet
|
|
@@ -854,13 +854,13 @@ If \`scope_check\` flags implementation (non-git), the orchestrator should dispa
|
|
|
854
854
|
`,sourcePath:"agent-framework-private/agents/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:"Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only."};import{join as re,dirname as nl}from"path";import{homedir as eo}from"os";function oe(){return re(eo(),".afk")}function ce(){return re(oe(),"plugins")}function to(){return re(process.cwd(),".afk")}function je(){return re(to(),"plugins")}function He(){return re(ce(),".index.json")}function no(){return re(oe(),"state")}function en(){return re(no(),"sessions")}import{existsSync as J,readdirSync as uo,readFileSync as po}from"fs";import{join as q}from"path";import{existsSync as nt,readFileSync as so,readdirSync as io,statSync as ao}from"fs";import{join as ve,resolve as nn}from"path";import{existsSync as ro,mkdirSync as il,readFileSync as oo,renameSync as al,writeFileSync as ll,unlinkSync as cl}from"fs";function tn(t=He()){if(!ro(t))return Le();try{let e=oo(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Le();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Le()}catch{return Le()}}function Le(){return{version:2,plugins:{},marketplaces:{}}}var lo=5,rn="cache";function Q(t=ce()){if(!nt(t))return[];let e=t===ce()?He():ve(t,".index.json"),n=tn(e),r=[];return on(t,t,0,r,new Set,n.plugins),r}function on(t,e,n,r,o,s){if(n>lo||o.has(e))return;if(o.add(e),nt(ve(e,".claude-plugin","plugin.json"))){let a=rt(t,e);if(a===null){r.push({type:"local",path:e});return}if(a.layout==="cache"){let c=s[a.key];if(!c||c.enabled===!1)return;r.push({type:"local",path:e});return}let l=s[a.key];if(l&&l.enabled===!1)return;r.push({type:"local",path:e});return}let i;try{i=io(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ve(e,a),c;try{c=ao(l)}catch{continue}c.isDirectory()&&on(t,l,n+1,r,o,s)}}function rt(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===rn&&r.length>=3){let s=r[1];if(s){let i=ve(t,rn,s),l=co(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function co(t,e){let n=ve(t,".claude-plugin","marketplace.json");if(!nt(n))return null;let r;try{r=JSON.parse(so(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=nn(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&nn(t,a.source)===s)return a.name}return null}var sn=["command","agent"];function an(t=oe()){let e=[],n=q(t,"skills");if(J(n))for(let r of Ue(n)){let o=q(n,r,"SKILL.md");J(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of sn){let o=q(t,`${r}s`);if(J(o))for(let s of Ue(o))s.endsWith(".md")&&e.push({path:q(o,s),type:r,source:"user"})}return e}function ln(t=ce()){if(!J(t))return[];let e=[],n=Q(t);for(let r of n){let s=rt(t,r.path)?.key,i=q(r.path,"skills");if(J(i))for(let a of Ue(i)){let l=q(i,a,"SKILL.md");if(!J(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of sn){let l=q(r.path,`${a}s`);if(J(l))for(let c of Ue(l)){if(!c.endsWith(".md"))continue;let d={path:q(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function cn(t=q(oe(),"settings.json")){if(!J(t))return[];try{let e=po(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ue(t){try{return uo(t).filter(e=>!e.startsWith("."))}catch{return[]}}var fn=T.object({path:T.string(),type:T.enum(["skill","command","agent","hook"]),source:T.enum(["user","plugin"]),plugin_key:T.string().optional(),verdict:T.enum(["correct","misfit","outlier"]),recommended_type:T.string(),rationale:T.string(),confidence:T.enum(["high","med","low"])}),pn=T.record(T.string(),T.record(T.string(),T.number())),_l=T.object({inventory:T.object({user:pn,plugin:pn}),misfits:T.array(fn),briefs_written:T.number(),total_artifacts:T.number()}),fo=T.object({writeBriefs:T.boolean().optional(),scope:T.enum(["user","plugin","all"]).optional()}),mo=["skill","command","agent"],mn=["skill","command","agent","hook"];function go(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function ho(t){let e=()=>{let s={};for(let i of mn)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function yo(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function bo(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
855
855
|
`)}function vo(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
856
856
|
`);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
|
|
857
|
-
`)}function wo(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function ko(t,e){let n=typeof t=="object"&&t!==null?t:{},r=fo.parse(n),o=r.writeBriefs??!0,s=r.scope??"all",i=go(s);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let a=e.sessionId,l=I("audit-fit"),c={skill:l["01-skill-inspector.md"],command:l["02-command-inspector.md"],agent:l["03-agent-inspector.md"],hook:l["04-hook-inspector.md"]};for(let
|
|
858
|
-
${bo(
|
|
859
|
-
${vo(
|
|
857
|
+
`)}function wo(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function ko(t,e){let n=typeof t=="object"&&t!==null?t:{},r=fo.parse(n),o=r.writeBriefs??!0,s=r.scope??"all",i=go(s);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let a=e.sessionId,l=I("audit-fit"),c={skill:l["01-skill-inspector.md"],command:l["02-command-inspector.md"],agent:l["03-agent-inspector.md"],hook:l["04-hook-inspector.md"]};for(let v of mn)if(!c[v])throw new Error(`audit-fit skill missing inspector prompt for ${v}`);let d=i.runUserDiscovery?an():[],u=i.runPluginDiscovery?ln():[],p={skill:[],command:[],agent:[]};for(let v of[...d,...u])p[v.type].push(v);let m=new x,g=()=>async v=>j.allowedTools.includes(v)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${v} not allowed for audit-fit inspectors. Allowed tools: ${j.allowedTools.join(", ")}`},y=[];for(let v of mo){let S=p[v];if(S.length===0)continue;let h=c[v];h&&y.push({type:v,prompt:`${h}
|
|
858
|
+
${bo(S)}`,artifacts:S,runPrompt:`Inspect every ${v} listed in the artifact section.`})}if(i.runHookInspector){let v=c.hook;if(v){let S=we(oe(),"settings.json"),h=cn(S);y.push({type:"hook",prompt:`${v}
|
|
859
|
+
${vo(S,h)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${S}.`})}}let f=[];if(y.length>0){let v=await Promise.all(y.map(E=>m.forkSubagent({parent:{sessionId:a},config:{model:"sonnet",systemPrompt:`${j.systemPrompt}
|
|
860
860
|
|
|
861
|
-
${E.prompt}`,canUseTool:g()},idPrefix:`inspector-${E.type}`,outputSchema:T.array(fn)}))),
|
|
861
|
+
${E.prompt}`,canUseTool:g()},idPrefix:`inspector-${E.type}`,outputSchema:T.array(fn)}))),S=await Fe(y.map((E,H)=>{let _=v[H];if(!_)throw new Error(`audit-fit: missing handle for ${E.type} inspector`);return{handle:_,prompt:E.runPrompt}}),{failFast:!1}),h=[];for(let E=0;E<S.length;E++){let H=S[E],_=y[E];if(!_)continue;let ee=wo(_.type,H);if(ee.kind==="failure"){h.push(ee.message);continue}let Ze=new Map;for(let L of _.artifacts)Ze.set(L.path,L.source);for(let L of ee.output){if(_.type==="hook"){if(L.source!=="user"){h.push(`${_.type}: hook verdict has source=${L.source} (must be 'user')`);continue}}else{let te=Ze.get(L.path);if(te===void 0){h.push(`${_.type}: verdict for unknown path ${L.path} (not in discovered list)`);continue}if(L.source!==te){h.push(`${_.type}: verdict source mismatch for ${L.path} (expected ${te}, got ${L.source})`);continue}}f.push(L)}}if(h.length>0){let E=h.map(H=>` - ${H}`).join(`
|
|
862
862
|
`);throw new Error(`audit-fit: ${h.length} inspector failure(s):
|
|
863
|
-
${E}`)}}let{inventory:
|
|
863
|
+
${E}`)}}let{inventory:w,misfits:k}=ho(f),$=0;if(o){let v=process.env.HOME||process.env.USERPROFILE||"~",S=we(v,".claude","agent-framework","briefs");await dn(S,{recursive:!0});for(let h of k.filter(yo)){let E=h.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),H=we(S,`audit-fit-${E}.md`),_=`---
|
|
864
864
|
theme: audit-fit
|
|
865
865
|
session_count: 1
|
|
866
866
|
---
|
|
@@ -882,14 +882,14 @@ ${h.rationale}
|
|
|
882
882
|
|
|
883
883
|
---
|
|
884
884
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
885
|
-
`;await un(H,_)
|
|
886
|
-
`),{inventory:
|
|
885
|
+
`;await un(H,_),$++}}let D=process.env.HOME||process.env.USERPROFILE||"~",P=we(D,".claude","agent-framework");await dn(P,{recursive:!0});let O=v=>{let S=0;for(let h of Object.values(v))for(let E of Object.values(h))S+=E;return S},R=v=>{let S=w.user[v]??{},h=w.plugin[v]??{},E=H=>Object.values(H).reduce((_,ee)=>_+ee,0);return E(S)+E(h)},W={timestamp:new Date().toISOString(),surface:"afk",scope:s,total_artifacts:f.length,misfits_count:k.length,briefs_written:$,by_source:{user:O(w.user),plugin:O(w.plugin)},by_type:{skill:R("skill"),command:R("command"),agent:R("agent"),hook:R("hook")}},Y=we(P,"audit-fit-telemetry.jsonl");return await un(Y,JSON.stringify(W)+`
|
|
886
|
+
`),{inventory:w,misfits:k,briefs_written:$,total_artifacts:f.length}}var So={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:ko,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"]};G(So);import{z as b}from"zod";import{execFile as Ao}from"node:child_process";import{promisify as To}from"node:util";import{tmpdir as Co}from"node:os";import{join as Io}from"node:path";function gn(t){return t.confidence<.5?{verify:!0,reason:`low confidence (${t.confidence.toFixed(2)} < ${.5})`}:t.boundary_flag&&t.boundary_flag.length>0?{verify:!0,reason:`boundary flag set: ${t.boundary_flag}`}:t.coverage_gaps&&t.coverage_gaps.length>0?{verify:!0,reason:`coverage gap${t.coverage_gaps.length===1?"":"s"}: ${t.coverage_gaps.length} unresolved`}:{verify:!1,reason:`confidence ${t.confidence.toFixed(2)} with no gaps or boundary`}}import{fileURLToPath as xo}from"node:url";import{dirname as Po}from"node:path";var Eo=xo(import.meta.url),Hl=Po(Eo),ot={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\nmodel: sonnet\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"agent-framework-private/agents/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"};function st(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var hn=To(Ao),vn=b.object({id:b.string(),claim:b.string(),confidence:b.number().min(0).max(1),evidence_sources:b.array(b.string()),location:b.string().optional(),proposed_fix:b.string().optional(),coverage_gaps:b.array(b.string()).optional(),boundary_flag:b.string().optional()}),Mo=b.object({hypothesis_id:b.string(),claim:b.string(),verdict:b.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:b.string(),gate_reason:b.string()}),wn=b.object({hypothesis_id:b.string(),reproducer_passed:b.boolean(),regressions:b.array(b.string()),confidence:b.number().min(0).max(1),verification_log:b.string()}),tc=b.object({reproducer:b.string().optional(),hypotheses:b.array(vn),premise_verifications:b.array(Mo).optional(),winner:b.object({hypothesis_id:b.string(),verification_log:b.string(),proposed_fix:b.string()}).optional(),verification_results:b.array(wn).optional()});async function Ro(t,e){let n=t.map(l=>({hypothesis:l,decision:gn(l)})).filter(l=>l.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{r=await e(n.map(l=>l.hypothesis.claim))}catch(l){o=l instanceof Error?l.message:String(l)}let s=n.map((l,c)=>{let d=r[c];return o!==void 0?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:l.decision.reason}:d?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:l.decision.reason}:{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:l.decision.reason}}),i=new Set(s.filter(l=>l.verdict==="REFUTED").map(l=>l.hypothesis_id)),a=i.size===0?t:t.filter(l=>!i.has(l.id));return{premise_verifications:s,hypotheses_to_test:a}}async function _o(t,e){let n=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let h=t;if(typeof h.failure=="string")return{failure:h.failure,repoPath:h.repoPath||process.cwd(),context:h.context||"",maxHypotheses:Math.min(h.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!e?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let r=e.sessionId,o=I("diagnose"),s=o["system.md"],i=o["research.md"],a=o["hypothesis.md"],l=o["verify.md"];if(!s||!i||!a||!l)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let c=new x,d=Do(n.context),u=`${j.systemPrompt}
|
|
887
887
|
|
|
888
888
|
${i}
|
|
889
889
|
|
|
890
890
|
Focus: CODEBASE
|
|
891
891
|
Failure: ${n.failure}${n.context?`
|
|
892
|
-
Context: ${n.context}`:""}`,p=`${
|
|
892
|
+
Context: ${n.context}`:""}`,p=`${j.systemPrompt}
|
|
893
893
|
|
|
894
894
|
${i}
|
|
895
895
|
|
|
@@ -897,17 +897,17 @@ Focus: GIT HISTORY
|
|
|
897
897
|
Failure: ${n.failure}${n.context?`
|
|
898
898
|
Context: ${n.context}`:""}
|
|
899
899
|
|
|
900
|
-
Repo: ${n.repoPath}`,m=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:u,canUseTool:yn()},idPrefix:"diagnose-codebase-research"}),g=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:p,cwd:n.repoPath,agents:{"git-investigator":st(ot)},canUseTool:Oo()},idPrefix:"diagnose-git-research"}),[y,f]=await Fe([{handle:m,prompt:"Analyze the codebase for potential causes of this failure."},{handle:g,prompt:"Analyze git history for recent changes that could cause this failure."}],{failFast:!1}),
|
|
900
|
+
Repo: ${n.repoPath}`,m=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:u,canUseTool:yn()},idPrefix:"diagnose-codebase-research"}),g=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:p,cwd:n.repoPath,agents:{"git-investigator":st(ot)},canUseTool:Oo()},idPrefix:"diagnose-git-research"}),[y,f]=await Fe([{handle:m,prompt:"Analyze the codebase for potential causes of this failure."},{handle:g,prompt:"Analyze git history for recent changes that could cause this failure."}],{failFast:!1}),w={codebase:y?.output||y?.message||"No output",git:f?.output||f?.message||"No output"},k=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${s}
|
|
901
901
|
|
|
902
|
-
${a}`,canUseTool:yn()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:b.object({hypotheses:b.array(vn)})})
|
|
902
|
+
${a}`,canUseTool:yn()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:b.object({hypotheses:b.array(vn)})}),$=`Given these research findings, synthesize 2\u20134 hypotheses (max 4):
|
|
903
903
|
|
|
904
904
|
CODEBASE RESEARCH:
|
|
905
|
-
${JSON.stringify(
|
|
905
|
+
${JSON.stringify(w.codebase,null,2)}
|
|
906
906
|
|
|
907
907
|
GIT RESEARCH:
|
|
908
|
-
${JSON.stringify(
|
|
908
|
+
${JSON.stringify(w.git,null,2)}
|
|
909
909
|
|
|
910
|
-
Original failure: ${n.failure}`,D;try{D=await
|
|
910
|
+
Original failure: ${n.failure}`,D;try{D=await k.runToResult($)}finally{await k.teardown().catch(()=>{})}if(D.status!=="succeeded"||!D.output)throw new Error(`hypothesis synthesis failed: ${C(D)}`);let P=D.output.hypotheses.slice(0,n.maxHypotheses);if(P.length===0)return{reproducer:d,hypotheses:[],verification_results:[]};let{premise_verifications:O,hypotheses_to_test:R}=await Ro(P,async h=>{let E=z("shadow-verify");if(!E)throw new Error("shadow-verify skill not registered");return(await E.handler({claims:h,context:`Original failure: ${n.failure}`},e)).verifications});if(R.length===0)return{reproducer:d,hypotheses:P,premise_verifications:O,verification_results:[]};let W=d||n.failure,Y=R.map(h=>$o(h,W,n.repoPath,r,l,c)),v=await Promise.all(Y),S=v.find(h=>h.reproducer_passed);return{reproducer:d,hypotheses:P,premise_verifications:O.length>0?O:void 0,winner:S?{hypothesis_id:S.hypothesis_id,verification_log:S.verification_log,proposed_fix:P.find(h=>h.id===S.hypothesis_id)?.proposed_fix||""}:void 0,verification_results:v}}function Do(t){if(!t)return;let e=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of e){let r=t.match(n);if(r)return r[1]}}function yn(){return async t=>j.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${j.allowedTools.join(", ")}`}}var bn=[...j.allowedTools,"Agent"];function Oo(){return async t=>bn.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${bn.join(", ")}`}}async function $o(t,e,n,r,o,s){let i=Io(Co(),`diagnose-hyp-${t.id}-${Date.now()}`),a;try{await hn("git",["worktree","add","--detach",i,"HEAD"],{cwd:n}),a=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
|
|
911
911
|
|
|
912
912
|
You are testing in an isolated worktree at: ${i}`,canUseTool:Fo()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:wn});let l=`Test this hypothesis:
|
|
913
913
|
|
|
@@ -916,7 +916,7 @@ Location: ${t.location||"unknown"}
|
|
|
916
916
|
Proposed fix: ${t.proposed_fix||"unknown"}
|
|
917
917
|
Reproducer: ${e}
|
|
918
918
|
|
|
919
|
-
Working directory (isolated): ${i}`,c=await a.runToResult(l);return c.status!=="succeeded"||!c.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${C(c)}`}:c.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(a)try{await a.teardown()}catch{}try{await hn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function Fo(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:
|
|
919
|
+
Working directory (isolated): ${i}`,c=await a.runToResult(l);return c.status!=="succeeded"||!c.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${C(c)}`}:c.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(a)try{await a.teardown()}catch{}try{await hn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function Fo(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:j.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${j.allowedTools.join(", ")}`}}var jo={name:"diagnose",description:"Parallel root-cause analysis for bugs and failing tests \u2014 forks research subagents, synthesizes hypotheses, and validates each in isolated worktrees",handler:_o,argumentHint:"<bug-or-failing-test>",whenToUse:"When a test is failing, a bug is reported, or behavior is unexplained \u2014 runs parallel root-cause analysis with hypothesis sub-agents."};G(jo);import{z as N}from"zod";import{execFile as Qo}from"child_process";import{promisify as Jo}from"util";import{mkdir as In,writeFile as Mn}from"fs/promises";import{existsSync as Cn}from"fs";import{join as X}from"path";import{fileURLToPath as Xo}from"url";import{fileURLToPath as Ho}from"node:url";import{dirname as Lo}from"node:path";var Uo=Ho(import.meta.url),ic=Lo(Uo),it={name:"qualify",systemPrompt:`---
|
|
920
920
|
name: qualify
|
|
921
921
|
description: Gate proposed plugin skills. Approve only real force multipliers. Reject reminders, checklists, best-practice nudges, and generic execution advice. Invoke when evaluating whether a proposed skill deserves top-level status in this plugin.
|
|
922
922
|
model: sonnet
|
|
@@ -1143,25 +1143,25 @@ Be skeptical. Protect the plugin from fluff. Stage 2 catches patterns that are s
|
|
|
1143
1143
|
`).map(l=>l.trim()).filter(l=>l),n=e.find(l=>/^(APPROVE|SALVAGE|REJECT)/.test(l));if(!n)return{verdict:"REJECT",feedback:t};let r=n.match(/^(APPROVE|SALVAGE|REJECT)/)?.[1];if(!r)return{verdict:"REJECT",feedback:t};let o=t.match(/score:\s*(\d+)/i),s=o&&o[1]?parseInt(o[1],10):void 0,i=e.indexOf(n),a=e.slice(i+1).join(`
|
|
1144
1144
|
`).trim();return{verdict:r,score:s,feedback:a||n}}var Zo=Jo(Qo);function es(){let t=process.env.AFK_EVAL_HARNESS_ROOT;if(t){let o=X(t,"scripts","eval-harness","runner.py");if(Cn(o))return o}let e=Xo(import.meta.url),n=X(e,"../../../.."),r=X(n,"..","awa-private","scripts","eval-harness","runner.py");if(Cn(r))return r;throw new Error(`Could not find eval-harness runner.py. Tried: ${r}`)}function ts(t){return X(t,"..","..","..","plugins","awa-private")}function ns(){let t=process.env.HOME||process.env.USERPROFILE||"~";return X(t,".claude","agent-framework","ceiling-ledger")}function rs(t){let e=t.split(`
|
|
1145
1145
|
`),n=[],r=/^\s+✗\s+(\S+):/;for(let o of e){let s=o.match(r);s&&s[1]&&n.push(s[1])}return n}async function os(t){let e=ns(),n=X(e,"qualifications.jsonl");await In(e,{recursive:!0});let o=new Date().toISOString().split(".")[0]+"Z",i=JSON.stringify({timestamp:o,surface:"atlas",refers_to_run_id:t,source:"forge-gate-check-ts"})+`
|
|
1146
|
-
`;return await Mn(n,i,{flag:"a"}),o}async function ss(){let t;try{t=es()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=ts(t),n="",r="",o=0;try{let l=await Zo("python3",[t,"--plugin-root",e],{timeout:6e4});n=l.stdout||"",r=l.stderr||"",o=0}catch(l){let c=l;if(n=c.stdout||"",r=c.stderr||"",o=typeof c.code=="number"?c.code:1,c.code==="ENOENT"||r&&r.includes("No such file"))throw new Error(`eval-harness runner.py not found at ${t}.`)}let s=o===0?"OPEN":"CLOSED",i=s==="CLOSED"?rs(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await os(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var is=N.object({iteration:N.number().int().positive(),verdict:N.enum(["APPROVE","SALVAGE","REJECT"]),score:N.number().optional(),feedback:N.string()}),zc=N.object({status:N.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:N.string().optional(),qualify_verdicts:N.array(is),brief_id:N.string().optional(),telemetry_ref:N.string()});async function as(t,e){let n=typeof t=="string"?{brief:t}:typeof t=="object"&&t!==null?t:{},r=n.brief,o=n.forceThaw??!1,s=n.maxIterations??3,i="",a=[],l="REJECTED",c,d;try{let u=await ss();if(u.gate_status==="CLOSED"&&!o)return i=await V({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:i};o&&u.gate_status==="CLOSED"&&(await xn(),i=await V({event:"forge.thaw_override",gate_status:"CLOSED"})),i=await V({event:"forge.gate_check",gate_status:"OPEN"});let p="",m=!1;if(r)p=r,m=!0;else{let P=await An();if(P.length>0){let O=P[0],R=await En(O);p=R.content,d=R.id,m=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let R=I("forge")["gap-discovery.md"];if(!R)throw new Error("forge skill missing gap-discovery.md prompt");let
|
|
1146
|
+
`;return await Mn(n,i,{flag:"a"}),o}async function ss(){let t;try{t=es()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=ts(t),n="",r="",o=0;try{let l=await Zo("python3",[t,"--plugin-root",e],{timeout:6e4});n=l.stdout||"",r=l.stderr||"",o=0}catch(l){let c=l;if(n=c.stdout||"",r=c.stderr||"",o=typeof c.code=="number"?c.code:1,c.code==="ENOENT"||r&&r.includes("No such file"))throw new Error(`eval-harness runner.py not found at ${t}.`)}let s=o===0?"OPEN":"CLOSED",i=s==="CLOSED"?rs(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await os(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var is=N.object({iteration:N.number().int().positive(),verdict:N.enum(["APPROVE","SALVAGE","REJECT"]),score:N.number().optional(),feedback:N.string()}),zc=N.object({status:N.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:N.string().optional(),qualify_verdicts:N.array(is),brief_id:N.string().optional(),telemetry_ref:N.string()});async function as(t,e){let n=typeof t=="string"?{brief:t}:typeof t=="object"&&t!==null?t:{},r=n.brief,o=n.forceThaw??!1,s=n.maxIterations??3,i="",a=[],l="REJECTED",c,d;try{let u=await ss();if(u.gate_status==="CLOSED"&&!o)return i=await V({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:i};o&&u.gate_status==="CLOSED"&&(await xn(),i=await V({event:"forge.thaw_override",gate_status:"CLOSED"})),i=await V({event:"forge.gate_check",gate_status:"OPEN"});let p="",m=!1;if(r)p=r,m=!0;else{let P=await An();if(P.length>0){let O=P[0],R=await En(O);p=R.content,d=R.id,m=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let R=I("forge")["gap-discovery.md"];if(!R)throw new Error("forge skill missing gap-discovery.md prompt");let v=await(await new x().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:R},idPrefix:"forge-gap-discovery"})).runToResult("Identify the most impactful skill gap.");if(v.status!=="succeeded")throw new Error(`gap discovery failed: ${C(v)}`);if(p=v.message?.content||"",!p)throw new Error("gap discovery returned no concept")}}if(i=await V({event:"forge.brief_loaded",used_brief:m,brief_id:d||null}),!e?.sessionId)throw new Error("forge requires parent session for skill generation");let g=I("forge"),y=g["generate.md"],f=g["system.md"];if(!y)throw new Error("forge skill missing generate.md prompt");if(!f)throw new Error("forge skill missing system.md prompt");let $=await(await new x().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:f},idPrefix:"forge-generate"})).runToResult(`Generate a new amplifier skill based on this concept:
|
|
1147
1147
|
|
|
1148
|
-
${p}`);if(
|
|
1148
|
+
${p}`);if($.status!=="succeeded")throw new Error(`skill generation failed: ${C($)}`);let D=$.message?.content||"";if(!D)throw new Error("skill generation returned no output");for(let P=1;P<=s;P++){let O=it.systemPrompt;if(!O)throw new Error("qualify agent missing system prompt");let Y=await(await new x().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:O},idPrefix:`forge-qualify-${P}`})).runToResult(`Evaluate this amplifier skill against the force-multiplier criteria:
|
|
1149
1149
|
|
|
1150
|
-
${D}`);if(Y.status!=="succeeded")throw new Error(`qualify iteration ${P} failed: ${C(Y)}`);let
|
|
1150
|
+
${D}`);if(Y.status!=="succeeded")throw new Error(`qualify iteration ${P} failed: ${C(Y)}`);let v=Y.message?.content||"",{verdict:S,score:h,feedback:E}=Tn(v),H={iteration:P,verdict:S,score:h,feedback:E};if(a.push(H),i=await V({event:"forge.qualify_iteration",iteration:P,verdict:S,score:h||null}),S==="APPROVE"){l="APPROVED";break}else if(S==="SALVAGE"&&P<s){let _=g["qualify-rework.md"];if(!_)throw new Error("forge skill missing qualify-rework.md prompt");let ee=_.replace("{feedback}",E).replace("{original_skill}",D),te=await(await new x().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:ee},idPrefix:`forge-rework-${P}`})).runToResult("Refine the skill based on the feedback.");if(te.status!=="succeeded")throw new Error(`rework iteration ${P} failed: ${C(te)}`);if(D=te.message?.content||"",!D)throw new Error(`rework iteration ${P} returned no output`)}else S==="REJECT"&&P>=s&&(l="MAX_ITERATIONS")}if(l==="APPROVED"){let P=D.match(/^name:\s*([^\n]+)/m),O=P&&P[1]?P[1].trim().replace(/^["']|["']$/g,""):"unknown",R=X(se(),".claude","agent-framework-local","skills",O);await In(R,{recursive:!0});let W=X(R,"SKILL.md");await Mn(W,D,"utf-8"),c=W,m&&d&&await lt(d,"consumed"),i=await V({event:"forge.complete",status:"APPROVED",skill_name:O,iterations:a.length})}else l==="MAX_ITERATIONS"&&(m&&d&&await lt(d,"failed"),i=await V({event:"forge.complete",status:"MAX_ITERATIONS",iterations:a.length}))}catch(u){throw i=await V({event:"forge.error",error:u instanceof Error?u.message:String(u)}),u}return{status:l,skill_path:c,qualify_verdicts:a,brief_id:d,telemetry_ref:i}}var ls={name:"forge",description:'Creates new amplifier skills gated by forge-gate-check, with autonomous gap discovery, skill generation, and qualify iteration loop \u22643\xD7. Writes approved skills and appends telemetry to shared JSONL with surface: "atlas".',handler:as,argumentHint:"[--brief <path>]",whenToUse:"When the user wants to grow the plugin with a new amplifier skill \u2014 autonomously generates and validates one.",flags:["--brief"]};G(ls);var cs={name:"bash",description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},ds={name:"read_file",description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},us={name:"write_file",description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},ps={name:"edit_file",description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},fs={name:"glob",description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},ms={name:"grep",description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Uses grep -rn (or ripgrep if available). Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (basic regex by default)."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'}},required:["pattern"]}},gs={name:"list_directory",description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},Rn={name:"agent",description:"Dispatch a subtask to an independent agent session. The agent runs with its own conversation context and tool access. Use for tasks that benefit from isolated context (research, parallel work, specialized focus). The agent runs to completion and returns its final response.",input_schema:{type:"object",properties:{prompt:{type:"string",description:"The task for the agent to perform."},model:{type:"string",description:"Model for the agent. Defaults to parent session model. Override per-call to right-size cost vs. capability \u2014 `haiku` (cheapest/fastest), `sonnet` (general-use), `opus` (most capable). Append `_1m` (e.g. `sonnet_1m`) for 1M-context variants. Full model IDs are also accepted."},max_turns:{type:"number",description:"Maximum conversation turns (default 10, max 50)."},id_prefix:{type:"string",description:"Label prefix for log correlation."}},required:["prompt"]}},_n={name:"skill",description:"Invoke a registered skill by name. Skills are specialized capabilities that dispatch subagents with domain-specific prompts. Check the system prompt for the list of available skills and their descriptions.",input_schema:{type:"object",properties:{name:{type:"string",description:'Skill name (e.g., "mint", "diagnose", "shadow-verify").'},arguments:{type:"string",description:"Arguments to pass to the skill."}},required:["name"]}},de=[cs,ds,us,ps,fs,ms,gs],Dn=de.map(t=>t.name);import{config as nd}from"dotenv";var On={opus:"claude-opus-4-7",opus_1m:"claude-opus-4-7",sonnet:"claude-sonnet-4-6",sonnet_1m:"claude-sonnet-4-6",haiku:"claude-haiku-4-5-20251001"};function $n(t){return t in On}function Fn(t){let e=On[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function Se(t){if(t!==void 0)return typeof t=="string"&&$n(t)?Fn(t):t}import{execFileSync as hs}from"child_process";import{existsSync as ys,readFileSync as bs}from"fs";import{homedir as vs,userInfo as ws}from"os";import{join as ks}from"path";function jn(){let t=Ss();if(t===void 0)return;let e=xs(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}function Ss(){if(process.platform==="darwin")try{return hs("security",["find-generic-password","-s","Claude Code-credentials","-a",ws().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=ks(vs(),".claude",".credentials.json");if(!ys(t))return;try{return bs(t,"utf-8")}catch{return}}}function xs(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s=r.expiresAt,i={accessToken:o};return typeof s=="number"&&(i.expiresAt=s),i}function Hn(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||jn()}function F(){return Hn()}async function Ln(t,e){let r=I("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new x().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:F()},idPrefix:"mint-spec"})).runToResult(`Create a detailed specification for: ${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`spec phase failed: ${C(i)}`);return i.message.content}async function Un(t,e){let r=I("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new x().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:F()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
|
|
1151
1151
|
|
|
1152
|
-
${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function Nn(t,e,n){let o=I("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new
|
|
1152
|
+
${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function Nn(t,e,n){let o=I("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new x().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:F()},idPrefix:"mint-plan"}),a=`Specification:
|
|
1153
1153
|
${t}
|
|
1154
1154
|
|
|
1155
1155
|
Research findings:
|
|
1156
1156
|
${e}
|
|
1157
1157
|
|
|
1158
|
-
Create a detailed implementation plan based on the spec and research.`,l=await i.runToResult(a);if(l.status!=="succeeded"||!l.message)throw new Error(`plan phase failed: ${C(l)}`);return l.message.content}function As(t){let e=t.match(/\.\w+\s/g)||[],n=t.match(/Files?:\s*(.+?)(?:\n|$)/gi)||[],r=e.length;for(let o of n){let s=o.replace(/Files?:\s*/i,"").split(/[,;]/g).filter(i=>i.trim().length>0);r+=s.length}return r}async function Bn(t,e){if(As(t)<3)return null;try{return await z("parallelize").handler({plan:t})}catch(r){return console.warn(`Parallelize dispatch failed: ${r instanceof Error?r.message:String(r)}`),null}}import{z as K}from"zod";function ue(t){let e=le();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var Ts=K.object({status:K.enum(["PASS","FAIL"]),status_reason:K.string().optional(),files_changed:K.array(K.string()),tests_passed:K.boolean(),build_passed:K.boolean().optional(),verification_passed:K.boolean().optional(),notes:K.string()});async function Gn(t,e,n){let o=I("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new
|
|
1158
|
+
Create a detailed implementation plan based on the spec and research.`,l=await i.runToResult(a);if(l.status!=="succeeded"||!l.message)throw new Error(`plan phase failed: ${C(l)}`);return l.message.content}function As(t){let e=t.match(/\.\w+\s/g)||[],n=t.match(/Files?:\s*(.+?)(?:\n|$)/gi)||[],r=e.length;for(let o of n){let s=o.replace(/Files?:\s*/i,"").split(/[,;]/g).filter(i=>i.trim().length>0);r+=s.length}return r}async function Bn(t,e){if(As(t)<3)return null;try{return await z("parallelize").handler({plan:t})}catch(r){return console.warn(`Parallelize dispatch failed: ${r instanceof Error?r.message:String(r)}`),null}}import{z as K}from"zod";function ue(t){let e=le();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var Ts=K.object({status:K.enum(["PASS","FAIL"]),status_reason:K.string().optional(),files_changed:K.array(K.string()),tests_passed:K.boolean(),build_passed:K.boolean().optional(),verification_passed:K.boolean().optional(),notes:K.string()});async function Gn(t,e,n){let o=I("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new x().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:F()},idPrefix:"mint-build",outputSchema:Ts}),a=`Implementation plan:
|
|
1159
1159
|
${t}
|
|
1160
1160
|
|
|
1161
1161
|
`+(e?`Wave orchestration plan:
|
|
1162
1162
|
${JSON.stringify(e,null,2)}
|
|
1163
1163
|
|
|
1164
|
-
`:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return ue({kind:"checkpoint",title:"build",body:[`Files changed: ${d.filesChanged.length}`,`Tests: ${d.testsPassed?"passed":"failed"}`,"Next: verify"]}),d}import{z as pe}from"zod";var Cs=pe.object({status:pe.enum(["PASS","FAIL"]),status_reason:pe.string().optional(),issues:pe.array(pe.string()).default([]),summary:pe.string().optional()});async function ct(t,e,n,r,o){let i=await new
|
|
1164
|
+
`:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return ue({kind:"checkpoint",title:"build",body:[`Files changed: ${d.filesChanged.length}`,`Tests: ${d.testsPassed?"passed":"failed"}`,"Next: verify"]}),d}import{z as pe}from"zod";var Cs=pe.object({status:pe.enum(["PASS","FAIL"]),status_reason:pe.string().optional(),issues:pe.array(pe.string()).default([]),summary:pe.string().optional()});async function ct(t,e,n,r,o){let i=await new x().forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:o,apiKey:F()},idPrefix:`mint-verify-${t}`,outputSchema:Cs}),a=`Plan:
|
|
1165
1165
|
${e}
|
|
1166
1166
|
|
|
1167
1167
|
Build results:
|
|
@@ -1174,7 +1174,7 @@ Tests: ${n.testsPassed?"PASS":"FAIL"}
|
|
|
1174
1174
|
Lint: ${n.lintPassed?"PASS":"FAIL"}
|
|
1175
1175
|
Design: ${n.designReviewPassed?"PASS":"FAIL"}
|
|
1176
1176
|
Issues: ${n.issues?.join(`
|
|
1177
|
-
`)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let
|
|
1177
|
+
`)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let $=a.winner;typeof $.proposed_fix=="string"&&(l=$.proposed_fix)}let d=I("mint")["heal.md"];if(!d)throw new Error("mint skill missing heal.md prompt");let p=await new x().forkSubagent({parent:{sessionId:o.sessionId},config:{model:"sonnet",systemPrompt:d,apiKey:F()},idPrefix:"mint-heal"}),m=n.issues?.join(`
|
|
1178
1178
|
`)??"none",g=`Plan:
|
|
1179
1179
|
${t}
|
|
1180
1180
|
|
|
@@ -1184,7 +1184,7 @@ ${l}
|
|
|
1184
1184
|
Verification issues:
|
|
1185
1185
|
${m}
|
|
1186
1186
|
|
|
1187
|
-
Apply the fix and update the implementation.`,y=await p.runToResult(g);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${C(y)}`);let f=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(y.message.content)?.[1]?.toLowerCase()==="true",
|
|
1187
|
+
Apply the fix and update the implementation.`,y=await p.runToResult(g);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${C(y)}`);let f=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(y.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!f)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let k=await Be(t,e,o.sessionId);return{healed:k.testsPassed&&k.lintPassed&&k.designReviewPassed,newHealIterations:w,newVerifyResults:k}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}async function qn(t,e){let r=I("mint")["ship.md"];if(!r)throw new Error("mint skill missing ship.md prompt");let s=await new x().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:F()},idPrefix:"mint-ship"}),i=`Idea: ${t.idea}
|
|
1188
1188
|
|
|
1189
1189
|
Specification:
|
|
1190
1190
|
${t.spec}
|
|
@@ -1204,9 +1204,9 @@ Create a ship-ready summary with next steps.`,a=await s.runToResult(i);if(a.stat
|
|
|
1204
1204
|
`);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let d=l.slice(0,c).trim(),u=l.slice(c+1).trim();d==="name"?i.name=u.replace(/^["']|["']$/g,""):d==="description"?i.description=u.replace(/^["']|["']$/g,""):d==="argumentHint"&&(i.argumentHint=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function Zn(t){let e=pt(t);if(e.length===0)return"";let n=[];for(let r of e){let o=r.argumentHint?`${r.argumentHint}`:"",s=o?`- \`${r.name} ${o}\`: ${r.description}`:`- ${r.name}: ${r.description}`;n.push(s),r.whenToUse&&n.push(` When to use: ${r.whenToUse}`)}return["Available skills (invoke via the `skill` tool):",...n].join(`
|
|
1205
1205
|
`)}function pt(t){let e=[],n=new Set;for(let o of qt()){let s=z(o);e.push({name:o,description:s.description,source:s.origin==="user"?"user":s.origin==="project"?"project":"builtin",argumentHint:s.argumentHint,whenToUse:s.whenToUse}),n.add(o)}let r=t??[...Q(je()),...Q()];for(let o of r){if(o.type!=="local")continue;let s=Xn(o.path);for(let i of s)!i.name||n.has(i.name)||(e.push({name:i.name,description:i.description??`Skill from plugin at ${o.path}`,source:"plugin"}),n.add(i.name))}return e}var Ks=3,Ws="claude-haiku-4-5-20251001",Ys=1024,Qs=[{value:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-4-5-20250929",displayName:"Claude Opus 4.5",description:"Highest-capability Claude"},{value:"claude-haiku-4-5-20250929",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],Ge=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=ft(),this.promptStream=e.promptStream,this.toolDispatcher=e.toolDispatcher,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.userSystem=e.userSystem,this.currentModel=e.model,this.currentPermissionMode=e.permissionMode??"default",this.closedPromise=new Promise(n=>{this.closeResolve=()=>n("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=new AbortController;if(this.abortController=i,this.pendingAbortReason!==null&&!i.signal.aborted&&(i.abort(this.pendingAbortReason),this.pendingAbortReason=null),i.signal.aborted)return;this.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=et(this.authMode,this.initSessionId,ft()),c={client:this.client,messages:this.messages,system:a,tools:this.tools,toolDispatcher:this.toolDispatcher,model:this.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId}};try{for await(let d of $t(c)){if(this.closed)return;d.type==="turn.completed"&&(this.lastUsage=d.usage),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abortController===i&&(this.abortController=null)}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.userSystem,r=[];return e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n}),r.length===0?null:Re()?It(r,_e()):r}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&e.length>0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=e}async supportedCommands(){try{return pt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return Qs.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:this.lastUsage}}async mcpServerStatus(){return[]}async accountInfo(){return{subscriptionType:this.authMode==="oauth"?"claude-subscription":"api-key"}}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){let e=this.messages.length;if(this.closed)return{compacted:!1,reason:"session-closed",messagesBefore:e,messagesAfter:e};if(this.abortController!==null)return{compacted:!1,reason:"turn-in-flight",messagesBefore:e,messagesAfter:e};let n=Js(),r=Ht(this.messages,n);if(r<=0)return{compacted:!1,reason:"history-too-short",messagesBefore:e,messagesAfter:e};let o=this.messages.slice(0,r),s=Xs(),i=Lt(o,s,Ys),a=new AbortController;this.abortController=a,this.pendingAbortReason!==null&&!a.signal.aborted&&(a.abort(this.pendingAbortReason),this.pendingAbortReason=null);let l;try{if(a.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e};let u=et(this.authMode,this.initSessionId,ft()),p=this.client,m=await Promise.resolve(p.messages.create(i,{headers:u,signal:a.signal}));l=await Zs(m)}catch(u){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(u instanceof Error?u.message:String(u)),messagesBefore:e,messagesAfter:e}}finally{this.abortController===a&&(this.abortController=null)}if(l.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:e,messagesAfter:e};let c=Nt(this.messages,r,l),d=Ut(this.messages,r,l);return this.messages.splice(0,this.messages.length,...d),{compacted:!0,messagesBefore:e,messagesAfter:this.messages.length,tokensSavedEstimate:c}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.()}};function Js(){let t=process.env.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Ks}function Xs(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Ws}async function Zs(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var ei=new Set(["read_file","glob","grep","list_directory"]);function Ee(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:ei.has(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" requires explicit permission (add to allowedTools config)`}}var ti=new Set(["agent","read_file","glob","grep","list_directory"]);function er(t){return ti.has(t)}function ni(t,e){return t.reduce((n,r,o)=>{let s=e(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var ie=class{handlers;schemas;hookRegistry;permissions;subagentExecutor;skillExecutor;classifier;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.classifier=e.concurrencyClassifier??er}get toolDefs(){return this.schemas}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0};if(this.hookRegistry){let s={event:"PreToolUse",toolName:e.name,input:e.input};try{await this.hookRegistry.dispatch(s,e.signal)}catch(i){if(i instanceof U)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=Ee(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s;try{s=await this.subagentExecutor.execute(e)}catch(i){s={content:`Agent tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s;try{s=await this.skillExecutor.execute(e)}catch(i){s={content:`Skill tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}let r=this.handlers.get(e.name);if(!r)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let o;try{o=await r(e.input,e.signal)}catch(s){o={content:`Tool execution error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}if(this.hookRegistry){let s={event:"PostToolUse",toolName:e.name,output:o.content};try{await this.hookRegistry.dispatch(s,e.signal)}catch{}}return o}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let c={event:"PreToolUse",toolName:a.name,input:a.input};try{await this.hookRegistry.dispatch(c,a.signal)}catch(d){if(d instanceof U){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0},r.add(i);continue}throw d}}let l=Ee(a.name,this.permissions);l.allowed||(n[i]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0},r.add(i))}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=ni(o.map(i=>i.call),this.classifier);for(let i of s){if(e[0].signal.aborted){for(let a of i.indices){let l=o[a].originalIndex;n[l]={content:"Tool call aborted",isError:!0}}continue}if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:d}=o[l];return{result:await this.executeCore(c),originalIndex:d}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),d=i.indices[a.indexOf(l)];n[o[d].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0};continue}n[c]=await this.executeCore(l)}}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};this.hookRegistry.dispatch(o,r).catch(()=>{})}};import{spawn as ri}from"child_process";function oi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function si(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var tr=async(t,e)=>{let{command:n,timeout_ms:r}=oi(t);return e.aborted?{content:"Command aborted",isError:!0}:new Promise(o=>{let s=!1;function i(p){s||(s=!0,clearTimeout(l),e.removeEventListener("abort",u),o(p))}let a=ri(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",d="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{d+=p.toString()});let u=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",u),a.on("close",()=>{let p=(c+d).trimEnd();p=si(p);let m=1e5;p.length>m&&(p=p.slice(0,m)+`
|
|
1206
1206
|
[output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as ii}from"fs";var nr=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.file_path,o=n.offset??1,s=n.limit??2e3;if(typeof r!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof o!="number"||o<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: limit must be a positive number",isError:!0};try{let i=await ii.readFile(r),a=Math.min(8192,i.length);for(let f=0;f<a;f++)if(i[f]===0)return{content:`File appears to be binary: ${r}`,isError:!0};let l=i.toString("utf-8");if(l.length===0)return{content:""};let c=l.split(`
|
|
1207
|
-
`),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),m=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${m} lines)`};let g=String(m).length,y=p.map((f,
|
|
1208
|
-
`);if(p.length<m){let f=d+1,
|
|
1209
|
-
... (showing lines ${f}-${
|
|
1207
|
+
`),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),m=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${m} lines)`};let g=String(m).length,y=p.map((f,w)=>{let k=d+w+1;return`${String(k).padStart(g," ")} ${f}`}).join(`
|
|
1208
|
+
`);if(p.length<m){let f=d+1,w=d+p.length,k=w<m?` \u2014 pass offset=${w+1} to continue`:"";return{content:`${y}
|
|
1209
|
+
... (showing lines ${f}-${w} of ${m}${k})`}}return{content:y}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`File not found: ${r}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error reading file: ${i.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};import{writeFile as ai}from"fs/promises";import{mkdir as li}from"fs/promises";import{dirname as ci}from"path";function di(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var rr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,content:r}=di(t);try{let o=ci(n);return await li(o,{recursive:!0}),await ai(n,r,{signal:e}),{content:`Wrote ${Buffer.byteLength(r,"utf8")} bytes to ${n}`}}catch(o){return o instanceof Error?"code"in o&&o.code==="EACCES"?{content:`Permission denied: ${n}`,isError:!0}:{content:`Error writing file: ${o.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0}}};import{readFile as ui,writeFile as pi}from"fs/promises";function fi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function mi(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}function gi(t,e,n){let r=t.split(`
|
|
1210
1210
|
`),o=0,s=0;for(let c=0;c<r.length;c++){let d=r[c]?.length??0,u=o+d+1;if(o+d>=n+e.length){s=c;break}o=u}let i=Math.max(0,s-2),a=Math.min(r.length,s+3);return`...${r.slice(i,a).join(`
|
|
1211
1211
|
`)}...`}var or=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,old_string:r,new_string:o,replace_all:s}=fi(t);try{let i=await ui(n,"utf-8"),a=mi(i,r);if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1&&!s)return{content:`old_string matches ${a} locations in ${n}. Use replace_all: true or provide more context.`,isError:!0};let l,c;s?(l=i.split(r).join(o),c=i.indexOf(r)):(c=i.indexOf(r),l=i.slice(0,c)+o+i.slice(c+r.length)),await pi(n,l,"utf-8");let d=gi(i,r,c);return{content:`${a===1?`Replaced 1 occurrence in ${n}`:`Replaced ${a} occurrences in ${n}`}
|
|
1212
1212
|
|
|
@@ -1224,9 +1224,10 @@ ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}
|
|
|
1224
1224
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1225
1225
|
- Use absolute paths for file operations.
|
|
1226
1226
|
|
|
1227
|
-
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var ur="anthropic-direct",Pi=8192,Ei="claude-sonnet-4-5-20250929",Ai=null;var Pe=class{name=ur;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...de];e.subagentExecutor&&n.push(Rn),e.skillExecutor&&n.push(_n),this.tools=e.tools??new ie({handlers:ze(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${ur} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=At(r),s=Tt(r,o),i=this.providerFactory??Ai,a=i?i(s):new xi(s),l=Ct(o),c=Ti(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?Se(n.model)??n.model:Ei,u=Ci(n),p=this.tools instanceof ie?[...this.tools.toolDefs]:[...de],m=[...Q(je()),...Q()],g=n.plugins??[],y=[...m,...g],f=this.skillExecutor?Zn(y):"",
|
|
1227
|
+
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var ur="anthropic-direct",Pi=8192,Ei="claude-sonnet-4-5-20250929",Ai=null;var Pe=class{name=ur;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...de];e.subagentExecutor&&n.push(Rn),e.skillExecutor&&n.push(_n),this.tools=e.tools??new ie({handlers:ze(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${ur} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=At(r),s=Tt(r,o),i=this.providerFactory??Ai,a=i?i(s):new xi(s),l=Ct(o),c=Ti(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?Se(n.model)??n.model:Ei,u=Ci(n),p=this.tools instanceof ie?[...this.tools.toolDefs]:[...de],m=[...Q(je()),...Q()],g=n.plugins??[],y=[...m,...g],f=this.skillExecutor?Zn(y):"",w=n.cwd||process.cwd(),k=[dr];k.push(`# Environment
|
|
1228
|
+
- Working directory: ${w}`),f.length>0&&k.push(f),c&&k.push(c);let $=k.join(`
|
|
1228
1229
|
|
|
1229
|
-
`);return new Ge({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem
|
|
1230
|
+
`);return new Ge({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:$,systemPrefix:l})}};function Ti(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function Ci(t){let e=t.maxOutputTokens;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Pi}var pr=new Pe;import{Codex as mr}from"@openai/codex-sdk";import{mkdtempSync as Ii,rmSync as Mi,writeFileSync as Ri}from"node:fs";import{tmpdir as _i}from"node:os";import{join as fr}from"node:path";var Ae="openai-codex",Di=[{value:"gpt-5.4",displayName:"GPT-5.4",description:"Codex default"},{value:"gpt-5.4-mini",displayName:"GPT-5.4 mini",description:"Faster, cheaper Codex variant"}];function Oi(t){let e=[];if(t.continue&&e.push("continue"),t.resumeSessionAt!==void 0&&e.push("resumeSessionAt"),t.forkSession&&e.push("forkSession"),t.persistSession===!1&&e.push("persistSession=false"),t.enableFileCheckpointing&&e.push("enableFileCheckpointing"),t.thinking!==void 0&&e.push("thinking"),t.maxBudgetUsd!==void 0&&e.push("maxBudgetUsd"),t.taskBudget!==void 0&&e.push("taskBudget"),t.plugins&&t.plugins.length>0&&e.push("plugins"),t.agents&&e.push("agents"),t.agent!==void 0&&e.push("agent"),t.onElicitation&&e.push("onElicitation"),t.hooks&&e.push("hooks"),t.canUseTool&&e.push("canUseTool"),t.mcpServers&&e.push("mcpServers"),t.includeHookEvents&&e.push("includeHookEvents"),t.agentProgressSummaries&&e.push("agentProgressSummaries"),t.includePartialMessages&&e.push("includePartialMessages"),e.length>0)throw new ge(Ae,e.join(", "),`${Ae} provider does not support AgentConfig fields: ${e.join(", ")}`)}function gr(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function $i(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function Fi(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string")return e.length>0?e:void 0;if(typeof e=="object"&&e!==null&&"append"in e){let n=e.append;return n&&n.length>0?n:void 0}}}function ji(t){let e=Ii(fr(_i(),"afk-codex-instr-")),n=fr(e,"instructions.md");return Ri(n,t,"utf-8"),{path:n,dispose:()=>{try{Mi(e,{recursive:!0,force:!0})}catch{}}}}function Hi(t){if(t.apiKey)return t.apiKey;let e=process.env.OPENAI_API_KEY??process.env.CODEX_API_KEY;return e&&e.length>0?e:void 0}function*Li(t,e,n,r){if(t.type!=="thread.started"&&t.type!=="turn.started"){if(t.type==="turn.completed"){let o=t.usage;yield{type:"turn.completed",usage:{inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,totalTokens:o.input_tokens+o.output_tokens+o.cached_input_tokens,resultSubtype:"success",isError:!1,raw:{input_tokens:o.input_tokens,output_tokens:o.output_tokens,cached_input_tokens:o.cached_input_tokens}},...e!==void 0?{sessionId:e}:{}};return}if(t.type==="turn.failed"){yield{type:"error",error:new Error(t.error.message)};return}if(t.type==="error"){yield{type:"error",error:new Error(t.message)};return}(t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed")&&(yield*Ui(t.item,t.type==="item.completed",e,n,r))}}function*Ui(t,e,n,r,o){if(t.type==="agent_message"){let s=r.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;r.set(t.id,t.text),i.length>0&&(yield{type:"delta.text",text:i,...n!==void 0?{sessionId:n}:{}})}e&&(yield{type:"assistant.message",text:t.text,...n!==void 0?{sessionId:n}:{}},r.delete(t.id));return}if(t.type==="reasoning"){let s=o.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;o.set(t.id,t.text),i.length>0&&(yield{type:"delta.reasoning",text:i,...n!==void 0?{sessionId:n}:{}})}e&&o.delete(t.id);return}if(t.type==="command_execution"){if(e){let s=t.status==="failed",i=t.exit_code!==void 0?` (exit ${t.exit_code})`:"",a=`$ ${t.command}${i}
|
|
1230
1231
|
`+(t.aggregated_output??"");yield{type:"tool.output",toolUseId:t.id,content:a,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="file_change"){if(e){let s=t.changes.map(i=>`${i.kind} ${i.path}`).join(`
|
|
1231
1232
|
`);yield{type:"tool.output",toolUseId:t.id,content:s,isError:t.status==="failed",...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="mcp_tool_call"){if(e){let s=t.status==="failed",i;t.error?i=t.error.message:t.result?i=JSON.stringify(t.result,null,2):i="",yield{type:"tool.output",toolUseId:t.id,content:i,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="web_search"){e&&(yield{type:"tool.output",toolUseId:t.id,content:`web_search: ${t.query}`,...n!==void 0?{sessionId:n}:{}});return}if(t.type!=="todo_list"&&t.type==="error"){e&&(yield{type:"error",error:new Error(t.message)});return}}var mt=class{startOpts;promptStream;codex;thread;currentModel;currentSandbox;currentApproval;abortController=null;pendingAbortReason=null;closed=!1;initSessionId;dispose;closeResolve=null;closedPromise;constructor(e,n,r){this.startOpts=e,this.promptStream=n,this.initSessionId=r,this.codex=new mr(e.codexOptions),this.thread=e.resumeId?this.codex.resumeThread(e.resumeId,e.threadOptions):this.codex.startThread(e.threadOptions),this.currentModel=e.threadOptions.model,this.currentSandbox=e.threadOptions.sandboxMode??"workspace-write",this.currentApproval=e.threadOptions.approvalPolicy??"never",e.instructionsDispose!==void 0&&(this.dispose=e.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let i=await Promise.race([s.next(),this.closedPromise]);if(i==="__closed__")break;let a=i;if(a.done)break;let l=a.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let d;try{let u=typeof l.content=="string"?l.content:l.content.map(p=>{if(typeof p=="object"&&p&&"type"in p){if(p.type==="text")return p.text;if(p.type==="image")return"[image omitted]"}return""}).join(`
|
|
1232
1233
|
`);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*Li(u,o,n,r)}}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(i){yield{type:"error",error:i instanceof Error?i:new Error(String(i))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){this.currentModel=e;let n={...this.startOpts.threadOptions,...e!==void 0?{model:e}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(e){let{sandboxMode:n,approvalPolicy:r}=gr(e);this.currentSandbox=n,this.currentApproval=r;let o={...this.startOpts.threadOptions,sandboxMode:n,approvalPolicy:r},s=this.thread.id;this.thread=s?this.codex.resumeThread(s,o):this.codex.startThread(o),this.startOpts.threadOptions=o}async supportedCommands(){return[]}async supportedModels(){return Di.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:null}}async mcpServerStatus(){return[]}async accountInfo(){return{}}async rewindFiles(e,n){throw new ge(Ae,"rewindFiles",`${Ae} provider does not support file checkpoint rewind.`)}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),this.dispose?.()}getThread(){return this.thread}},Ni=null;var fe=class{name=Ae;query(e){Oi(e.config);let n=Hi(e.config),r=$i(e.config.effort),{sandboxMode:o,approvalPolicy:s}=gr(e.config.permissionMode),i={...e.config.model!==void 0?{model:e.config.model}:{},sandboxMode:o,approvalPolicy:s,...r!==void 0?{modelReasoningEffort:r}:{},skipGitRepoCheck:!0,workingDirectory:process.cwd()},a=Fi(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:y}=ji(a);l.config={...l.config??{},model_instructions_file:g},c=y}A(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(e.config.model)}, sandbox=${o}, approval=${s})`);let d=Ni,u=d??(g=>new mr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,m=new mt({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(d){let g=u(l);m.codex=g,m.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return m}},qe=new fe;var Bi=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function xe(t){if(!t)return"anthropic-direct";let e=t.trim().toLowerCase();return!e||Bi.has(e)||e.startsWith("claude-")||e.startsWith("claude_")?"anthropic-direct":e.startsWith("gpt-")||e.startsWith("gpt_")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"?"openai-codex":"anthropic-direct"}function Ve(t){return xe(t)==="openai-codex"?qe:pr}async function hr(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function yr(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof U||r instanceof B){A(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}A(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Ke=class{pendingResolve=null;bufferedMessage=null;getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessage=e}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessage!==null){let n=e.bufferedMessage;e.bufferedMessage=null;let r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function Gi(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function zi(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function qi(t){let e=Buffer.byteLength(t,"utf8"),n=zi(e),r=t.split(`
|
|
@@ -1244,9 +1245,9 @@ ${Er.map(e=>`${e.cmd} - ${e.desc}`).join(`
|
|
|
1244
1245
|
Just send me a message to get started!`}function yt(t){return`${{opus:"\u{1F680}",sonnet:"\u26A1",haiku:"\u{1F338}"}[t]||"\u{1F916}"} Switched to Claude ${t.toUpperCase()}`}function Ie(){return"\u{1F504} Conversation history cleared!"}function bt(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${ea(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function vt(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function ea(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}async function wt(t){await t.reply(ht())}async function kt(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Ar(r))}async function St(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(M("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(Ie())}catch(s){r("Clear error:",s),await t.reply(M(s))}}async function Tr(t,e,n){let r=t.chat?.id;if(!r){await t.reply(M("Could not identify chat"));return}try{let o=await e.getSession(r);await t.sendChatAction("typing").catch(()=>{});let s=await o.compact();s.compacted?await t.reply(bt({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(vt(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(M(o))}}async function xt(t,e,n){let r=t.chat?.id;if(!r){await t.reply(M("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let c=e.getModel(r);await t.reply(`Current model: ${c.toUpperCase()}
|
|
1245
1246
|
|
|
1246
1247
|
Usage: /model [opus|sonnet|haiku]`);return}let i=s[0];if(!i){await t.reply(M("Please specify a model: opus, sonnet, or haiku"));return}let a=i.toLowerCase();if(!["opus","sonnet","haiku"].includes(a)){await t.reply(M(`Invalid model: ${i}
|
|
1247
|
-
Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(yt(a))}catch(c){n("Model switch error:",c),await t.reply(M(c))}}function Ye(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function Qe(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var ta=300,na=9e4,ra=6e4;async function Pt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let d=gt(l||"\u2026"),u=Date.now();if(!s){let m=Ce(d);s=await t.reply(m[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&u-i<ta&&l.length<100)return;i=u;let p=Ce(d);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??d,{parse_mode:"HTML"})}catch{}};try{let l="sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let m=await e.sendMessage(n,{stream:!1});yield{type:"message",message:m},yield{type:"done",metadata:m.metadata}})();await a("Thinking\u2026");let c=l[Symbol.asyncIterator](),d=!1,u=null,p=()=>{let m=d?ra:na;return new Promise((g,y)=>{u=setTimeout(()=>{u=null,y(new Error(d?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))},m),c.next().then(f=>{u!=null&&(clearTimeout(u),u=null),g(f)},f=>{u!=null&&(clearTimeout(u),u=null),y(f)})})};for(;;){let m=await p();if(m.done)break;let g=m.value;if(d||(d=!0,console.log("\u{1F4E1} First stream event received:",g.type),r?.("First stream event received:",g.type)),g.type==="chunk"&&g.chunk.type==="content"&&(o+=g.chunk.content,await a(o)),g.type==="message"&&g.message.role==="assistant"&&(o=g.message.content,await a(o)),g.type==="progress"){let{description:y,summary:f,lastToolName:
|
|
1248
|
-
\u25E6 ${y} (${
|
|
1249
|
-
\u25E6 ${y}`;o+=
|
|
1248
|
+
Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(yt(a))}catch(c){n("Model switch error:",c),await t.reply(M(c))}}function Ye(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function Qe(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var ta=300,na=9e4,ra=6e4;async function Pt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let d=gt(l||"\u2026"),u=Date.now();if(!s){let m=Ce(d);s=await t.reply(m[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&u-i<ta&&l.length<100)return;i=u;let p=Ce(d);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??d,{parse_mode:"HTML"})}catch{}};try{let l="sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let m=await e.sendMessage(n,{stream:!1});yield{type:"message",message:m},yield{type:"done",metadata:m.metadata}})();await a("Thinking\u2026");let c=l[Symbol.asyncIterator](),d=!1,u=null,p=()=>{let m=d?ra:na;return new Promise((g,y)=>{u=setTimeout(()=>{u=null,y(new Error(d?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))},m),c.next().then(f=>{u!=null&&(clearTimeout(u),u=null),g(f)},f=>{u!=null&&(clearTimeout(u),u=null),y(f)})})};for(;;){let m=await p();if(m.done)break;let g=m.value;if(d||(d=!0,console.log("\u{1F4E1} First stream event received:",g.type),r?.("First stream event received:",g.type)),g.type==="chunk"&&g.chunk.type==="content"&&(o+=g.chunk.content,await a(o)),g.type==="message"&&g.message.role==="assistant"&&(o=g.message.content,await a(o)),g.type==="progress"){let{description:y,summary:f,lastToolName:w}=g.progress,k=w?`
|
|
1249
|
+
\u25E6 ${y} (${w})`:`
|
|
1250
|
+
\u25E6 ${y}`;o+=k,f&&(o+=`
|
|
1250
1251
|
${f}`),await a(o)}if(g.type==="suggestion"&&(o+=`
|
|
1251
1252
|
|
|
1252
|
-
\u{1F4A1} ${g.suggestion}`,await a(o)),g.type==="done"){o.trim()&&await a(o,!0);break}if(g.type==="error")throw g.error}if(o&&s){let m=Ce(gt(o));if(m.length>1)for(let g=1;g<m.length;g++){let y=m[g];y&&await t.reply(y,{parse_mode:"HTML"})}}}catch(l){throw r?.("Streaming error:",l),l}}async function Cr(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,l)=>setTimeout(()=>l(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let l=a.replace(/^\//,"");i.push({command:l,description:`SDK command: ${l}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}var Je=class{sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;constructor(e,n,r,o){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o}async handle(e){let n=e.chat?.id,r=e.message.text;if(!(!n||!r)&&(console.log(`\u{1F4EC} Message from chat ID: ${n}`),!r.startsWith("/")))try{let o=await this.sessionManager.getSession(n);if(Cr(this.bot,n,o,this.registeredCommandChats,this.log).catch(s=>this.log("Failed to register chat commands:",s)),o.state!=="idle"){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}await this.processOne(n,e,r)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;if((s?.message??"").includes("session is busy")){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}Ye(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Qe(o)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(M(s))}}async processClearDirect(e,n){try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e),await n.reply(Ie())}catch(r){this.log("Clear error:",r),await n.reply(M(r))}}enqueueMessage(e,n,r){let o=this.messageQueues.get(e);o||(o=[],this.messageQueues.set(e,o)),o.push({type:"message",ctx:n,text:r})}enqueueClear(e,n){let r=this.messageQueues.get(e);r||(r=[],this.messageQueues.set(e,r)),r.push({type:"clear",ctx:n})}async processOne(e,n,r){try{let o=await this.sessionManager.getSession(e);await n.sendChatAction("typing").catch(()=>{}),await Pt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;Ye(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Qe(o)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(M(s))}finally{this.drainQueue(e)}}async drainQueue(e){let n=this.messageQueues.get(e);if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):await this.processClearDirect(e,r.ctx)}};function Et(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var Xe=class{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;constructor(e){this.options=e,this.bot=new oa(e.botToken),this.sessionManager=new me(e),this.messageHandler=new Je(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Et(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>wt(e)),this.bot.command("help",e=>kt(e,this.sessionManager)),this.bot.command("clear",async e=>{let n=e.chat?.id;if(!n){await e.reply(M("Could not identify chat"));return}(await this.sessionManager.getSession(n)).state!=="idle"?(this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.")):await St(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>Tr(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>xt(e,this.sessionManager,this.log.bind(this))),this.bot.on("text",e=>this.messageHandler.handle(e)),this.bot.catch((e,n)=>{this.log("Bot error:",e),n.reply(M("An unexpected error occurred. Please try again.")).catch(r=>this.log("Failed to send error message:",r))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}]),this.running=!0,this.log("Bot started successfully");let e=async n=>{this.log(`Received ${n}, shutting down...`),await this.stop(),process.exit(0)};process.once("SIGINT",()=>e("SIGINT")),process.once("SIGTERM",()=>e("SIGTERM"))}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}async handleStart(e){return wt(e)}async handleHelp(e){return kt(e,this.sessionManager)}async handleClear(e){let n=e.chat?.id;if(!n){await e.reply(M("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return St(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return xt(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};export{ne as AgentSession,ae as MessageQueue,fe as OpenAICodexProvider,me as SessionManager,
|
|
1253
|
+
\u{1F4A1} ${g.suggestion}`,await a(o)),g.type==="done"){o.trim()&&await a(o,!0);break}if(g.type==="error")throw g.error}if(o&&s){let m=Ce(gt(o));if(m.length>1)for(let g=1;g<m.length;g++){let y=m[g];y&&await t.reply(y,{parse_mode:"HTML"})}}}catch(l){throw r?.("Streaming error:",l),l}}async function Cr(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,l)=>setTimeout(()=>l(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let l=a.replace(/^\//,"");i.push({command:l,description:`SDK command: ${l}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}var Je=class{sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;constructor(e,n,r,o){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o}async handle(e){let n=e.chat?.id,r=e.message.text;if(!(!n||!r)&&(console.log(`\u{1F4EC} Message from chat ID: ${n}`),!r.startsWith("/")))try{let o=await this.sessionManager.getSession(n);if(Cr(this.bot,n,o,this.registeredCommandChats,this.log).catch(s=>this.log("Failed to register chat commands:",s)),o.state!=="idle"){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}await this.processOne(n,e,r)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;if((s?.message??"").includes("session is busy")){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}Ye(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Qe(o)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(M(s))}}async processClearDirect(e,n){try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e),await n.reply(Ie())}catch(r){this.log("Clear error:",r),await n.reply(M(r))}}enqueueMessage(e,n,r){let o=this.messageQueues.get(e);o||(o=[],this.messageQueues.set(e,o)),o.push({type:"message",ctx:n,text:r})}enqueueClear(e,n){let r=this.messageQueues.get(e);r||(r=[],this.messageQueues.set(e,r)),r.push({type:"clear",ctx:n})}async processOne(e,n,r){try{let o=await this.sessionManager.getSession(e);await n.sendChatAction("typing").catch(()=>{}),await Pt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;Ye(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Qe(o)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(M(s))}finally{this.drainQueue(e)}}async drainQueue(e){let n=this.messageQueues.get(e);if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):await this.processClearDirect(e,r.ctx)}};function Et(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var Xe=class{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;constructor(e){this.options=e,this.bot=new oa(e.botToken),this.sessionManager=new me(e),this.messageHandler=new Je(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Et(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>wt(e)),this.bot.command("help",e=>kt(e,this.sessionManager)),this.bot.command("clear",async e=>{let n=e.chat?.id;if(!n){await e.reply(M("Could not identify chat"));return}(await this.sessionManager.getSession(n)).state!=="idle"?(this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.")):await St(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>Tr(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>xt(e,this.sessionManager,this.log.bind(this))),this.bot.on("text",e=>this.messageHandler.handle(e)),this.bot.catch((e,n)=>{this.log("Bot error:",e),n.reply(M("An unexpected error occurred. Please try again.")).catch(r=>this.log("Failed to send error message:",r))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}]),this.running=!0,this.log("Bot started successfully");let e=async n=>{this.log(`Received ${n}, shutting down...`),await this.stop(),process.exit(0)};process.once("SIGINT",()=>e("SIGINT")),process.once("SIGTERM",()=>e("SIGTERM"))}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}async handleStart(e){return wt(e)}async handleHelp(e){return kt(e,this.sessionManager)}async handleClear(e){let n=e.chat?.id;if(!n){await e.reply(M("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return St(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return xt(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};export{ne as AgentSession,ae as MessageQueue,fe as OpenAICodexProvider,me as SessionManager,x as SubagentManager,Xe as TelegramBot,xr as createCanUseToolHook,qe as openaiCodexProvider,xe as providerForModel,Ve as resolveProvider};
|
package/dist/telegram.mjs
CHANGED
|
@@ -1244,9 +1244,10 @@ ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}
|
|
|
1244
1244
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1245
1245
|
- Use absolute paths for file operations.
|
|
1246
1246
|
|
|
1247
|
-
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var $r="anthropic-direct",oa=8192,sa="claude-sonnet-4-5-20250929",ia=null;var Q=class{name=$r;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...Ge];e.subagentExecutor&&n.push(er),e.skillExecutor&&n.push(tr),this.tools=e.tools??new Se({handlers:Or(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${$r} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=zt(r),s=Vt(r,o),i=this.providerFactory??ia,a=i?i(s):new ra(s),l=qt(o),c=aa(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ae(n.model)??n.model:sa,u=la(n),p=this.tools instanceof Se?[...this.tools.toolDefs]:[...Ge],f=[...q(he()),...q()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?xr(h):"",b=
|
|
1247
|
+
When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var $r="anthropic-direct",oa=8192,sa="claude-sonnet-4-5-20250929",ia=null;var Q=class{name=$r;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...Ge];e.subagentExecutor&&n.push(er),e.skillExecutor&&n.push(tr),this.tools=e.tools??new Se({handlers:Or(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${$r} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=zt(r),s=Vt(r,o),i=this.providerFactory??ia,a=i?i(s):new ra(s),l=qt(o),c=aa(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ae(n.model)??n.model:sa,u=la(n),p=this.tools instanceof Se?[...this.tools.toolDefs]:[...Ge],f=[...q(he()),...q()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?xr(h):"",b=n.cwd||process.cwd(),S=[Fr];S.push(`# Environment
|
|
1248
|
+
- Working directory: ${b}`),m.length>0&&S.push(m),c&&S.push(c);let F=S.join(`
|
|
1248
1249
|
|
|
1249
|
-
`);return new We({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:
|
|
1250
|
+
`);return new We({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:F,systemPrefix:l})}};function aa(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function la(t){let e=t.maxOutputTokens;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):oa}var Lr=new Q;import{Codex as Hr}from"@openai/codex-sdk";import{mkdtempSync as ca,rmSync as da,writeFileSync as ua}from"node:fs";import{tmpdir as pa}from"node:os";import{join as jr}from"node:path";var xe="openai-codex",fa=[{value:"gpt-5.4",displayName:"GPT-5.4",description:"Codex default"},{value:"gpt-5.4-mini",displayName:"GPT-5.4 mini",description:"Faster, cheaper Codex variant"}];function ma(t){let e=[];if(t.continue&&e.push("continue"),t.resumeSessionAt!==void 0&&e.push("resumeSessionAt"),t.forkSession&&e.push("forkSession"),t.persistSession===!1&&e.push("persistSession=false"),t.enableFileCheckpointing&&e.push("enableFileCheckpointing"),t.thinking!==void 0&&e.push("thinking"),t.maxBudgetUsd!==void 0&&e.push("maxBudgetUsd"),t.taskBudget!==void 0&&e.push("taskBudget"),t.plugins&&t.plugins.length>0&&e.push("plugins"),t.agents&&e.push("agents"),t.agent!==void 0&&e.push("agent"),t.onElicitation&&e.push("onElicitation"),t.hooks&&e.push("hooks"),t.canUseTool&&e.push("canUseTool"),t.mcpServers&&e.push("mcpServers"),t.includeHookEvents&&e.push("includeHookEvents"),t.agentProgressSummaries&&e.push("agentProgressSummaries"),t.includePartialMessages&&e.push("includePartialMessages"),e.length>0)throw new ge(xe,e.join(", "),`${xe} provider does not support AgentConfig fields: ${e.join(", ")}`)}function Ur(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function ga(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function ha(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string")return e.length>0?e:void 0;if(typeof e=="object"&&e!==null&&"append"in e){let n=e.append;return n&&n.length>0?n:void 0}}}function ya(t){let e=ca(jr(pa(),"afk-codex-instr-")),n=jr(e,"instructions.md");return ua(n,t,"utf-8"),{path:n,dispose:()=>{try{da(e,{recursive:!0,force:!0})}catch{}}}}function ba(t){if(t.apiKey)return t.apiKey;let e=process.env.OPENAI_API_KEY??process.env.CODEX_API_KEY;return e&&e.length>0?e:void 0}function*va(t,e,n,r){if(t.type!=="thread.started"&&t.type!=="turn.started"){if(t.type==="turn.completed"){let o=t.usage;yield{type:"turn.completed",usage:{inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,totalTokens:o.input_tokens+o.output_tokens+o.cached_input_tokens,resultSubtype:"success",isError:!1,raw:{input_tokens:o.input_tokens,output_tokens:o.output_tokens,cached_input_tokens:o.cached_input_tokens}},...e!==void 0?{sessionId:e}:{}};return}if(t.type==="turn.failed"){yield{type:"error",error:new Error(t.error.message)};return}if(t.type==="error"){yield{type:"error",error:new Error(t.message)};return}(t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed")&&(yield*wa(t.item,t.type==="item.completed",e,n,r))}}function*wa(t,e,n,r,o){if(t.type==="agent_message"){let s=r.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;r.set(t.id,t.text),i.length>0&&(yield{type:"delta.text",text:i,...n!==void 0?{sessionId:n}:{}})}e&&(yield{type:"assistant.message",text:t.text,...n!==void 0?{sessionId:n}:{}},r.delete(t.id));return}if(t.type==="reasoning"){let s=o.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;o.set(t.id,t.text),i.length>0&&(yield{type:"delta.reasoning",text:i,...n!==void 0?{sessionId:n}:{}})}e&&o.delete(t.id);return}if(t.type==="command_execution"){if(e){let s=t.status==="failed",i=t.exit_code!==void 0?` (exit ${t.exit_code})`:"",a=`$ ${t.command}${i}
|
|
1250
1251
|
`+(t.aggregated_output??"");yield{type:"tool.output",toolUseId:t.id,content:a,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="file_change"){if(e){let s=t.changes.map(i=>`${i.kind} ${i.path}`).join(`
|
|
1251
1252
|
`);yield{type:"tool.output",toolUseId:t.id,content:s,isError:t.status==="failed",...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="mcp_tool_call"){if(e){let s=t.status==="failed",i;t.error?i=t.error.message:t.result?i=JSON.stringify(t.result,null,2):i="",yield{type:"tool.output",toolUseId:t.id,content:i,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="web_search"){e&&(yield{type:"tool.output",toolUseId:t.id,content:`web_search: ${t.query}`,...n!==void 0?{sessionId:n}:{}});return}if(t.type!=="todo_list"&&t.type==="error"){e&&(yield{type:"error",error:new Error(t.message)});return}}var Tt=class{startOpts;promptStream;codex;thread;currentModel;currentSandbox;currentApproval;abortController=null;pendingAbortReason=null;closed=!1;initSessionId;dispose;closeResolve=null;closedPromise;constructor(e,n,r){this.startOpts=e,this.promptStream=n,this.initSessionId=r,this.codex=new Hr(e.codexOptions),this.thread=e.resumeId?this.codex.resumeThread(e.resumeId,e.threadOptions):this.codex.startThread(e.threadOptions),this.currentModel=e.threadOptions.model,this.currentSandbox=e.threadOptions.sandboxMode??"workspace-write",this.currentApproval=e.threadOptions.approvalPolicy??"never",e.instructionsDispose!==void 0&&(this.dispose=e.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let i=await Promise.race([s.next(),this.closedPromise]);if(i==="__closed__")break;let a=i;if(a.done)break;let l=a.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let d;try{let u=typeof l.content=="string"?l.content:l.content.map(p=>{if(typeof p=="object"&&p&&"type"in p){if(p.type==="text")return p.text;if(p.type==="image")return"[image omitted]"}return""}).join(`
|
|
1252
1253
|
`);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*va(u,o,n,r)}}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(i){yield{type:"error",error:i instanceof Error?i:new Error(String(i))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){this.currentModel=e;let n={...this.startOpts.threadOptions,...e!==void 0?{model:e}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(e){let{sandboxMode:n,approvalPolicy:r}=Ur(e);this.currentSandbox=n,this.currentApproval=r;let o={...this.startOpts.threadOptions,sandboxMode:n,approvalPolicy:r},s=this.thread.id;this.thread=s?this.codex.resumeThread(s,o):this.codex.startThread(o),this.startOpts.threadOptions=o}async supportedCommands(){return[]}async supportedModels(){return fa.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:null}}async mcpServerStatus(){return[]}async accountInfo(){return{}}async rewindFiles(e,n){throw new ge(xe,"rewindFiles",`${xe} provider does not support file checkpoint rewind.`)}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),this.dispose?.()}getThread(){return this.thread}},ka=null;var Ye=class{name=xe;query(e){ma(e.config);let n=ba(e.config),r=ga(e.config.effort),{sandboxMode:o,approvalPolicy:s}=Ur(e.config.permissionMode),i={...e.config.model!==void 0?{model:e.config.model}:{},sandboxMode:o,approvalPolicy:s,...r!==void 0?{modelReasoningEffort:r}:{},skipGitRepoCheck:!0,workingDirectory:process.cwd()},a=ha(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:h}=ya(a);l.config={...l.config??{},model_instructions_file:g},c=h}A(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(e.config.model)}, sandbox=${o}, approval=${s})`);let d=ka,u=d??(g=>new Hr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new Tt({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(d){let g=u(l);f.codex=g,f.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return f}},Nr=new Ye;var Sa=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function de(t){if(!t)return"anthropic-direct";let e=t.trim().toLowerCase();return!e||Sa.has(e)||e.startsWith("claude-")||e.startsWith("claude_")?"anthropic-direct":e.startsWith("gpt-")||e.startsWith("gpt_")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"?"openai-codex":"anthropic-direct"}function Br(t){return de(t)==="openai-codex"?Nr:Lr}async function Kr(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function Gr(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof U||r instanceof G){A(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}A(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Je=class{pendingResolve=null;bufferedMessage=null;getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessage=e}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessage!==null){let n=e.bufferedMessage;e.bufferedMessage=null;let r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function xa(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function Pa(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function Ea(t){let e=Buffer.byteLength(t,"utf8"),n=Pa(e),r=t.split(`
|