agent-afk 2.7.1 → 2.8.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.
- package/dist/cli.mjs +118 -118
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/telegram.mjs
CHANGED
|
@@ -1478,7 +1478,7 @@ Single-pass sub-agent reports are prone to confident hallucination \u2014 polish
|
|
|
1478
1478
|
|
|
1479
1479
|
Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`;function Xl(t){if(!t)return!1;let e=t.toLowerCase();return zl.some(n=>e.includes(n))}function Ql(t){return Yl.some(e=>e.test(t))}function Zl(t){let e=0;for(let n of Vl)n.test(t)&&e++;return e}function ls(t){if(t.event!=="SubagentStop")return{};let e=t.lastMessage??"";return e.length<600?{}:Xl(t.agentType)?{}:Ql(e)?{}:Zl(e)<2?{}:{injectContext:Jl}}function mn(t,e,n){let r=cs();r.register("SubagentStop",ls);let o=n??new Z;return r.register("SessionEnd",Dt(o,e)),t&&r.register("SubagentStop",s=>s.event!=="SubagentStop"?{}:s.status==="idle"||s.status==="running"?{}:(t({subagentId:s.subagentId,status:s.status,durationMs:s.durationMs,agentType:s.agentType}),{})),{registry:r,memoryStore:o}}var ed="[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Multi-file implementation or new features \u2192 `/mint`\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n- Parallel or dependent multi-task work \u2192 `compose` tool (DAG of subagent nodes)\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n- Diagnose + fix in parallel \u2192 `compose` with two independent nodes\n- Research \u2192 implement \u2192 verify pipeline \u2192 `compose` with edges: research\u2192implement\u2192verify\n- Multiple independent investigations \u2192 `compose` with N nodes, no edges\n\nReach for context-isolated investigators when the task is exploratory:\n\n- Map an unfamiliar module before editing \u2192 `/gather` or `/research`\n- Re-derive a load-bearing claim independently \u2192 `/shadow-verify`\n- Audit a diff before merge \u2192 `/review`\n- Survey git + infra + memory before non-trivial work \u2192 `/ground-state`\n- Generate alternatives before committing to a plan \u2192 `/devils-advocate`\n\nOr dispatch a raw `agent` call when no skill matches but the work is parallelizable, verification-heavy, or would otherwise consume substantial inline context.\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony. If a skill would add overhead without adding value, don't invoke it.";function gn(t,e){return!t||!e?t:`${t}
|
|
1480
1480
|
|
|
1481
|
-
${ed}`}var td=new Set;function ds(t){return td.has(t)}var nd=new Set,rd=new Set;function us(t){for(let e of nd)e(t)}function ps(t){for(let e of rd)e(t)}function od(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function sd(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var ve=class{constructor(e){this.ctx=e}ctx;pluginBodies=null;async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Oe;if(n>=r){let a=od(e.input);return V({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:a}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=sd(e.input)}catch(a){return{content:`Skill tool input validation failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}try{let a=te(o.name);return await this.executeRegistrySkill(a,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s,o.arguments,e);let c=Me(this.ctx.pluginConfigs).map(a=>a.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${c||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);let o=ds(e.name);o&&ps(e.name);let s=Date.now(),i,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(l){i=l}finally{if(o){let l=Date.now()-s;us({skillName:e.name,durationMs:l,...i!==void 0?{isError:!0}:{}})}}return i!==void 0?{content:`Skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=I(e.name)["system.md"],!o)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(i){return{content:`Failed to load skill prompts: ${i instanceof Error?i.message:String(i)}`,isError:!0}}let s=new k({parentAbortSignal:r.signal,apiKey:this.ctx.apiKey,progressSink:ne()});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o},idPrefix:`skill-fork-${e.name}`,parentId:r.id}),c=n&&n.length>0?n:"Run the skill.",a=await i.runToResult(c);return a.status==="succeeded"&&a.message?{content:a.message.content}:{content:a.error?.message??"Forked skill failed with no output",isError:!0}}catch(i){return{content:`Forked skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}async executePluginSkill(e,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=new k({parentAbortSignal:o.signal,apiKey:this.ctx.apiKey,progressSink:ne()});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n},idPrefix:`skill-${e}`,parentId:o.id}),c=r&&r.length>0?r:"Run the skill.",a=await i.runToResult(c);return a.status==="succeeded"&&a.message?{content:a.message.content}:{content:a.error?.message??"Plugin skill failed with no output",isError:!0}}catch(i){return{content:`Plugin skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=mt(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}};var Oe=3;function hn(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var id=[...Pe,"agent","skill"];function fs(){return({childExecutor:t,childSkillExecutor:e})=>new ie({permissions:{allowedTools:id},subagentExecutor:t,skillExecutor:e})}function ms(t,e){return(n,r,o)=>new ve({parentSession:hn(o),defaultModel:t,apiKey:e,depth:n,maxDepth:r})}function ad(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let c="agent-tool",a=e.id_prefix;if(a!==void 0){if(typeof a!="string")throw new Error("Agent tool id_prefix must be a string");c=a}return{prompt:n,model:r,max_turns:s,id_prefix:c}}function yn(t){try{return V(t).catch(()=>{})}catch{return Promise.resolve()}}function Ne(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function hs(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}var cd=4096,gs=1024;function ld(t){if(t==null)return;let e=hs(t);return e!==void 0&&e>cd?{truncated:!0,chars:e}:t}function dd(t){let e={status:t.status,error:Ne(t.errorMessage,gs),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=Ne(t.schemaErrorMessage,gs));let n=ld(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var xt=class t{constructor(e){this.ctx=e}ctx;async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=ad(e.input)}catch(p){return{content:`Agent tool input validation failed: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let r=this.ctx.depth??0,o=this.ctx.maxDepth??Oe,s,i={model:n.model??this.ctx.defaultSubagentModel??"sonnet",apiKey:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,maxTurns:n.max_turns},c;if(this.ctx.childProviderFactory&&r<o){s=new k({parentAbortSignal:e.signal}),c=hn(e.signal);let p=new t({subagentManager:s,parentSession:c,defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o}),f=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;i.provider=this.ctx.childProviderFactory({childExecutor:p,childSkillExecutor:f})}let a;try{a=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:i,idPrefix:n.id_prefix}),c!==void 0&&(c.sessionId=a.id)}catch(p){return{content:`Failed to fork subagent: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let l=()=>{a.cancel()};e.signal.addEventListener("abort",l,{once:!0});let d=Date.now(),u=this.ctx.parentSession.sessionId;try{let p=await a.runToResult(n.prompt);if(p.status==="succeeded"&&p.message){let m=p.message.content,y=typeof m=="string"?m:JSON.stringify(m),b=p.trace;return yn({event:"subagent.completed",subagent_id:a.id,parent_session_id:u,status:p.status,duration_ms:Date.now()-d,content_chars:y.length,depth:r,tool_call_count:b?.toolCalls.length,thinking_present:b?.thinkingPresent,tool_names:b?.toolCalls.length?JSON.stringify([...new Set(b.toolCalls.map(x=>x.name))]):void 0}),{content:y}}let f=p.error?.message??"Subagent failed with no output",g=p.trace;yn({event:"subagent.failed",subagent_id:a.id,parent_session_id:u,status:p.status,duration_ms:Date.now()-d,error_message:Ne(f),schema_error:p.schemaError?Ne(p.schemaError.message):void 0,partial_output_chars:hs(p.partialOutput),depth:r,tool_call_count:g?.toolCalls.length,thinking_present:g?.thinkingPresent,tool_names:g?.toolCalls.length?JSON.stringify([...new Set(g.toolCalls.map(m=>m.name))]):void 0});let h=dd({status:p.status,errorMessage:f,schemaErrorMessage:p.schemaError?.message,partialOutput:p.partialOutput,subagentId:a.id});return{content:JSON.stringify(h),isError:!0}}catch(p){let f=p instanceof Error?p.message:String(p);throw yn({event:"subagent.failed",subagent_id:a.id,parent_session_id:u,status:"failed",duration_ms:Date.now()-d,error_message:Ne(f),depth:r}),p}finally{e.signal.removeEventListener("abort",l),await s?.teardownAll(),await a.teardown()}}};function ud(t){let e=new Set;for(let c of t.nodes){if(e.has(c.id))throw new Error(`Duplicate node ID: ${c.id}`);e.add(c.id)}let n=new Set;for(let c of t.edges){if(!e.has(c.from))throw new Error(`Edge references non-existent node: ${c.from}`);if(!e.has(c.to))throw new Error(`Edge references non-existent node: ${c.to}`);let a=`${c.from}->${c.to}`;if(n.has(a))throw new Error(`Duplicate edge: ${c.from} -> ${c.to}`);n.add(a)}let r=ys(t),o=new Map(r.inDegree),s=[];for(let[c,a]of o)a===0&&s.push(c);let i=0;for(;s.length>0;){let c=s.shift();i+=1;for(let a of r.downstream.get(c)??[]){let l=o.get(a)-1;o.set(a,l),l===0&&s.push(a)}}if(i!==e.size)throw new Error("Cycle detected in DAG")}function ys(t){let e=new Map,n=new Map,r=new Map;for(let o of t.nodes)e.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of t.edges)e.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:e,upstream:n,inDegree:r}}function pd(t,e,n){let r=[t];for(;r.length>0;){let o=r.shift();for(let s of e.get(o)??[])n.has(s)||(n.add(s),r.push(s))}}async function bs(t,e,n={}){if(t.nodes.length===0)return{outputs:{},failed:[],skipped:[]};ud(t);let{failFast:r=!0}=n,o=ys(t),s=new Map(t.nodes.map(f=>[f.id,f])),i={},c=[],a=new Set,l=new Set,d=new Map(o.inDegree),u=new AbortController,p=()=>{u.signal.aborted||u.abort(e.reason)};e.aborted?u.abort(e.reason):e.addEventListener("abort",p,{once:!0});try{for(;!u.signal.aborted;){let f=[];for(let[h,m]of d)m===0&&!l.has(h)&&!a.has(h)&&f.push(h);if(f.length===0)break;let g=await Promise.allSettled(f.map(async h=>{let m=s.get(h),y=new AbortController,b=()=>{y.signal.aborted||y.abort(u.signal.reason)};u.signal.aborted?y.abort(u.signal.reason):u.signal.addEventListener("abort",b,{once:!0});let x={};for(let F of o.upstream.get(h)??[])x[F]=i[F];try{let F=await m.run(x,y.signal);return{id:h,result:F}}finally{u.signal.removeEventListener("abort",b)}}));for(let h=0;h<g.length;h++){let m=g[h];if(m.status==="fulfilled"){let{id:y,result:b}=m.value;i[y]=b,l.add(y),d.delete(y);for(let x of o.downstream.get(y)??[])d.set(x,d.get(x)-1)}else{let y=m.reason instanceof Error?m.reason:new Error(String(m.reason)),b=f[h];c.push({id:b,error:y}),l.add(b),d.delete(b),pd(b,o.downstream,a),r&&u.abort("fail-fast")}}}}finally{e.removeEventListener("abort",p)}return{outputs:i,failed:c,skipped:Array.from(a)}}async function ws(t){let{manager:e,parentSession:n,nodes:r,edges:o,failFast:s}=t,i=n.abortSignal??new AbortController().signal,c=r.map(a=>({id:a.id,async run(l,d){let u=await e.forkSubagent({parent:{sessionId:n.sessionId},config:{model:a.model??"sonnet",systemPrompt:a.systemPrompt,...a.canUseTool!==void 0?{canUseTool:a.canUseTool}:{}},idPrefix:a.idPrefix??`dag-${a.id}`,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{},...a.agentType!==void 0?{agentType:a.agentType}:{},...a.parentId!==void 0?{parentId:a.parentId}:{}});try{if(d.aborted)throw new DOMException("Aborted","AbortError");let p=a.promptBuilder(l),f=await u.runToResult(p);if(f.status!=="succeeded")throw f.error??new Error(`Subagent ${a.id} ${f.status}`);return f.output??f.message?.content}finally{await u.teardown().catch(()=>{})}}}));return bs({nodes:c,edges:o},i,{failFast:s})}function fd(t){if(typeof t!="object"||t===null)throw new Error("Compose tool input must be an object");let e=t,n=e.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],s=new Set;for(let a of n){if(typeof a!="object"||a===null)throw new Error("Each node must be an object");let l=a,d=l.id;if(typeof d!="string"||d.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(d)){let f=d.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${f}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(s.has(d))throw new Error(`Duplicate node ID: ${d}`);s.add(d);let u=l.prompt;if(typeof u!="string"||u.trim().length===0)throw new Error(`Node "${d}" must have a non-empty "prompt" string`);let p;if(l.model!==void 0){if(typeof l.model!="string")throw new Error(`Node "${d}" model must be a string`);p=l.model}o.push({id:d,prompt:u,model:p})}let i;if(e.edges!==void 0){if(!Array.isArray(e.edges))throw new Error('"edges" must be an array');i=[];for(let a of e.edges){if(typeof a!="object"||a===null)throw new Error("Each edge must be an object");let l=a;if(typeof l.from!="string"||typeof l.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!s.has(l.from))throw new Error(`Edge references non-existent node: ${l.from}`);if(!s.has(l.to))throw new Error(`Edge references non-existent node: ${l.to}`);i.push({from:l.from,to:l.to})}}let c;if(e.fail_fast!==void 0){if(typeof e.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');c=e.fail_fast}return{nodes:o,edges:i,fail_fast:c}}var ks=8e3,vs=500;function md(t){let e=[];for(let[n,r]of Object.entries(t.outputs)){let o=typeof r=="string"?r:r!=null?JSON.stringify(r):"(no output)",s=o.length>ks?o.slice(0,ks)+`
|
|
1481
|
+
${ed}`}var td=new Set;function ds(t){return td.has(t)}var nd=new Set,rd=new Set;function us(t){for(let e of nd)e(t)}function ps(t){for(let e of rd)e(t)}function od(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function sd(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var ve=class{constructor(e){this.ctx=e}ctx;pluginBodies=null;async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Oe;if(n>=r){let a=od(e.input);return V({event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:a}).catch(()=>{}),{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0}}let o;try{o=sd(e.input)}catch(a){return{content:`Skill tool input validation failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}try{let a=te(o.name);return await this.executeRegistrySkill(a,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s,o.arguments,e);let c=Me(this.ctx.pluginConfigs).map(a=>a.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${c||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);let o=ds(e.name);o&&ps(e.name);let s=Date.now(),i,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(l){i=l}finally{if(o){let l=Date.now()-s;us({skillName:e.name,durationMs:l,...i!==void 0?{isError:!0}:{}})}}return i!==void 0?{content:`Skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=I(e.name)["system.md"],!o)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(i){return{content:`Failed to load skill prompts: ${i instanceof Error?i.message:String(i)}`,isError:!0}}let s=new k({parentAbortSignal:r.signal,apiKey:this.ctx.apiKey,progressSink:ne()});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o},idPrefix:`skill-fork-${e.name}`,parentId:r.id,agentType:e.name}),c=n&&n.length>0?n:"Run the skill.",a=await i.runToResult(c);return a.status==="succeeded"&&a.message?{content:a.message.content}:{content:a.error?.message??"Forked skill failed with no output",isError:!0}}catch(i){return{content:`Forked skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}async executePluginSkill(e,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=new k({parentAbortSignal:o.signal,apiKey:this.ctx.apiKey,progressSink:ne()});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n},idPrefix:`skill-${e}`,parentId:o.id,agentType:e}),c=r&&r.length>0?r:"Run the skill.",a=await i.runToResult(c);return a.status==="succeeded"&&a.message?{content:a.message.content}:{content:a.error?.message??"Plugin skill failed with no output",isError:!0}}catch(i){return{content:`Plugin skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=mt(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}};var Oe=3;function hn(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var id=[...Pe,"agent","skill"];function fs(){return({childExecutor:t,childSkillExecutor:e})=>new ie({permissions:{allowedTools:id},subagentExecutor:t,skillExecutor:e})}function ms(t,e){return(n,r,o)=>new ve({parentSession:hn(o),defaultModel:t,apiKey:e,depth:n,maxDepth:r})}function ad(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let c="agent-tool",a=e.id_prefix;if(a!==void 0){if(typeof a!="string")throw new Error("Agent tool id_prefix must be a string");c=a}return{prompt:n,model:r,max_turns:s,id_prefix:c}}function yn(t){try{return V(t).catch(()=>{})}catch{return Promise.resolve()}}function Ne(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function hs(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}var cd=4096,gs=1024;function ld(t){if(t==null)return;let e=hs(t);return e!==void 0&&e>cd?{truncated:!0,chars:e}:t}function dd(t){let e={status:t.status,error:Ne(t.errorMessage,gs),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=Ne(t.schemaErrorMessage,gs));let n=ld(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var xt=class t{constructor(e){this.ctx=e}ctx;async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=ad(e.input)}catch(p){return{content:`Agent tool input validation failed: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let r=this.ctx.depth??0,o=this.ctx.maxDepth??Oe,s,i={model:n.model??this.ctx.defaultSubagentModel??"sonnet",apiKey:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,maxTurns:n.max_turns},c;if(this.ctx.childProviderFactory&&r<o){s=new k({parentAbortSignal:e.signal}),c=hn(e.signal);let p=new t({subagentManager:s,parentSession:c,defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o}),f=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;i.provider=this.ctx.childProviderFactory({childExecutor:p,childSkillExecutor:f})}let a;try{a=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:i,idPrefix:n.id_prefix}),c!==void 0&&(c.sessionId=a.id)}catch(p){return{content:`Failed to fork subagent: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let l=()=>{a.cancel()};e.signal.addEventListener("abort",l,{once:!0});let d=Date.now(),u=this.ctx.parentSession.sessionId;try{let p=await a.runToResult(n.prompt);if(p.status==="succeeded"&&p.message){let m=p.message.content,y=typeof m=="string"?m:JSON.stringify(m),b=p.trace;return yn({event:"subagent.completed",subagent_id:a.id,parent_session_id:u,status:p.status,duration_ms:Date.now()-d,content_chars:y.length,depth:r,tool_call_count:b?.toolCalls.length,thinking_present:b?.thinkingPresent,tool_names:b?.toolCalls.length?JSON.stringify([...new Set(b.toolCalls.map(x=>x.name))]):void 0}),{content:y}}let f=p.error?.message??"Subagent failed with no output",g=p.trace;yn({event:"subagent.failed",subagent_id:a.id,parent_session_id:u,status:p.status,duration_ms:Date.now()-d,error_message:Ne(f),schema_error:p.schemaError?Ne(p.schemaError.message):void 0,partial_output_chars:hs(p.partialOutput),depth:r,tool_call_count:g?.toolCalls.length,thinking_present:g?.thinkingPresent,tool_names:g?.toolCalls.length?JSON.stringify([...new Set(g.toolCalls.map(m=>m.name))]):void 0});let h=dd({status:p.status,errorMessage:f,schemaErrorMessage:p.schemaError?.message,partialOutput:p.partialOutput,subagentId:a.id});return{content:JSON.stringify(h),isError:!0}}catch(p){let f=p instanceof Error?p.message:String(p);throw yn({event:"subagent.failed",subagent_id:a.id,parent_session_id:u,status:"failed",duration_ms:Date.now()-d,error_message:Ne(f),depth:r}),p}finally{e.signal.removeEventListener("abort",l),await s?.teardownAll(),await a.teardown()}}};function ud(t){let e=new Set;for(let c of t.nodes){if(e.has(c.id))throw new Error(`Duplicate node ID: ${c.id}`);e.add(c.id)}let n=new Set;for(let c of t.edges){if(!e.has(c.from))throw new Error(`Edge references non-existent node: ${c.from}`);if(!e.has(c.to))throw new Error(`Edge references non-existent node: ${c.to}`);let a=`${c.from}->${c.to}`;if(n.has(a))throw new Error(`Duplicate edge: ${c.from} -> ${c.to}`);n.add(a)}let r=ys(t),o=new Map(r.inDegree),s=[];for(let[c,a]of o)a===0&&s.push(c);let i=0;for(;s.length>0;){let c=s.shift();i+=1;for(let a of r.downstream.get(c)??[]){let l=o.get(a)-1;o.set(a,l),l===0&&s.push(a)}}if(i!==e.size)throw new Error("Cycle detected in DAG")}function ys(t){let e=new Map,n=new Map,r=new Map;for(let o of t.nodes)e.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of t.edges)e.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:e,upstream:n,inDegree:r}}function pd(t,e,n){let r=[t];for(;r.length>0;){let o=r.shift();for(let s of e.get(o)??[])n.has(s)||(n.add(s),r.push(s))}}async function bs(t,e,n={}){if(t.nodes.length===0)return{outputs:{},failed:[],skipped:[]};ud(t);let{failFast:r=!0}=n,o=ys(t),s=new Map(t.nodes.map(f=>[f.id,f])),i={},c=[],a=new Set,l=new Set,d=new Map(o.inDegree),u=new AbortController,p=()=>{u.signal.aborted||u.abort(e.reason)};e.aborted?u.abort(e.reason):e.addEventListener("abort",p,{once:!0});try{for(;!u.signal.aborted;){let f=[];for(let[h,m]of d)m===0&&!l.has(h)&&!a.has(h)&&f.push(h);if(f.length===0)break;let g=await Promise.allSettled(f.map(async h=>{let m=s.get(h),y=new AbortController,b=()=>{y.signal.aborted||y.abort(u.signal.reason)};u.signal.aborted?y.abort(u.signal.reason):u.signal.addEventListener("abort",b,{once:!0});let x={};for(let F of o.upstream.get(h)??[])x[F]=i[F];try{let F=await m.run(x,y.signal);return{id:h,result:F}}finally{u.signal.removeEventListener("abort",b)}}));for(let h=0;h<g.length;h++){let m=g[h];if(m.status==="fulfilled"){let{id:y,result:b}=m.value;i[y]=b,l.add(y),d.delete(y);for(let x of o.downstream.get(y)??[])d.set(x,d.get(x)-1)}else{let y=m.reason instanceof Error?m.reason:new Error(String(m.reason)),b=f[h];c.push({id:b,error:y}),l.add(b),d.delete(b),pd(b,o.downstream,a),r&&u.abort("fail-fast")}}}}finally{e.removeEventListener("abort",p)}return{outputs:i,failed:c,skipped:Array.from(a)}}async function ws(t){let{manager:e,parentSession:n,nodes:r,edges:o,failFast:s}=t,i=n.abortSignal??new AbortController().signal,c=r.map(a=>({id:a.id,async run(l,d){let u=await e.forkSubagent({parent:{sessionId:n.sessionId},config:{model:a.model??"sonnet",systemPrompt:a.systemPrompt,...a.canUseTool!==void 0?{canUseTool:a.canUseTool}:{}},idPrefix:a.idPrefix??`dag-${a.id}`,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{},...a.agentType!==void 0?{agentType:a.agentType}:{},...a.parentId!==void 0?{parentId:a.parentId}:{}});try{if(d.aborted)throw new DOMException("Aborted","AbortError");let p=a.promptBuilder(l),f=await u.runToResult(p);if(f.status!=="succeeded")throw f.error??new Error(`Subagent ${a.id} ${f.status}`);return f.output??f.message?.content}finally{await u.teardown().catch(()=>{})}}}));return bs({nodes:c,edges:o},i,{failFast:s})}function fd(t){if(typeof t!="object"||t===null)throw new Error("Compose tool input must be an object");let e=t,n=e.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],s=new Set;for(let a of n){if(typeof a!="object"||a===null)throw new Error("Each node must be an object");let l=a,d=l.id;if(typeof d!="string"||d.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(d)){let f=d.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${f}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(s.has(d))throw new Error(`Duplicate node ID: ${d}`);s.add(d);let u=l.prompt;if(typeof u!="string"||u.trim().length===0)throw new Error(`Node "${d}" must have a non-empty "prompt" string`);let p;if(l.model!==void 0){if(typeof l.model!="string")throw new Error(`Node "${d}" model must be a string`);p=l.model}o.push({id:d,prompt:u,model:p})}let i;if(e.edges!==void 0){if(!Array.isArray(e.edges))throw new Error('"edges" must be an array');i=[];for(let a of e.edges){if(typeof a!="object"||a===null)throw new Error("Each edge must be an object");let l=a;if(typeof l.from!="string"||typeof l.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!s.has(l.from))throw new Error(`Edge references non-existent node: ${l.from}`);if(!s.has(l.to))throw new Error(`Edge references non-existent node: ${l.to}`);i.push({from:l.from,to:l.to})}}let c;if(e.fail_fast!==void 0){if(typeof e.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');c=e.fail_fast}return{nodes:o,edges:i,fail_fast:c}}var ks=8e3,vs=500;function md(t){let e=[];for(let[n,r]of Object.entries(t.outputs)){let o=typeof r=="string"?r:r!=null?JSON.stringify(r):"(no output)",s=o.length>ks?o.slice(0,ks)+`
|
|
1482
1482
|
\u2026 (truncated)`:o;e.push(`## ${n}
|
|
1483
1483
|
${s}`)}if(t.failed.length>0)for(let n of t.failed){let r=n.error.message.length>vs?n.error.message.slice(0,vs)+"\u2026 (truncated)":n.error.message;e.push(`## ${n.id} [FAILED]
|
|
1484
1484
|
${r}`)}return t.skipped.length>0&&e.push(`## Skipped
|