agentix-cli 0.207.1 → 0.208.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.
Files changed (29) hide show
  1. package/dist/{agent-OVSBIXDF.js → agent-AG2FLW4B.js} +2 -2
  2. package/dist/{board-dashboard-P7F52WNX.js → board-dashboard-6KGRVAK6.js} +374 -357
  3. package/dist/board-dashboard-6KGRVAK6.js.map +1 -0
  4. package/dist/{chunk-4GN2VGRB.js → chunk-2BWTUD6Z.js} +2 -2
  5. package/dist/chunk-2BWTUD6Z.js.map +1 -0
  6. package/dist/{chunk-RP2YGJDW.js → chunk-D4QTZJ4G.js} +30 -30
  7. package/dist/chunk-D4QTZJ4G.js.map +1 -0
  8. package/dist/{chunk-HHFF7X4L.js → chunk-IANIJUL5.js} +2 -2
  9. package/dist/{chunk-BY7QINNM.js → chunk-IJXCGKAB.js} +3 -3
  10. package/dist/{chunk-T435JKGN.js → chunk-N2E73XNT.js} +23 -23
  11. package/dist/chunk-N2E73XNT.js.map +1 -0
  12. package/dist/{chunk-FNB2IBG7.js → chunk-OW4XJDFO.js} +2 -2
  13. package/dist/cli.js +1 -1
  14. package/dist/index.d.ts +4 -1
  15. package/dist/index.js +1 -1
  16. package/dist/{program-TTGZWU2T.js → program-AJVTYLTY.js} +5 -5
  17. package/dist/program-AJVTYLTY.js.map +1 -0
  18. package/dist/{registry-ZZ27JGL5.js → registry-T2SZPIUE.js} +2 -2
  19. package/package.json +1 -1
  20. package/dist/board-dashboard-P7F52WNX.js.map +0 -1
  21. package/dist/chunk-4GN2VGRB.js.map +0 -1
  22. package/dist/chunk-RP2YGJDW.js.map +0 -1
  23. package/dist/chunk-T435JKGN.js.map +0 -1
  24. package/dist/program-TTGZWU2T.js.map +0 -1
  25. /package/dist/{agent-OVSBIXDF.js.map → agent-AG2FLW4B.js.map} +0 -0
  26. /package/dist/{chunk-HHFF7X4L.js.map → chunk-IANIJUL5.js.map} +0 -0
  27. /package/dist/{chunk-BY7QINNM.js.map → chunk-IJXCGKAB.js.map} +0 -0
  28. /package/dist/{chunk-FNB2IBG7.js.map → chunk-OW4XJDFO.js.map} +0 -0
  29. /package/dist/{registry-ZZ27JGL5.js.map → registry-T2SZPIUE.js.map} +0 -0
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,r=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await ne.readFile(r,"utf8"),l=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await ne.writeFile(r,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${l.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-ZZ27JGL5.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-T2SZPIUE.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,r=t;return o?.length&&(r+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function Oe(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:p=!1,dryRun:c=!1,onProgress:d,abortSignal:u}=n,m=u?{...r,abortSignal:u}:r;if(!e.generateRaw)return mt(n);let I=new se(s,{interactive:a,overwrite:p,dryRun:c,acmeContext:n.acmeContext,abortSignal:u}),D=be(l);if(n.acmeContext)for(let g of ct)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(n.mcpTools?.length)for(let g of n.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,O=0,A="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),k.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let S=null,H=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?S=x.result:x.type==="error"&&(H=x.error);if(H&&!S)throw new Error(H);if(!S)throw new Error("generateRawStream returned no raw_result event");g=S,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(S){if(S.message?.includes("not available"))return mt(n);throw S}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,O+=g.usage.output_tokens;let P=g._streamedText;for(let S of g.content)S.type==="text"&&(A+=S.text,P===void 0&&d?.({type:"text_delta",text:S.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let S=g.content.filter(v=>v.type==="tool_use");if(S.length===0)break;C.push({role:"assistant",content:g.content});let H=[];for(let v of S){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),k.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&n.mcpDispatch){let h=await n.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),H.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:H}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:A,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:O||void 0,iterations:_}}async function mt(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,maxIterations:s=5}=n,l=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${n.projectInstructions}`),n.memoryContext&&o.push(n.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{We as a,Xt as b,Qt as c,Je as d,Ke as e,Xe as f,Qe as g,Pe as h,ee as i,Re as j,ce as k,te as l,Pt as m,oe as n,Et as o,f as p,ot as q,rt as r,Me as s,de as t,W as u,re as v,lt as w,Ee as x,$e as y,se as z,gt as A,tn as B,on as C};
126
- //# sourceMappingURL=chunk-HHFF7X4L.js.map
126
+ //# sourceMappingURL=chunk-IANIJUL5.js.map
@@ -1,4 +1,4 @@
1
- import{Ba as $o,Da as Co,G as po,N as Ut,O as mo,V as Ht,X as fo,a as Qr,b as Xr,d as Dn,f as nt,ha as ho,i as ao,ia as yo,j as co,ja as wo,k as Bt,la as bo,ma as xo,n as Ft,na as So,oa as Io,q as uo,r as lo,ra as To,sa as ko,v as go,va as vo,wa as Ao}from"./chunk-RP2YGJDW.js";import{b as Yr}from"./chunk-MEFPXHQJ.js";import{a as Bn}from"./chunk-W4YR2RO2.js";import{a as Jr}from"./chunk-VJVXEVZ7.js";import{b as Vr,d as Nn,e as to,f as Nt,i as no}from"./chunk-C5VFABFI.js";import{h as Kr,i as zr}from"./chunk-BE64IJWM.js";import{a as On,b as Zr}from"./chunk-J3SOEFRE.js";import{a as Ln,b as eo}from"./chunk-SIU6STB2.js";import{e as so,i as ro,j as oo,k as io}from"./chunk-X5C5W3E4.js";import{d as jr}from"./chunk-HPRLRD4P.js";import{a as Gr}from"./chunk-KN5LZ3JS.js";import{g as Wr,h as qr}from"./chunk-WD4HZAYI.js";import{c as vr,f as Ar}from"./chunk-XPKDQDBH.js";import{s as Tr,v as Lt,w as kr,y as Se,z as Pn}from"./chunk-NXOBCFUJ.js";import{a as tt,b as He,f as Ot}from"./chunk-72SZI2UW.js";import{a as Ue,b as Cn}from"./chunk-FCPTN6NF.js";import{a as $r,c as Cr}from"./chunk-MYVHVJWZ.js";import{e as je,h as Mr,i as _e}from"./chunk-QUFIUXMQ.js";import{a as Rr,b as _r,c as Pr,d as Er,l as Lr,q as Nr}from"./chunk-3AHYZLGE.js";import{a as Dr,b as Or}from"./chunk-LY4G7PCW.js";import{a as Br,b as Hr}from"./chunk-2HBEZV7L.js";import{a as Ur,b as En}from"./chunk-A7JSRDJL.js";import{c as Fr}from"./chunk-BERWTVG2.js";import{c as ur,d as lr}from"./chunk-AHWWJ7AF.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{La as hr,Oa as _n,Qa as bc,Rb as Sc,Ta as yr,Ya as xc,cb as wr,db as Dt,eb as br,fb as et,gb as xr,hb as Sr,nb as Ir}from"./chunk-ZAPHYYGT.js";import{f as fr,g as Ve,h as yc}from"./chunk-KEUW6YLL.js";import{j as Rn,r as wc}from"./chunk-UEEB3UTU.js";import{a as gr,b as me,c as pr,d as mr,e as Mn}from"./chunk-VQRY4IDI.js";Pn();Ot();var jt="tool-set",Mo=["answer","code","full"],Ro={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Ic=.1;function Po(n){return{task:_o(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:_o(n.agentPrompt,600)}:{}}}var Eo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Do(n,e=Ic){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Fn(s.answer),o=Fn(s.code),i=Fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Oo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Ro.answer.includes(t))?"answer":e.every(t=>Ro.code.includes(t))?"code":"full"}function Lo(n,e){return Mo.indexOf(n)<Mo.indexOf(e)}function Fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function _o(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var No=!1;function Bo(n,e){let t=Lt(jt);if(t!=="off")return t==="active"&&!No&&(No=!0,e(`[decisions] seat "${jt}" is set to active, but only shadow is built: it records and changes nothing`)),Se(jt,Po(n),Eo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Do(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Oo(r);kr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Lo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Tc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Uo(n,e){let t=Tc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Un(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Pn();Ot();var Ho="session-continuity",jo={continues:tt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:tt("Does the new request refer to something stated earlier in the conversation?")};function Wo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Hn(n.message,1200),previousRequest:n.previousMessage?Hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function qo(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Xt}from"execa";import{spawn as kc}from"node:child_process";import{createHash as vc}from"node:crypto";import{createInterface as Ac}from"node:readline";var Ie=class extends Error{},$c=n=>kc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),jn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ac({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{Ba as $o,Da as Co,G as po,N as Ut,O as mo,V as Ht,X as fo,a as Qr,b as Xr,d as Dn,f as nt,ha as ho,i as ao,ia as yo,j as co,ja as wo,k as Bt,la as bo,ma as xo,n as Ft,na as So,oa as Io,q as uo,r as lo,ra as To,sa as ko,v as go,va as vo,wa as Ao}from"./chunk-D4QTZJ4G.js";import{b as Yr}from"./chunk-MEFPXHQJ.js";import{a as Bn}from"./chunk-W4YR2RO2.js";import{a as Jr}from"./chunk-VJVXEVZ7.js";import{b as Vr,d as Nn,e as to,f as Nt,i as no}from"./chunk-C5VFABFI.js";import{h as Kr,i as zr}from"./chunk-BE64IJWM.js";import{a as On,b as Zr}from"./chunk-J3SOEFRE.js";import{a as Ln,b as eo}from"./chunk-SIU6STB2.js";import{e as so,i as ro,j as oo,k as io}from"./chunk-X5C5W3E4.js";import{d as jr}from"./chunk-HPRLRD4P.js";import{a as Gr}from"./chunk-KN5LZ3JS.js";import{g as Wr,h as qr}from"./chunk-WD4HZAYI.js";import{c as vr,f as Ar}from"./chunk-XPKDQDBH.js";import{s as Tr,v as Lt,w as kr,y as Se,z as Pn}from"./chunk-NXOBCFUJ.js";import{a as tt,b as He,f as Ot}from"./chunk-72SZI2UW.js";import{a as Ue,b as Cn}from"./chunk-FCPTN6NF.js";import{a as $r,c as Cr}from"./chunk-MYVHVJWZ.js";import{e as je,h as Mr,i as _e}from"./chunk-QUFIUXMQ.js";import{a as Rr,b as _r,c as Pr,d as Er,l as Lr,q as Nr}from"./chunk-3AHYZLGE.js";import{a as Dr,b as Or}from"./chunk-LY4G7PCW.js";import{a as Br,b as Hr}from"./chunk-2HBEZV7L.js";import{a as Ur,b as En}from"./chunk-A7JSRDJL.js";import{c as Fr}from"./chunk-BERWTVG2.js";import{c as ur,d as lr}from"./chunk-AHWWJ7AF.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{La as hr,Oa as _n,Qa as bc,Rb as Sc,Ta as yr,Ya as xc,cb as wr,db as Dt,eb as br,fb as et,gb as xr,hb as Sr,nb as Ir}from"./chunk-ZAPHYYGT.js";import{f as fr,g as Ve,h as yc}from"./chunk-KEUW6YLL.js";import{j as Rn,r as wc}from"./chunk-UEEB3UTU.js";import{a as gr,b as me,c as pr,d as mr,e as Mn}from"./chunk-VQRY4IDI.js";Pn();Ot();var jt="tool-set",Mo=["answer","code","full"],Ro={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Ic=.1;function Po(n){return{task:_o(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:_o(n.agentPrompt,600)}:{}}}var Eo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Do(n,e=Ic){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Fn(s.answer),o=Fn(s.code),i=Fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Oo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Ro.answer.includes(t))?"answer":e.every(t=>Ro.code.includes(t))?"code":"full"}function Lo(n,e){return Mo.indexOf(n)<Mo.indexOf(e)}function Fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function _o(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var No=!1;function Bo(n,e){let t=Lt(jt);if(t!=="off")return t==="active"&&!No&&(No=!0,e(`[decisions] seat "${jt}" is set to active, but only shadow is built: it records and changes nothing`)),Se(jt,Po(n),Eo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Do(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Oo(r);kr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Lo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Tc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Uo(n,e){let t=Tc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Un(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Pn();Ot();var Ho="session-continuity",jo={continues:tt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:tt("Does the new request refer to something stated earlier in the conversation?")};function Wo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Hn(n.message,1200),previousRequest:n.previousMessage?Hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function qo(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Xt}from"execa";import{spawn as kc}from"node:child_process";import{createHash as vc}from"node:crypto";import{createInterface as Ac}from"node:readline";var Ie=class extends Error{},$c=n=>kc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),jn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ac({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Wn=class{constructor(e=$c,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=vc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([S],[E])=>S.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Ie("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let S=[...this.entries].find(([,E])=>!E.connection.busy);if(!S)throw new Ie("Codex warm process capacity reached");S[1].connection.close(),this.entries.delete(S[0])}try{r={fingerprint:s,connection:new jn(e,this.launchProcess)}}catch{throw new Ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let S={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...S,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return U.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await U,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(S){if(i.close(),!a&&!e.signal?.aborted)throw new Ie(S.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:S.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Go=new Wn;import{execFile as Qc}from"child_process";import{StringDecoder as at}from"string_decoder";import{mkdtempSync as ci,readFileSync as ui,rmSync as li}from"fs";import{join as Jt}from"path";import{tmpdir as gi}from"os";function Wt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function qt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Gt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Pe=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var Ko=null;function st(){return Ko}function Bm(n){Ko=n}function fe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Cc(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var We=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},zo=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=fe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Cc(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new We(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new We(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=fe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=fe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Mc}from"child_process";import{randomUUID as Rc}from"crypto";import{existsSync as _c,readFileSync as Pc}from"fs";import{resolve as Ec}from"path";function Dc(n){let e=Ec(n,"CLAUDE.md");if(!_c(e))return null;try{let t=Pc(e,"utf8");return Nr(t)}catch{return null}}var Oc=20*60*1e3,Lc=5e3,rt=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},ot=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Nc(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Jo=class{constructor(e={}){this.opts=e}spawn(e,t){return new qn(e,t,this.opts)}},qn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Mc(r,o,{cwd:t.workspace,env:_e(Nc({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Dc(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new Pe;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=Rc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??Oc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new rt(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new ot(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Lc);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
4
  `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};Mn();wc();Cn();import{resolve as Qo,join as Xo}from"path";var Bc=4e3;function Kt(n){try{let e=Xo(Qo(n.root),".agentx","db.sqlite"),t=Rn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ue(),r=n.input.command?n.input.command.slice(0,Bc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function Yc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,l)}};b.stdout?.on("data",v=>{L+=j.write(v);let x=L.split(`
32
32
  `);L=x.pop()||"";for(let B of x)z(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let $=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&z(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,x;return v.timedOut?x=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?x=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?x=ii():x=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(E?.message||"")?ii():E?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{S?.(),y?.release(A)}}async function du(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Te(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function cu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",S=s?`${s}
33
33
 
34
- ${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(z,$)=>Lr(z,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:z}=await import("./agent-OVSBIXDF.js"),$="",v,x,B,W;for await(let P of z(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")$+=P.text,r(P.text,$);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(x=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((x===void 0||B===void 0)&&v&&(x=Math.round(v*.7),B=v-x),{content:$||"Done.",tokensUsed:v,usage:x!==void 0||B!==void 0?{inputTokens:x||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-OVSBIXDF.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let z=N.tokensUsed;j=Math.round(z*.7),q=z-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var uu=1e3;async function lu(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),uu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function gu(n,e,t,s,r,o,i){let a=st();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Zt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof We,null}f&&Qn(e.agentId,n,e.model,s,"persistent");let h=Te(n,e,t),y="",A,S,E,U,b,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
34
+ ${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(z,$)=>Lr(z,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:z}=await import("./agent-AG2FLW4B.js"),$="",v,x,B,W;for await(let P of z(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")$+=P.text,r(P.text,$);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(x=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((x===void 0||B===void 0)&&v&&(x=Math.round(v*.7),B=v-x),{content:$||"Done.",tokensUsed:v,usage:x!==void 0||B!==void 0?{inputTokens:x||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-AG2FLW4B.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let z=N.tokensUsed;j=Math.round(z*.7),q=z-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var uu=1e3;async function lu(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),uu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function gu(n,e,t,s,r,o,i){let a=st();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Zt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof We,null}f&&Qn(e.agentId,n,e.model,s,"persistent");let h=Te(n,e,t),y="",A,S,E,U,b,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let z=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(z=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let x=v.raw.message?.content??[];for(let W of x)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let x=v.raw;if(x.is_error){let B=Z(typeof x.result=="string"?x.result:"claude error");A=B.error,S=B.errorKind}else typeof x.result=="string"&&x.result.length>0&&(y=x.result,M||N(x.result));typeof x.session_id=="string"&&(R=x.session_id),x.usage&&(E={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(b=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=Gt(x.modelUsage)||_}}}catch($){if(j)A="task cancelled by operator",S="cancelled";else if(z)if($ instanceof ot)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,S="interrupted";else if($ instanceof rt){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,S=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);A=v.error,S=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!A&&(A="task cancelled by operator",S="cancelled"),{content:j?"":y,error:A,errorKind:S,duration:Date.now()-c,usage:E,contextTokens:U,numTurns:b,billedModel:_,claudeSessionId:R}}function Ii(n){let e=me(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Vo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ri(t.args,n.taskId,n.agentId)}function pu(n){return me(n.autonomy)||!!n.personLimits}async function mu(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,c=a&&ei(a,n.tier)||e.personLimits&&oi(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${mr(a)}
@@ -186,4 +186,4 @@ ${Ce}`),m+=Ce.length}catch{}}}let uc=Tn.length>0?Tn.join(`
186
186
 
187
187
  Agent: ${C.content}`,meta:fm(ee,e.context)})},ce=>this.log(ce)),Hr(e.agentId,e.message,C.content,{channel:w,chatId:I,sender:xn},this.memoryStore).catch(()=>{}),Xi(e.agentId,e.message,C.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Be=e.context?.channel,Fe=Be&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Be}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,pe,Be,Fe),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${O()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Wt(g.message);return se={content:"",error:qt(m),errorKind:m.kind},se}finally{if(dr.stop(),cr&&de&&Ae)try{let g=se?.usage,m=To(Ae,de,{error:se?se.error||void 0:R.signal.aborted?Ne(R.signal).message:"run ended before completion",canceled:ko(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:An,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${de} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${de} (non-fatal): ${g?.message||g}`)}_s(se),Es(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?cm(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:vo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Xe,this.safe(e.agentId),t);ae(s)||tm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);sm(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Xe,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of ye(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),S=t-1-A;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Xe);if(!ae(e))return 0;let t=0;for(let s of ye(e)){let r=G(e,s),o;try{o=ye(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=ye(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(wt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=mm){let t=G(process.cwd(),Xe);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ye(t)){let i=G(t,o),a;try{a=ye(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{nm(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Xe,this.safe(e));if(!ae(s))return[];let r=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=ye(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(wt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Xe,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(wt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Bt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Bn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||nt(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){im.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Zt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:wr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{nt(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Im(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
188
188
  `)}export{Go as a,Bm as b,zo as c,Dc as d,Jo as e,Kt as f,Zm as g,nf as h,sf as i,cf as j,Zt as k,nu as l,xi as m,au as n,du as o,cu as p,Ti as q,en as r,Mi as s,Uf as t,tn as u,Eu as v,Gf as w,Kf as x,Jf as y,sn as z,Yf as A,ss as B,V as C,Yi as D,Yu as E,tl as F,ea as G,ph as H,ta as I,oa as J,$h as K,Ch as L,la as M,Mh as N,ga as O,dn as P,Bh as Q,Fh as R,gt as S,mg as T,fg as U,hg as V,yg as W,wg as X,fs as Y,gn as Z,fy as _,mn as $,pn as aa,id as ba,mt as ca,ad as da,Iy as ea,Ty as fa,ky as ga,vy as ha,Ay as ia,$y as ja,Cy as ka,Xg as la,bd as ma,Qe as na,am as oa,dm as pa,pb as qa,mb as ra,cm as sa,pm as ta,fm as ua,hm as va,wm as wa,Ms as xa,Ud as ya,Hd as za,xm as Aa,jd as Ba,Wd as Ca,Im as Da};
189
- //# sourceMappingURL=chunk-BY7QINNM.js.map
189
+ //# sourceMappingURL=chunk-IJXCGKAB.js.map