agent-afk 3.82.0 → 3.83.0

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.
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: contract
3
3
  description: "Reference convention for sub-agent I/O schemas. Loaded by orchestrator skills via /contract and into agents via the `skills:` field."
4
+ context: load
4
5
  ---
5
6
 
6
7
  # Contract
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: devils-advocate
3
3
  description: "Adversarially critique a proposal by generating alternatives. Dispatches 3 parallel critics (pragmatist, paranoid, architect lenses) — each invents one alternative approach — then a synthesis step ranks all 4 options and recommends the top choice. Use when a plan, fix, scoping, decomposition, or named recommendation will drive decisions and you want structured alternative-generation before committing. Complements /shadow-verify — that skill re-derives factual claims; this one critiques whether the chosen approach itself is best."
4
+ context: load
4
5
  ---
5
6
 
6
7
  ## Sub-agent contract
@@ -2,6 +2,7 @@
2
2
  name: ground-claim
3
3
  description: "Use when the user asks a meta-capability question about a system/framework/repo ('what does X enable', 'what can this do', 'list the capabilities'). Forces file-read grounding with path:line citations before answering; tags any unverifiable claim as [UNVERIFIED]."
4
4
  argument-hint: "<the meta-capability question>"
5
+ context: load
5
6
  ---
6
7
 
7
8
  ## Trigger
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: ground-state
3
3
  description: "Before starting any non-trivial implementation (multi-file edits, new features, config changes, anything that writes), dispatch a parallel pre-flight reconnaissance wave to triangulate git state, project infrastructure, and prior-session memory. Produces a 5-line ground-truth snapshot that grounds the implementation and catches wrong-branch edits, assumed-no-CI, stale origin, and missed memory context before the first edit."
4
+ context: fork
4
5
  ---
5
6
 
6
7
  ## Sub-agent contract
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: intent-lock
3
3
  description: "Fires before multi-step work when the user's request contains ambiguous referents ('the text', 'her Y'), characterizations of unverified entities ('the meeting is substantive'), or identity assumptions (which contact = the user). Emits a one-sentence interpretation lock for fast async correction; escalates to Asking only when interpretation gates an irreversible action AND multiple plausible reads exist."
4
+ context: load
4
5
  ---
5
6
 
6
7
  ## When to invoke
@@ -7,6 +7,7 @@ failure_modes:
7
7
  - dependency blindness
8
8
  - false completeness
9
9
  - premature execution
10
+ context: fork
10
11
  ---
11
12
 
12
13
  ## Sub-agent contract
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: research
3
3
  description: "Dispatches two sub-agents in parallel to gather external and local context for the current task."
4
+ context: fork
4
5
  ---
5
6
 
6
7
  ## Sub-agent contract
@@ -2,6 +2,7 @@
2
2
  name: review
3
3
  description: "Dispatches parallel dimension agents across a diff, PR (URL or number), commit SHA, branch, staged changes, or patch file — covering security, correctness, api-compat, test-coverage, and perf-observability — synthesizes findings by severity, and emits a merge recommendation. Use when changes are ready for review before merge. Read-only: this skill analyzes and reports only — it never edits files, commits, pushes, comments on a PR, or modifies the PR description."
4
4
  argument-hint: "[diff|pr-url|pr-number|commit-sha|branch|--staged|--head] [--light] [--change-type hotfix|feature|refactor|dep-bump|new-service]"
5
+ context: fork
5
6
  ---
6
7
 
7
8
  ## Read-only — hard constraint
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: shadow-verify
3
3
  description: "Dispatch a parallel adversarial verifier wave after any high-stakes sub-agent investigation (code reviews, audits, findings reports, large refactors). Shadow verifiers independently re-derive 2–3 key claims from scratch and flag disagreements before the user acts. Use when sub-agent output will drive decisions, file changes, commits, or external side-effects."
4
+ context: fork
4
5
  ---
5
6
 
6
7
  ## Sub-agent contract
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: ship
3
3
  description: "Release pipeline for already-done local work. Dispatches /ground-state pre-flight, runs the project test suite, drafts a commit message, pushes, and opens a PR with a structured verification summary. Use when local changes are ready to hand off to review — e.g. 'ship this', 'push and open a PR', 'release this work'. Add --verify to trigger an adversarial verifier wave on the diff before a human reads the PR."
4
+ context: fork
4
5
  ---
5
6
 
6
7
  ## Sub-agent contract
@@ -2,6 +2,7 @@
2
2
  name: simplify
3
3
  description: "Discovers incidental complexity, duplication, and dead code in a codebase and produces a ranked, behavior-preserving reduction plan — optionally applying safe changes. Dispatches four parallel read-only discovery lenses (clone detection, dead code, complexity hotspots, wrong abstraction), synthesizes into a prioritized reduction plan, and gates apply mode behind /refactor and a hard test check."
4
4
  argument-hint: "[target] [--apply] [--all]"
5
+ context: fork
5
6
  ---
6
7
 
7
8
  ## Sub-agent contract
@@ -120,4 +121,4 @@ On full success, chain to `/ship` for commit + PR.
120
121
 
121
122
  - `/refactor` — multi-site mechanical apply
122
123
  - `/ship` — commit + PR after successful apply
123
- - `/diagnose` — when an applied simplification breaks a test
124
+ - `/diagnose` — when an applied simplification breaks a test
@@ -2,6 +2,7 @@
2
2
  name: spec
3
3
  description: "Takes a loose idea and transforms it into a structured, actionable spec ready for implementation. Use when the user passes an idea, feature request, or problem description that needs scoping before building."
4
4
  argument-hint: "<idea or feature request>"
5
+ context: fork
5
6
  ---
6
7
 
7
8
  ## Triage: bugs route to /diagnose
package/dist/cli.mjs CHANGED
@@ -1081,7 +1081,7 @@ ${c}`:c};return Ly(d,t.prompt,a)}buildDispatcher(t,n){let r=Ra(t,n.cwd),o=Es(thi
1081
1081
  `)}finally{h&&await h.close().catch(()=>{})}}async function d(){let h=await e.readMeta(t);if(!h||!(h.status!=="running"))return!1;try{let y=await De.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await De.stat(r)).size}catch{}if(await d())return;let p=null,f=null,g=()=>new Promise(h=>{f=h;let b=setTimeout(()=>{f=null,h()},c);p=()=>{clearTimeout(b),f=null,h()}});try{l=ao.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{f?.(),l?.close()}}};K();var iO=300*1e3,Uy=4096;function xd(e){Re(e).catch(()=>{})}var jy=5e3,aO=10,Ds=class extends Error{constructor(t,n){super(`Background job cap reached (${t}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}},Pa=class extends oO{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??aO,setTimeout(()=>this._sweepOldJobs().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
1082
1082
  `)),5e3).unref()}register(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new Ds(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=t.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(d=>{i=d}),l={jobId:r,subagentId:t.handle.id,label:o,model:t.model,startedAt:s,status:"running",handle:t.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",parentSessionId:t.parentSessionId};this.jobs.set(r,l),Xr(this.traceWriter,{transition:"started",jobId:r,subagentId:t.handle.id,label:o,model:t.model}),this.emit("started",this.snapshot(l));let c=new Ia(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:sO("sha256").update(t.prompt).digest("hex"),model:t.model,startedAt:s,status:"running",...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},schemaVersion:1};return c.writeMeta(u),t.handle.runInBackground(t.prompt,d=>{this.markTerminal(r,d,c,u)},d=>{c.write(d),d.type==="chunk"&&d.chunk.type==="content"&&this.appendTranscript(r,d.chunk.content)}),this.snapshot(l)}get(t){let n=this.jobs.get(t);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(t=>this.snapshot(t))}async join(t){let n=this.jobs.get(t);if(!n)throw new Error(`Background job not found: "${t}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return Xr(this.traceWriter,{transition:"joined",jobId:t,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}async cancelJob(t){let n=this.jobs.get(t);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelAll(){let t=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of t)n.cancelSource="cascade";await Promise.allSettled(t.map(n=>n.handle.cancel())),await Promise.allSettled(t.map(n=>{let r=new Promise(o=>setTimeout(()=>{console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${jy}ms \u2014 continuing teardown`),o()},jy).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(t,n){let r=this.jobs.get(t);if(!r)return;let o=r.transcriptTail+n;o.length<=Uy?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-Uy)}getTranscript(t){return this.jobs.get(t)?.transcriptTail}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}markTerminal(t,n,r,o){let s=this.jobs.get(t);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let l=n.message?.content,c=typeof l=="string"?l:l!==void 0?JSON.stringify(l):"";Xr(this.traceWriter,{transition:"completed",jobId:t,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(c,"utf8")}),xd({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:c.length}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let l=n.error;Xr(this.traceWriter,{transition:"failed",jobId:t,subagentId:s.subagentId,durationMs:i,errorClass:l?.name??"Error",errorMessage:l?.message??"unknown"}),xd({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:l?.message}),this.emit("settled",this.snapshot(s))}else Xr(this.traceWriter,{transition:"cancelled",jobId:t,subagentId:s.subagentId,source:s.cancelSource??"explicit"}),xd({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let l=s.status,c=s.endedAt;r.writeMeta({...o,status:l,...c!==void 0?{endedAt:c}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(t)},iO).unref()}async _sweepOldJobs(){let n=hs(),r;try{r=await Pn.readdir(n)}catch{return}for(let o of r){let s=Vn(o),i=Hy.join(s,"meta.json");try{if(!(await Pn.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
1083
1083
  `);continue}let l=await Pn.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Pn.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
1084
- `)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}};function lO(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function Ls(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||me(t)==="openai-compatible"?n:lO(r)?r:n}z();function Ed(){return T.ANTHROPIC_API_KEY||T.CLAUDE_CODE_OAUTH_TOKEN||Je()}function Rd(){return T.OPENAI_API_KEY||T.CODEX_API_KEY||void 0}function cr(e){let t=me(e);return t==="openai-compatible"||t==="openai-codex"?Rd():Ed()}function uO(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!cO(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function Ma(e){try{return Re(e).catch(()=>{})}catch{return Promise.resolve()}}function lo(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ky(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}var dO=4096,Wy=1024;function pO(e){if(e==null)return;let t=Ky(e);return t!==void 0&&t>dO?{truncated:!0,chars:t}:e}function mO(e){let t={status:e.status,error:lo(e.errorMessage,Wy),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=lo(e.schemaErrorMessage,Wy));let n=pO(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var Bt=class e{constructor(t){this.ctx=t}ctx;getSubagentsLite(){let t=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=uO(t.input)}catch(h){return{content:`Agent tool input validation failed: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??co,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=me(i)==="openai-compatible",l=Ls({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):cr(i),parentApiKey:this.ctx.defaultConfig.apiKey}),c={model:i,apiKey:a?void 0:l,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:a?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},u;if(this.ctx.childProviderFactory&&r<o){s=new ee({parentAbortSignal:t.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),u=ur(t.signal);let h=new e({subagentManager:s,parentSession:u,defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),b=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;c.provider=this.ctx.childProviderFactory({childExecutor:h,...b!==void 0?{childSkillExecutor:b}:{},...c.model!==void 0?{model:c.model}:{}})}let d;try{d=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:c,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?on(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":on(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),u!==void 0&&(u.sessionId=d.id)}catch(h){let b=h instanceof Error?h.message:String(h);return Ma({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:lo(b),depth:r}),{content:`Failed to fork subagent: ${b}`,isError:!0}}if(n.mode==="background"){let h=this.ctx.backgroundRegistry;if(!h)return await d.teardown().catch(w=>Y("subagent-executor: handle teardown failed: "+(w instanceof Error?w.message:String(w)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let b;try{b=h.register({handle:d,prompt:n.prompt,model:c.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(w){if(w instanceof Ds)return await d.teardown().catch(S=>Y("subagent-executor: handle teardown failed after cap error: "+(S instanceof Error?S.message:String(S)))),{content:w.message,isError:!0};throw w}let y={status:"running",jobId:b.jobId,subagentId:b.subagentId,label:b.label,message:`Background subagent started (jobId=${b.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${b.jobId} or ask the user to join.`};return{content:JSON.stringify(y)}}let p=()=>{d.cancel()};t.signal.addEventListener("abort",p,{once:!0});let f=Date.now(),g=this.ctx.parentSession.sessionId;try{let h=await d.runToResult(n.prompt);if(h.status==="succeeded"&&h.message){let S=h.message.content,E=typeof S=="string"?S:JSON.stringify(S),k=h.trace;return Ma({event:"subagent.completed",subagent_id:d.id,parent_session_id:g,status:h.status,duration_ms:Date.now()-f,content_chars:E.length,depth:r,tool_call_count:k?.toolCalls.length,thinking_present:k?.thinkingPresent,tool_names:k?.toolCalls.length?JSON.stringify([...new Set(k.toolCalls.map(R=>R.name))]):void 0}),{content:E}}let b=h.error?.message??"Subagent failed with no output",y=h.trace;Ma({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:h.status,duration_ms:Date.now()-f,error_message:lo(b),schema_error:h.schemaError?lo(h.schemaError.message):void 0,partial_output_chars:Ky(h.partialOutput),depth:r,tool_call_count:y?.toolCalls.length,thinking_present:y?.thinkingPresent,tool_names:y?.toolCalls.length?JSON.stringify([...new Set(y.toolCalls.map(S=>S.name))]):void 0});let w=mO({status:h.status,errorMessage:b,schemaErrorMessage:h.schemaError?.message,partialOutput:h.partialOutput,subagentId:d.id});return{content:JSON.stringify(w),isError:!0}}catch(h){let b=h instanceof Error?h.message:String(h);throw Ma({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:"failed",duration_ms:Date.now()-f,error_message:lo(b),depth:r}),h}finally{t.signal.removeEventListener("abort",p),await s?.teardownAll(),await d.teardown()}}};var Gy=new Set;function zy(e){Gy.add(e)}function qy(e){return Gy.has(e)}var Ad=new Set,Cd=new Set;function Jy(e){Ad.add(e)}function Yy(e){Ad.delete(e)}function Vy(e){Cd.add(e)}function Xy(e){Cd.delete(e)}function Zy(e){for(let t of Ad)t(e)}function Qy(e){for(let t of Cd)t(e)}var fO=240;function gO(e,t=fO){return e.length<=t?e:e.slice(0,t)+"\u2026"}function hO(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function yO(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Ut=class{constructor(t){this.ctx=t}ctx;pluginBodies=null;async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??co;if(n>=r){let l=hO(t.input);return Re({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=yO(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Oe(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="load"){let l=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,l,o.arguments,t)}return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t)}let a=an(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return this.executeForkedRegistrySkill(t,n,r);if(t.context==="load")return this.executeLoadedRegistrySkill(t,n,r);let o=qy(t.name);o&&Qy(t.name);let s=this.ctx.depth??0;Re({event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(u){a=u}finally{let u=Date.now()-i;o&&Zy({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Re({event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:gO(d)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}buildForkedChildConfig(t,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??co,s={...t};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new ee({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),a=new Bt({subagentManager:i,parentSession:ur(n),defaultConfig:{model:s.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{}}),l=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:a,...l!==void 0?{childSkillExecutor:l}:{},...s.model!==void 0?{model:s.model}:{}}),{childConfig:s,childManager:i}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=Ce(t.name)["system.md"],!o)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(d){return{content:`Failed to load skill prompts: ${d instanceof Error?d.message:String(d)}`,isError:!0}}let s=t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",i=Ls({childModel:s,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(s):cr(s),parentApiKey:this.ctx.apiKey}),a=new ee({parentAbortSignal:r.signal,apiKey:i,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:l,childManager:c}=this.buildForkedChildConfig({model:s,systemPrompt:o,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),u;try{u=await a.forkSubagent({parent:this.ctx.parentSession,config:l,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let d=n&&n.length>0?n:`Run the ${t.name} skill now, following the instructions in your system prompt.`,p=await u.runToResult(d);return p.status==="succeeded"&&p.message?{content:p.message.content}:p.status==="cancelled"&&typeof p.partialOutput=="string"&&p.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1084
+ `)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}};function lO(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function Ls(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||me(t)==="openai-compatible"?n:lO(r)?r:n}z();function Ed(){return T.ANTHROPIC_API_KEY||T.CLAUDE_CODE_OAUTH_TOKEN||Je()}function Rd(){return T.OPENAI_API_KEY||T.CODEX_API_KEY||void 0}function cr(e){let t=me(e);return t==="openai-compatible"||t==="openai-codex"?Rd():Ed()}function uO(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!cO(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function Ma(e){try{return Re(e).catch(()=>{})}catch{return Promise.resolve()}}function lo(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ky(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}var dO=4096,Wy=1024;function pO(e){if(e==null)return;let t=Ky(e);return t!==void 0&&t>dO?{truncated:!0,chars:t}:e}function mO(e){let t={status:e.status,error:lo(e.errorMessage,Wy),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=lo(e.schemaErrorMessage,Wy));let n=pO(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var Bt=class e{constructor(t){this.ctx=t}ctx;getSubagentsLite(){let t=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=uO(t.input)}catch(h){return{content:`Agent tool input validation failed: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??co,s,i=n.model??this.ctx.defaultSubagentModel??"sonnet",a=me(i)==="openai-compatible",l=Ls({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):cr(i),parentApiKey:this.ctx.defaultConfig.apiKey}),c={model:i,apiKey:a?void 0:l,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:a?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},u;if(this.ctx.childProviderFactory&&r<o){s=new ee({parentAbortSignal:t.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),u=ur(t.signal);let h=new e({subagentManager:s,parentSession:u,defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),b=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;c.provider=this.ctx.childProviderFactory({childExecutor:h,...b!==void 0?{childSkillExecutor:b}:{},...c.model!==void 0?{model:c.model}:{}})}let d;try{d=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:c,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?on(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":on(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),u!==void 0&&(u.sessionId=d.id)}catch(h){let b=h instanceof Error?h.message:String(h);return Ma({event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:lo(b),depth:r}),{content:`Failed to fork subagent: ${b}`,isError:!0}}if(n.mode==="background"){let h=this.ctx.backgroundRegistry;if(!h)return await d.teardown().catch(w=>Y("subagent-executor: handle teardown failed: "+(w instanceof Error?w.message:String(w)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let b;try{b=h.register({handle:d,prompt:n.prompt,model:c.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(w){if(w instanceof Ds)return await d.teardown().catch(S=>Y("subagent-executor: handle teardown failed after cap error: "+(S instanceof Error?S.message:String(S)))),{content:w.message,isError:!0};throw w}let y={status:"running",jobId:b.jobId,subagentId:b.subagentId,label:b.label,message:`Background subagent started (jobId=${b.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${b.jobId} or ask the user to join.`};return{content:JSON.stringify(y)}}let p=()=>{d.cancel()};t.signal.addEventListener("abort",p,{once:!0});let f=Date.now(),g=this.ctx.parentSession.sessionId;try{let h=await d.runToResult(n.prompt);if(h.status==="succeeded"&&h.message){let S=h.message.content,E=typeof S=="string"?S:JSON.stringify(S),k=h.trace;return Ma({event:"subagent.completed",subagent_id:d.id,parent_session_id:g,status:h.status,duration_ms:Date.now()-f,content_chars:E.length,depth:r,tool_call_count:k?.toolCalls.length,thinking_present:k?.thinkingPresent,tool_names:k?.toolCalls.length?JSON.stringify([...new Set(k.toolCalls.map(R=>R.name))]):void 0}),{content:E}}let b=h.error?.message??"Subagent failed with no output",y=h.trace;Ma({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:h.status,duration_ms:Date.now()-f,error_message:lo(b),schema_error:h.schemaError?lo(h.schemaError.message):void 0,partial_output_chars:Ky(h.partialOutput),depth:r,tool_call_count:y?.toolCalls.length,thinking_present:y?.thinkingPresent,tool_names:y?.toolCalls.length?JSON.stringify([...new Set(y.toolCalls.map(S=>S.name))]):void 0});let w=mO({status:h.status,errorMessage:b,schemaErrorMessage:h.schemaError?.message,partialOutput:h.partialOutput,subagentId:d.id});return{content:JSON.stringify(w),isError:!0}}catch(h){let b=h instanceof Error?h.message:String(h);throw Ma({event:"subagent.failed",subagent_id:d.id,id_prefix:n.id_prefix,parent_session_id:g,status:"failed",duration_ms:Date.now()-f,error_message:lo(b),depth:r}),h}finally{t.signal.removeEventListener("abort",p),await s?.teardownAll(),await d.teardown()}}};var Gy=new Set;function zy(e){Gy.add(e)}function qy(e){return Gy.has(e)}var Ad=new Set,Cd=new Set;function Jy(e){Ad.add(e)}function Yy(e){Ad.delete(e)}function Vy(e){Cd.add(e)}function Xy(e){Cd.delete(e)}function Zy(e){for(let t of Ad)t(e)}function Qy(e){for(let t of Cd)t(e)}var fO=240;function gO(e,t=fO){return e.length<=t?e:e.slice(0,t)+"\u2026"}function hO(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function yO(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Ut=class{constructor(t){this.ctx=t}ctx;pluginBodies=null;async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??co;if(n>=r){let l=hO(t.input);return Re({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=yO(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Oe(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork")return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t);let l=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,l,o.arguments,t)}let a=an(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return this.executeForkedRegistrySkill(t,n,r);if(t.context==="load")return this.executeLoadedRegistrySkill(t,n,r);let o=qy(t.name);o&&Qy(t.name);let s=this.ctx.depth??0;Re({event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(u){a=u}finally{let u=Date.now()-i;o&&Zy({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Re({event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:gO(d)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}buildForkedChildConfig(t,n){let r=this.ctx.depth??0,o=this.ctx.maxDepth??co,s={...t};if(!this.ctx.childProviderFactory||r>=o)return{childConfig:s,childManager:void 0};let i=new ee({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),a=new Bt({subagentManager:i,parentSession:ur(n),defaultConfig:{model:s.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{}}),l=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,n):void 0;return s.provider=this.ctx.childProviderFactory({childExecutor:a,...l!==void 0?{childSkillExecutor:l}:{},...s.model!==void 0?{model:s.model}:{}}),{childConfig:s,childManager:i}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=Ce(t.name)["system.md"],!o)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(d){return{content:`Failed to load skill prompts: ${d instanceof Error?d.message:String(d)}`,isError:!0}}let s=t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",i=Ls({childModel:s,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(s):cr(s),parentApiKey:this.ctx.apiKey}),a=new ee({parentAbortSignal:r.signal,apiKey:i,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:l,childManager:c}=this.buildForkedChildConfig({model:s,systemPrompt:o,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal),u;try{u=await a.forkSubagent({parent:this.ctx.parentSession,config:l,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let d=n&&n.length>0?n:`Run the ${t.name} skill now, following the instructions in your system prompt.`,p=await u.runToResult(d);return p.status==="succeeded"&&p.message?{content:p.message.content}:p.status==="cancelled"&&typeof p.partialOutput=="string"&&p.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1085
1085
 
1086
1086
  ${p.partialOutput}`}:{content:p.error?.message??"Forked skill failed with no output",isError:!0}}catch(d){return{content:`Forked skill execution error: ${d instanceof Error?d.message:String(d)}`,isError:!0}}finally{u&&await u.teardown().catch(Y),await c?.teardownAll(),await a.teardownAll()}}formatLoadedSkillResult(t,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${t}" loaded into your current context \u2014 act on it now]
1087
1087
  The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
@@ -1089,7 +1089,7 @@ Arguments: ${o}`}
1089
1089
 
1090
1090
  ----- skill: ${t} -----
1091
1091
 
1092
- ${n}`}}emitLoadTelemetry(t,n,r,o){let s=this.ctx.depth??0,i={requested_name:t,parent_session_id:this.ctx.parentSession.sessionId,depth:s,mode:"load",...o!==void 0?{model:o}:{}};Re({event:"skill.dispatched",...i}).catch(()=>{}),Re({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...i}).catch(()=>{})}executeLoadedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;try{let l=Ce(t.name)["system.md"];if(!l)return{content:`Skill "${t.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=l}catch(a){return{content:`Failed to load skill prompts: ${a instanceof Error?a.message:String(a)}`,isError:!0}}let i=this.substituteSkillArgs(s,n);return this.emitLoadTelemetry(t.name,i.length,Date.now()-o,t.model),this.formatLoadedSkillResult(t.name,i,n)}executeLoadedPluginSkill(t,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=Date.now(),i=this.substituteSkillArgs(n,r);return this.emitLoadTelemetry(t,i.length,Date.now()-s,void 0),this.formatLoadedSkillResult(t,i,r)}substituteSkillArgs(t,n){let r=n??"";return t.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(t,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=Ls({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):cr(i),parentApiKey:this.ctx.apiKey}),l=new ee({parentAbortSignal:s.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:c,childManager:u}=this.buildForkedChildConfig({model:i,systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},s.signal),d;try{d=await l.forkSubagent({parent:this.ctx.parentSession,config:c,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let p=o&&o.length>0?o:`Run the ${t} skill now, following the instructions in your system prompt.`,f=await d.runToResult(p);return f.status==="succeeded"&&f.message?{content:f.message.content}:f.status==="cancelled"&&typeof f.partialOutput=="string"&&f.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1092
+ ${n}`}}emitLoadTelemetry(t,n,r,o){let s=this.ctx.depth??0,i={requested_name:t,parent_session_id:this.ctx.parentSession.sessionId,depth:s,mode:"load",...o!==void 0?{model:o}:{}};Re({event:"skill.dispatched",...i}).catch(()=>{}),Re({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...i}).catch(()=>{})}executeLoadedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;if(t.loadBody!==void 0)s=t.loadBody;else try{let l=Ce(t.name)["system.md"];if(!l)return{content:`Skill "${t.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=l}catch(a){return{content:`Failed to load skill prompts: ${a instanceof Error?a.message:String(a)}`,isError:!0}}let i=this.substituteSkillArgs(s,n);return this.emitLoadTelemetry(t.name,i.length,Date.now()-o,t.model),this.formatLoadedSkillResult(t.name,i,n)}executeLoadedPluginSkill(t,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=Date.now(),i=this.substituteSkillArgs(n,r);return this.emitLoadTelemetry(t,i.length,Date.now()-s,void 0),this.formatLoadedSkillResult(t,i,r)}substituteSkillArgs(t,n){let r=n??"";return t.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(t,n,r,o,s){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let i=this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=Ls({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):cr(i),parentApiKey:this.ctx.apiKey}),l=new ee({parentAbortSignal:s.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ft(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:c,childManager:u}=this.buildForkedChildConfig({model:i,systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},s.signal),d;try{d=await l.forkSubagent({parent:this.ctx.parentSession,config:c,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let p=o&&o.length>0?o:`Run the ${t} skill now, following the instructions in your system prompt.`,f=await d.runToResult(p);return f.status==="succeeded"&&f.message?{content:f.message.content}:f.status==="cancelled"&&typeof f.partialOutput=="string"&&f.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1093
1093
 
1094
1094
  ${f.partialOutput}`}:{content:f.error?.message??"Plugin skill failed with no output",isError:!0}}catch(p){return{content:`Plugin skill execution error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}finally{d&&await d.teardown().catch(Y),await u?.teardownAll(),await l.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=Oa(this.ctx.pluginConfigs)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}};var co=3;function ur(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}var bO=[...$t,...st,"memory_search","agent","skill"];function uo(e={}){return({childExecutor:t,childSkillExecutor:n,model:r})=>{let o={permissions:{allowedTools:bO},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{}};return me(typeof r=="string"?r:void 0)==="openai-compatible"?new Tt({...o,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new Le({...o,readOnlyMemory:!0})}}function po(e,t,n,r,o,s,i,a){let l=(c,u,d)=>new Ut({parentSession:ur(d),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:c,maxDepth:u,childProviderFactory:n,childSkillExecutorFactory:l,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{}});return l}function eb(e,t){let n={allowedTools:[...Ny]};return me(typeof t=="string"?t:void 0)==="openai-compatible"?new Tt({permissions:n}):new Le({permissions:n})}function tb(e){let t=wO(e);return t!==void 0?t:SO(e)}function wO(e){let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=t.exec(e))!==null;)n=r[1];if(n)return nb(n.trim())}function SO(e){for(let t=e.length-1;t>=0;t--){if(e[t]!=="}")continue;let n=kO(e,t);if(n===-1)continue;let r=e.slice(n,t+1),o=nb(r);if(o!==void 0)return o}}function kO(e,t){let n=0,r=!1,o=!1;for(let s=t;s>=0;s--){let i=e[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function nb(e){try{return JSON.parse(e)}catch{return}}function _d(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function rb(e,t,n,r,o){if(!r)return{id:e,status:t,message:n,trace:o};let s=tb(n.content),i=r.safeParse(s);return i.success?{id:e,status:t,message:n,output:i.data,trace:o}:{id:e,status:"failed",message:n,error:new Error(`structured output did not match schema: ${i.error.message}`,{cause:i.error}),schemaError:i.error,trace:o}}function ob(e,t,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:e,status:t,error:o,trace:r}}function He(e){return`${e.status}${e.error?`: ${e.error.message}`:""}`}function sb(e,t){let n=e;return t.partialOutput!==void 0&&t.partialOutput!==null&&(n.partialOutput=t.partialOutput),t.subagentId!==void 0&&(n.subagentId=t.subagentId),n}var $a=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,f,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=_d();lastStreamedContent="";get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=la(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",Zn(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(Zn(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Zn(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=_d();let s=n??this.progressSink??ft(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(t)){if(s&&s(a,i),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(t,n){try{let r=await this.run(t,n);return rb(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=ob(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??ft();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{Y("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Zn(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async teardown(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Kg(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)Y(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){Y(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var vO=async(e,t)=>({action:"decline"}),ee=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentCwd=t.cwd,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new ia(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry;o&&await Wg(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!0?{onElicitation:vO}:{},...t.phaseRole==="read-only"?{provider:eb("read-only",t.config.model)}:{}},a;try{a=new Ye(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??ft(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,f=new $a(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??aa,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return Zn(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await Re({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),f}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}};async function Da(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}import{fileURLToPath as TO}from"node:url";import{dirname as xO}from"node:path";var EO=TO(import.meta.url),v9=xO(EO),yt={name:"research-agent",systemPrompt:`---
1095
1095
  name: research-agent
@@ -1505,9 +1505,9 @@ Create a ship-ready summary with next steps.`,c=await a.runToResult(l);if(c.stat
1505
1505
  `,4);if(t===-1)return{frontmatter:null,frontmatterFlags:null,body:e};let n=e.slice(4,t),r=e.slice(t+5),o={},s=null,i=n.split(`
1506
1506
  `);for(let a=0;a<i.length;a++){let l=i[a];if(!l||!l.trim()||l.trimStart().startsWith("#"))continue;if(l.startsWith("flags:")){let u=l.slice(6).trim();if(u.startsWith("[")){let d=u.match(/\[(.*?)\]/);if(d?.[1]){let p=d[1].split(",").map(f=>f.trim()).filter(f=>f.length>0);p.length>0&&(s=p.map(lw).sort())}continue}if(u===""||u==="null"){let d=[];for(let p=a+1;p<i.length;p++){let f=i[p];if(!f||!f.match(/^\s+-\s/))break;let g=f.match(/^\s+-\s+(.+)/);g?.[1]&&d.push(g[1].trim())}d.length>0&&(s=d.map(lw).sort());continue}}let c=l.match(/^([a-zA-Z][a-zA-Z0-9_-]*):\s*(.*)$/);if(c&&c[1]!==void 0&&c[2]!==void 0){let u=c[2].trim().replace(/^['"]|['"]$/g,"");u.length>0&&(o[c[1]]=u)}}return{frontmatter:o,frontmatterFlags:s,body:r}}function cw(e){let t=Hs(e);return t.frontmatterFlags&&t.frontmatterFlags.length>0?t.frontmatterFlags:qd(t.body)}function dD(e,t){return e.length===0||e.length>64?{valid:!1,reason:`name must be 1\u201364 characters, got ${e.length}`}:/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e)?e!==t?{valid:!1,reason:`name field "${e}" does not match parent directory name "${t}"`}:{valid:!0}:{valid:!1,reason:`name "${e}" does not match spec pattern ^[a-z0-9]+(-[a-z0-9]+)*$ (only lowercase a-z0-9 and hyphens, no leading/trailing/consecutive hyphens)`}}var dw=1024;function pD(e,t){let n=Hs(e);if(!n.frontmatter)return null;let r=n.frontmatter.name,o=n.frontmatter.description,s=n.body.trim();if(!r||!o||s.length===0)return null;let i=dD(r,t);if(!i.valid)return process.stderr.write(`[afk] skipping skill ${t}: ${i.reason}
1507
1507
  `),null;if(o.length>dw)return process.stderr.write(`[afk] skipping skill ${t}: description exceeds ${dw} characters (got ${o.length})
1508
- `),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,l=cw(e),c={name:r,description:o,body:s,dir:""};return a&&a.length>0&&(c.argumentHint=a),l.length>0&&(c.flags=l),c}function mD(e){return async(t,n,r)=>{let o=typeof t=="string"&&t.length>0?t:`Run the ${e.name} skill now, following the instructions in your system prompt.`,s=new ee({parentAbortSignal:n?.abortSignal}),i=r?.callId;return await(await s.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:"sonnet",systemPrompt:e.body,env:{SKILL_ROOT:e.dir},isSkillDispatch:!0},idPrefix:`user-skill-${e.name}`,...i?{parentId:i}:{}})).runToResult(o)}}function fD(e,t){try{return Oe(e).origin===t?e:`${t}:${e}`}catch{return e}}function dr(e,t){let n;try{n=cD(e,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${e}: ${s.message}
1508
+ `),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,l=cw(e),c={name:r,description:o,body:s,dir:""};a&&a.length>0&&(c.argumentHint=a),l.length>0&&(c.flags=l);let u=n.frontmatter.context;return(u==="inline"||u==="fork"||u==="load")&&(c.context=u),c}function mD(e){return async(t,n,r)=>{let o=typeof t=="string"&&t.length>0?t:`Run the ${e.name} skill now, following the instructions in your system prompt.`,s=new ee({parentAbortSignal:n?.abortSignal}),i=r?.callId;return await(await s.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:"sonnet",systemPrompt:e.body,env:{SKILL_ROOT:e.dir},isSkillDispatch:!0},idPrefix:`user-skill-${e.name}`,...i?{parentId:i}:{}})).runToResult(o)}}function fD(e,t){try{return Oe(e).origin===t?e:`${t}:${e}`}catch{return e}}function dr(e,t){let n;try{n=cD(e,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${e}: ${s.message}
1509
1509
  `),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=uD(uw(e,o.name,"SKILL.md"),"utf-8")}catch(c){let u=c;u.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${u.message}
1510
- `);continue}let i=pD(s,o.name);if(!i)continue;i.dir=uw(e,o.name);let l={name:fD(i.name,t),description:i.description,handler:mD(i),origin:t};i.argumentHint&&(l.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(l.flags=i.flags),mt(l),r++}return r}function Jd(){return dr(Ui(),"user")}import{existsSync as gD,readdirSync as hD,readFileSync as yD,statSync as bD}from"fs";import{join as wD}from"path";function Yd(e){let t=[];function n(r,o=0){if(o>10||!gD(r))return;let s;try{s=hD(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=wD(r,i),l;try{l=bD(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=SD(a);c.name&&t.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(e),t}function SD(e){try{let t=yD(e,"utf-8");if(!t.startsWith(`---
1510
+ `);continue}let i=pD(s,o.name);if(!i)continue;i.dir=uw(e,o.name);let l={name:fD(i.name,t),description:i.description,handler:mD(i),origin:t};i.argumentHint&&(l.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(l.flags=i.flags),i.context!=="fork"&&(l.context="load",l.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),mt(l),r++}return r}function Jd(){return dr(Ui(),"user")}import{existsSync as gD,readdirSync as hD,readFileSync as yD,statSync as bD}from"fs";import{join as wD}from"path";function Yd(e){let t=[];function n(r,o=0){if(o>10||!gD(r))return;let s;try{s=hD(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=wD(r,i),l;try{l=bD(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=SD(a);c.name&&t.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(e),t}function SD(e){try{let t=yD(e,"utf-8");if(!t.startsWith(`---
1511
1511
  `))return{};let n=t.slice(4),r=n.indexOf(`
1512
1512
  ---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
1513
1513
  `);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let u=l.slice(0,c).trim(),d=l.slice(c+1).trim();if(u==="name")i.name=d.replace(/^["']|["']$/g,"");else if(u==="description")i.description=d.replace(/^["']|["']$/g,"");else if(u==="argumentHint")i.argumentHint=d.replace(/^["']|["']$/g,"");else if(u==="audience"){let p=d.replace(/^["']|["']$/g,"");(p==="public"||p==="internal")&&(i.audience=p)}else u==="context"&&(i.context=d.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}K();z();function pw(e){let t=an(e);if(t.length===0)return"";let n=[];for(let r of t){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):","","Each skill either dispatches one or more context-isolated subagents (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context (`load` mode). Calling `skill` is the entry point for both; the executor picks the mode per skill. Prefer a skill over inline investigation when the task shape matches.","",...n].join(`
@@ -1877,7 +1877,7 @@ ${E}`})}return{fileBlocks:a,warnings:l}}async function aE(e,t,n,r,o="summary",s,
1877
1877
  `))!==-1;){let u=n.slice(0,c);n=n.slice(c+1),this.opts.writeLine(u)}},s={command:t,mode:"foreground",onChunk:c=>{r||(n+=c.toString("utf8"),o())}},i=this.opts.getCwd();i!==void 0&&(s.cwd=i);let{job:a,handle:l}=this.registry.start(s);this.activeFgJobId=a.id;try{let c=await l.promise;r=!0,n.length>0&&(this.opts.writeLine(n),n=""),this.opts.writeLine(KW(a,c)),this.queueInjection({command:t,mode:"foreground",result:c})}finally{this.activeFgJobId=null}}startBackground(t){let n={command:t,mode:"background"},r=this.opts.getCwd();r!==void 0&&(n.cwd=r);let{job:o}=this.registry.start(n);this.opts.writeLine(m.dim(` [${o.id}] background: `)+t)}queueInjection(t){this.pendingInjections.push(t),this.pendingInjections.length>e.MAX_PENDING_INJECTIONS&&this.pendingInjections.shift()}};function zW(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function qW(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}function Lc(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function gE(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async S=>{Ue()&&(o=gl(S)),await lc(e.session.current),Ue()&&(s=sx())}).catch(()=>{});let i=await Yx(),a=new Oc({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d,p,f,g,h=!1,b=!1,y=gv({onError:S=>Y("[afk suggest] Tier-2 completion failed:",S)}),w=zW(T.AFK_SUGGEST_GHOST,e.suggestGhostConfig);try{await a.armCompositor({promptFn:()=>Lc(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let C=e.slashCtx;C.stats.planMode&&C.stats.pendingPlanExit?(C.stats.pendingPlanExit=!1,Et(C,!1,{closureSummarySkipped:!0}).catch(()=>{})):Et(C).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{},...w?{suggest:{engine:y,getContext:()=>({model:e.stats.model,apiKey:e.suggestApiKey,baseUrl:e.suggestBaseUrl,cwd:e.stats.cwd??process.cwd(),getHistory:()=>{let C=a.history;return C.getEntries?[...C.getEntries()]:[]},getDropdownTopCandidate:C=>{let D=a.autocompleteState.candidates[0];return D&&D.value.startsWith(C)&&D.value.length>C.length?D.value:null},getTranscriptTail:()=>"",getRecentCommands:()=>[],llmEnabled:()=>/^(1|true|yes|on)$/i.test(T.AFK_SUGGEST_ENABLED??"")})}}:{}});let S=a.getCompositor();Ft.install(dl({readLine:C=>a.readLine({promptFn:()=>C}).then(L=>L.text),writer:{line:(C="")=>{let L=a.getCompositor();L?L.commitAbove(C):process.stdout.write(C+`
1878
1878
  `)}},pendingCount:()=>Ft.pendingCount(),...S?{pickFromList:C=>eE(S,C),readTextOverlay:C=>tE(S,C)}:{}})),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor();let E=a.getCompositor();if(E){let C=L=>E.commitAbove(L);e.completionWriter.fn=C,e.completionWriter.idleFn=C}e.slashCtx.setSoftStopHandler=C=>a.setSoftStopHandler(C),e.inputSurfaceRef&&(e.inputSurfaceRef.current=a),c=lE(),g=cE(),e.clearVerdictLedger=()=>g?.reset(),u=new vl,Ik(u),Bk(u),Hk(u),Uk(e.backgroundRegistry);let k=0,R=0,_=1,A=()=>e.statusLine.setExtraRows(_+k+R);g.setRowCountChangeHandler(C=>{R=C,A(),d?.redraw(),p?.redraw()}),d=new $c(u,e.backgroundRegistry,{getAdjacentRows:()=>R}),d.setRowCountChangeHandler(C=>{k=C,A()}),p=new Gl({getExtraRows:()=>e.statusLine.getExtraRows()}),p.setRowCountChangeHandler(C=>{A()}),e.statusLine.setAfterScrollRestore(()=>{g?.repaint(),d?.redraw(),p?.redraw()}),d.start(),p.start(),g.start({stream:process.stdout});let P=50,I=[];for(u.on("complete",C=>{I.length>=P&&I.shift(),I.push(C)}),f=new Dc({writeLine:C=>e.replRenderer.writeLine(C),getCwd:()=>e.stats.cwd}),Fk(f),n.tryAbortShellForeground=()=>f.abortActiveForeground();;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let x of s)e.replRenderer.writeLine(x);e.replRenderer.writeLine(""),s=[]}for(;I.length>0;){let x=I.shift(),O=x.status==="succeeded"?"\u2713":"\u2717",B=[];if(x.resultText){let H=x.resultText.trim().split(`
1879
1879
  `)[0]?.slice(0,80)??"";H&&B.push(H)}x.error&&B.push(x.error.message);let J=[x.stats.toolUses>0?`${x.stats.toolUses} tools`:"",x.stats.tokens>0?`${Math.round(x.stats.tokens/1e3)}k tok`:"",x.stats.durationMs>0?`${Math.round(x.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");J&&B.push(J),e.replRenderer.writeLine(xn({kind:x.status==="succeeded"?"checkpoint":"diagnosis",title:`${O} ${x.id} ${x.label}`,body:B})),e.replRenderer.writeLine("")}let C=f.drainNotifications();for(let{job:x,result:O}of C){let B=O.errorReason===void 0?"\u2713":"\u2717",J=O.errorReason==="abort"?"killed":O.errorReason==="timeout"?"timed out":O.errorReason==="signal-killed"?"killed by signal":`exit ${O.exitCode??0}`,H=Math.max(0,Math.round(O.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${B} [${x.id}] ${J} \xB7 ${H}s \xB7 `)+x.command)}let L=c.renderIfChanged(e.stats.sessionId);if(L.length>0){for(let x of L)e.replRenderer.writeLine(x);e.replRenderer.writeLine("")}let D,j;if(l!==void 0){let x=l;l=void 0;let O=Lc(e.stats.model,e.stats.planMode),B=br({buffer:x.text,promptText:O,isTTY:!!process.stdout.isTTY,attachmentSummary:Bo([...x.attachments])});e.replRenderer.writeLine(B),D=x.text.trim(),j=x.attachments}else{let x=await a.readLine({promptFn:()=>Lc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let O=e.slashCtx;O.stats.planMode&&O.stats.pendingPlanExit?(O.stats.pendingPlanExit=!1,Et(O,!1,{closureSummarySkipped:!0}).catch(()=>{})):Et(O).catch(()=>{}),e.statusLine.rearm()}});D=x.text.trim(),j=x.attachments}if(!D&&j.length===0)continue;if(D.startsWith("!")){let x=/^(0|false|off|no)$/i.test(T.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!x&&(h||(h=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await f.dispatch(D))){e.statusLine.rearm();continue}}let N=!1;if(D.startsWith("/")){let x=await GS(D,e.slashCtx,j);if(x.handled){if(x.result==="exit"){e.rl.close();return}if((D==="/clear"||D.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),g.reset()),x.result!==null&&typeof x.result=="object"&&"kind"in x.result&&x.result.kind==="submit"){l={text:x.result.message,attachments:j??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}N=!0}i.push(D),await qW(e,D);let W=D;if(N){let x=mp(D);if(x){let O=x.name.replace(/^\//,"").split(":").pop()??"";if(O&&gm(O)){let B={skillName:O,rawArgs:x.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},J=e.session.current.sessionId,H=Cr(J),F=Date.now();Y(`[afk trace] preflight.start commandName=${O}`);let V=!1,ye=await Ar(B,{cwd:e.stats.cwd??process.cwd(),artifactDir:H},Ne=>{Ue()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${O}) failed: `)+(Ne instanceof Error?Ne.message:String(Ne)))});V=ye!==null,Y(`[afk trace] preflight.end commandName=${O} durationMs=${Date.now()-F} success=${V}`),W=bm(ye?.manifestBlock,D)}}}let M=f.drainInjections();M.length>0&&(W=M+W),await aE({text:W,attachments:j},e.session.current,e.stats,{setInFlight(x){n.turnInFlight=x},async onTurnComplete(x,O){if(await t.appendTurn(x,O),e.stats.sessionId)try{Ht(e.stats)}catch(B){b||(b=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(B instanceof Error?B.message:String(B))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await sk(e.slashCtx),e.statusLine.rearm(),p?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:x=>g?.push(x),setActiveCompositor:x=>{n.activeCompositor=x},setInterruptNotifier:x=>{n.notifyInterrupting=x},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:x=>a.setBackgroundHandler(x),setSoftStopHandler:x=>a.setSoftStopHandler(x),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(yr(e.stats,e.contextSampler))},...p?{onStageChange:x=>p.repaint(x)}:{}},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(Lc(e.stats.model,e.stats.planMode)))}}finally{if(u!==void 0)for(let E of u.running())u.cancel(E.id);n.tryAbortShellForeground=null,f?.drainOnExit(),p?.stop(),d?.stop(),g?.stop(),c?.dispose();let S=E=>console.log(E);e.completionWriter.fn=S,e.completionWriter.idleFn=S,await a.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}import{execFile as JW}from"node:child_process";import{dirname as YW,isAbsolute as VW,resolve as XW}from"node:path";import{promisify as ZW}from"node:util";var hE=ZW(JW),QW=3e3,eK=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function tK(){let t=(await hE("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=VW(t)?t:XW(process.cwd(),t);return YW(n)}async function yE(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await tK()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),QW)});try{let o=zt({execFile:hE,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>eK.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as nK}from"node:fs";import{dirname as rK,join as SE}from"node:path";import{randomBytes as oK}from"node:crypto";var sK=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
1880
- `),bE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wm=30,iK=1024,aK=8e3,lK="haiku";async function cK(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=mK(n,iK),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??aK),i=t.signal?fK([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Zr({token:t.token,model:t.model??lK,system:sK,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=uK(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=rK(t.worktreePath);return await dK(l,c)}function uK(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(bE.test(t)&&t.length<=Wm)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Wm)break;o=i}return bE.test(o)?o:null}async function dK(e,t){if(!await pK(SE(t,e)))return e;let n=oK(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wm-5)}-${n}`}async function pK(e){try{return await nK.access(e),!0}catch{return!1}}function mK(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function fK(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function kE(e){let t,n,r=SE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await cK(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Ba(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return wE(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return wE(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function wE(e,t){e&&e.setCwd(t),gK(t)}function gK(e){try{process.chdir(e)}catch{}}K();import{spawn as vE}from"child_process";import{existsSync as SK,mkdirSync as kK,readFileSync as TE,unlinkSync as vK,writeFileSync as TK}from"fs";import{get as xK}from"https";import{join as xE}from"path";import{readFileSync as hK}from"fs";import{dirname as yK,join as bK}from"path";import{fileURLToPath as wK}from"url";function yn(){try{return"3.82.0"}catch{}try{let e=yK(wK(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(hK(bK(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}z();var EK=64*1024,RK=1440*60*1e3,AK="update-check.json",CK="pending-update.json";function EE(){return xE(Hi(),AK)}function Km(){return xE(Hi(),CK)}function RE(){let e=Hi();SK(e)||kK(e,{recursive:!0})}function _K(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function IK(){try{let e=TE(EE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function PK(){try{RE();let e=`
1880
+ `),bE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wm=30,iK=1024,aK=8e3,lK="haiku";async function cK(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=mK(n,iK),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??aK),i=t.signal?fK([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Zr({token:t.token,model:t.model??lK,system:sK,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=uK(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=rK(t.worktreePath);return await dK(l,c)}function uK(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(bE.test(t)&&t.length<=Wm)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Wm)break;o=i}return bE.test(o)?o:null}async function dK(e,t){if(!await pK(SE(t,e)))return e;let n=oK(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wm-5)}-${n}`}async function pK(e){try{return await nK.access(e),!0}catch{return!1}}function mK(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function fK(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function kE(e){let t,n,r=SE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await cK(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Ba(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return wE(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return wE(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function wE(e,t){e&&e.setCwd(t),gK(t)}function gK(e){try{process.chdir(e)}catch{}}K();import{spawn as vE}from"child_process";import{existsSync as SK,mkdirSync as kK,readFileSync as TE,unlinkSync as vK,writeFileSync as TK}from"fs";import{get as xK}from"https";import{join as xE}from"path";import{readFileSync as hK}from"fs";import{dirname as yK,join as bK}from"path";import{fileURLToPath as wK}from"url";function yn(){try{return"3.83.0"}catch{}try{let e=yK(wK(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(hK(bK(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}z();var EK=64*1024,RK=1440*60*1e3,AK="update-check.json",CK="pending-update.json";function EE(){return xE(Hi(),AK)}function Km(){return xE(Hi(),CK)}function RE(){let e=Hi();SK(e)||kK(e,{recursive:!0})}function _K(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function IK(){try{let e=TE(EE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function PK(){try{RE();let e=`
1881
1881
  const https = require('https');
1882
1882
  const fs = require('fs');
1883
1883
  const url = 'https://registry.npmjs.org/agent-afk/latest';
package/dist/index.mjs CHANGED
@@ -1205,9 +1205,9 @@ Create a ship-ready summary with next steps.`,l=await a.runToResult(c);if(l.stat
1205
1205
  `,4);if(e===-1)return{frontmatter:null,frontmatterFlags:null,body:t};let n=t.slice(4,e),r=t.slice(e+5),o={},s=null,i=n.split(`
1206
1206
  `);for(let a=0;a<i.length;a++){let c=i[a];if(!c||!c.trim()||c.trimStart().startsWith("#"))continue;if(c.startsWith("flags:")){let d=c.slice(6).trim();if(d.startsWith("[")){let u=d.match(/\[(.*?)\]/);if(u?.[1]){let p=u[1].split(",").map(f=>f.trim()).filter(f=>f.length>0);p.length>0&&(s=p.map(Ja).sort())}continue}if(d===""||d==="null"){let u=[];for(let p=a+1;p<i.length;p++){let f=i[p];if(!f||!f.match(/^\s+-\s/))break;let g=f.match(/^\s+-\s+(.+)/);g?.[1]&&u.push(g[1].trim())}u.length>0&&(s=u.map(Ja).sort());continue}}let l=c.match(/^([a-zA-Z][a-zA-Z0-9_-]*):\s*(.*)$/);if(l&&l[1]!==void 0&&l[2]!==void 0){let d=l[2].trim().replace(/^['"]|['"]$/g,"");d.length>0&&(o[l[1]]=d)}}return{frontmatter:o,frontmatterFlags:s,body:r}}function Va(t){let e=Vr(t);return e.frontmatterFlags&&e.frontmatterFlags.length>0?e.frontmatterFlags:Vg(e.body)}function Qg(t,e){return t.length===0||t.length>64?{valid:!1,reason:`name must be 1\u201364 characters, got ${t.length}`}:/^[a-z0-9]+(-[a-z0-9]+)*$/.test(t)?t!==e?{valid:!1,reason:`name field "${t}" does not match parent directory name "${e}"`}:{valid:!0}:{valid:!1,reason:`name "${t}" does not match spec pattern ^[a-z0-9]+(-[a-z0-9]+)*$ (only lowercase a-z0-9 and hyphens, no leading/trailing/consecutive hyphens)`}}var Xa=1024;function Zg(t,e){let n=Vr(t);if(!n.frontmatter)return null;let r=n.frontmatter.name,o=n.frontmatter.description,s=n.body.trim();if(!r||!o||s.length===0)return null;let i=Qg(r,e);if(!i.valid)return process.stderr.write(`[afk] skipping skill ${e}: ${i.reason}
1207
1207
  `),null;if(o.length>Xa)return process.stderr.write(`[afk] skipping skill ${e}: description exceeds ${Xa} characters (got ${o.length})
1208
- `),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,c=Va(t),l={name:r,description:o,body:s,dir:""};return a&&a.length>0&&(l.argumentHint=a),c.length>0&&(l.flags=c),l}function eh(t){return async(e,n,r)=>{let o=typeof e=="string"&&e.length>0?e:`Run the ${t.name} skill now, following the instructions in your system prompt.`,s=new N({parentAbortSignal:n?.abortSignal}),i=r?.callId;return await(await s.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:"sonnet",systemPrompt:t.body,env:{SKILL_ROOT:t.dir},isSkillDispatch:!0},idPrefix:`user-skill-${t.name}`,...i?{parentId:i}:{}})).runToResult(o)}}function th(t,e){try{return ye(t).origin===e?t:`${e}:${t}`}catch{return t}}function En(t,e){let n;try{n=Yg(t,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${t}: ${s.message}
1208
+ `),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,c=Va(t),l={name:r,description:o,body:s,dir:""};a&&a.length>0&&(l.argumentHint=a),c.length>0&&(l.flags=c);let d=n.frontmatter.context;return(d==="inline"||d==="fork"||d==="load")&&(l.context=d),l}function eh(t){return async(e,n,r)=>{let o=typeof e=="string"&&e.length>0?e:`Run the ${t.name} skill now, following the instructions in your system prompt.`,s=new N({parentAbortSignal:n?.abortSignal}),i=r?.callId;return await(await s.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:"sonnet",systemPrompt:t.body,env:{SKILL_ROOT:t.dir},isSkillDispatch:!0},idPrefix:`user-skill-${t.name}`,...i?{parentId:i}:{}})).runToResult(o)}}function th(t,e){try{return ye(t).origin===e?t:`${e}:${t}`}catch{return t}}function En(t,e){let n;try{n=Yg(t,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${t}: ${s.message}
1209
1209
  `),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=Xg(Ya(t,o.name,"SKILL.md"),"utf-8")}catch(l){let d=l;d.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${d.message}
1210
- `);continue}let i=Zg(s,o.name);if(!i)continue;i.dir=Ya(t,o.name);let c={name:th(i.name,e),description:i.description,handler:eh(i),origin:e};i.argumentHint&&(c.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(c.flags=i.flags),te(c),r++}return r}import{existsSync as nh,readdirSync as rh,readFileSync as oh,statSync as sh}from"fs";import{join as ih}from"path";function Yr(t){let e=[];function n(r,o=0){if(o>10||!nh(r))return;let s;try{s=rh(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=ih(r,i),c;try{c=sh(a)}catch{continue}if(c.isFile()&&i==="SKILL.md"){let l=ah(a);l.name&&e.push(l)}else c.isDirectory()&&n(a,o+1)}}return n(t),e}function ah(t){try{let e=oh(t,"utf-8");if(!e.startsWith(`---
1210
+ `);continue}let i=Zg(s,o.name);if(!i)continue;i.dir=Ya(t,o.name);let c={name:th(i.name,e),description:i.description,handler:eh(i),origin:e};i.argumentHint&&(c.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(c.flags=i.flags),i.context!=="fork"&&(c.context="load",c.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),te(c),r++}return r}import{existsSync as nh,readdirSync as rh,readFileSync as oh,statSync as sh}from"fs";import{join as ih}from"path";function Yr(t){let e=[];function n(r,o=0){if(o>10||!nh(r))return;let s;try{s=rh(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=ih(r,i),c;try{c=sh(a)}catch{continue}if(c.isFile()&&i==="SKILL.md"){let l=ah(a);l.name&&e.push(l)}else c.isDirectory()&&n(a,o+1)}}return n(t),e}function ah(t){try{let e=oh(t,"utf-8");if(!e.startsWith(`---
1211
1211
  `))return{};let n=e.slice(4),r=n.indexOf(`
1212
1212
  ---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
1213
1213
  `);for(let c of a){if(!c)continue;let l=c.indexOf(":");if(l===-1)continue;let d=c.slice(0,l).trim(),u=c.slice(l+1).trim();if(d==="name")i.name=u.replace(/^["']|["']$/g,"");else if(d==="description")i.description=u.replace(/^["']|["']$/g,"");else if(d==="argumentHint")i.argumentHint=u.replace(/^["']|["']$/g,"");else if(d==="audience"){let p=u.replace(/^["']|["']$/g,"");(p==="public"||p==="internal")&&(i.audience=p)}else d==="context"&&(i.context=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}U();L();function Qa(t){let e=st(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):","","Each skill either dispatches one or more context-isolated subagents (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context (`load` mode). Calling `skill` is the entry point for both; the executor picks the mode per skill. Prefer a skill over inline investigation when the task shape matches.","",...n].join(`