agentix-cli 0.80.0 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-2UCGXCX3.js → App-KVH5POXZ.js} +2 -2
- package/dist/{ChatApp-IRPSBYC7.js → ChatApp-LD4TXJWP.js} +2 -2
- package/dist/{agent-UPTK3HFR.js → agent-FUMJM6OW.js} +2 -2
- package/dist/{board-dashboard-GAUAYKWV.js → board-dashboard-OS5J3F73.js} +7 -4
- package/dist/board-dashboard-OS5J3F73.js.map +1 -0
- package/dist/{chunk-PT5Z5WW4.js → chunk-3UN6CXRL.js} +2 -2
- package/dist/{chunk-445P5QPS.js → chunk-42Y3BXXS.js} +1 -1
- package/dist/{chunk-445P5QPS.js.map → chunk-42Y3BXXS.js.map} +1 -1
- package/dist/{chunk-6TLQ4I32.js → chunk-6JJ3GODZ.js} +23 -23
- package/dist/{chunk-6TLQ4I32.js.map → chunk-6JJ3GODZ.js.map} +1 -1
- package/dist/{chunk-KAFUQILA.js → chunk-7IGSJGXI.js} +2 -2
- package/dist/{chunk-ECEDX6C6.js → chunk-AF46YOLU.js} +121 -121
- package/dist/chunk-AF46YOLU.js.map +1 -0
- package/dist/{chunk-NMFXY3QU.js → chunk-API4IZZG.js} +2 -2
- package/dist/{chunk-36TJTWG3.js → chunk-BEHC3X42.js} +59 -59
- package/dist/chunk-BEHC3X42.js.map +1 -0
- package/dist/{chunk-3GYCFRBK.js → chunk-BJPIRNP6.js} +2 -2
- package/dist/{chunk-Z522XZBL.js → chunk-BVZFYBBP.js} +2 -2
- package/dist/{chunk-AIHWGU4P.js → chunk-H7253EHW.js} +2 -2
- package/dist/{chunk-I2Z6D3MI.js → chunk-MOQNLS5Z.js} +2 -2
- package/dist/{chunk-7EIUNFDF.js → chunk-MYRSNJJ4.js} +2 -2
- package/dist/{chunk-KBSBMOOL.js → chunk-NOAAK2XI.js} +48 -48
- package/dist/chunk-NOAAK2XI.js.map +1 -0
- package/dist/{chunk-2YJ2ZIYC.js → chunk-PE55MMLK.js} +2 -2
- package/dist/{chunk-PXIGWFIQ.js → chunk-R42S57G6.js} +2 -2
- package/dist/{chunk-BIJB7CNG.js → chunk-TEFMZY6B.js} +2 -2
- package/dist/{chunk-PHFOYJUB.js → chunk-UB63NQQL.js} +2 -2
- package/dist/{chunk-AFSM3IY3.js → chunk-UR3ZIDMA.js} +2 -2
- package/dist/{chunk-4NUF3SXN.js → chunk-UXSYVMPK.js} +2 -2
- package/dist/{chunk-Z6G26FWC.js → chunk-XESESMKN.js} +52 -52
- package/dist/chunk-XESESMKN.js.map +1 -0
- package/dist/{chunk-O67KV3DX.js → chunk-YCI3KUYF.js} +2 -2
- package/dist/{chunk-D3FDPA74.js → chunk-Z3XUGXPD.js} +2 -2
- package/dist/{chunk-BBI3HG77.js → chunk-ZR3NZLJL.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-TJ5YZOEE.js +2 -0
- package/dist/{config-XPFCUOQT.js → config-4WZ7Y34V.js} +2 -2
- package/dist/config-mutator-5Z7EEB5N.js +2 -0
- package/dist/{doctor-XLLNQRRT.js → doctor-7K3NRBNN.js} +2 -2
- package/dist/{facts-YY2364CP.js → facts-U7BUYRXN.js} +2 -2
- package/dist/index.d.ts +11 -3
- package/dist/index.js +1 -1
- package/dist/program-KMQNX6YK.js +2 -0
- package/dist/{promote-YUZL3ZU2.js → promote-NDC3X54P.js} +2 -2
- package/dist/{query-3XH7I6WX.js → query-F7BD3JPE.js} +2 -2
- package/dist/{registry-5OD2IN5G.js → registry-5NBHBVY3.js} +2 -2
- package/dist/{request-planner-RNXA2QAH.js → request-planner-H74KHFGJ.js} +2 -2
- package/dist/{review-candidates-THKWXS7S.js → review-candidates-IPJWEXR2.js} +2 -2
- package/dist/{routing-X45VX723.js → routing-3RSG7SKW.js} +2 -2
- package/dist/schedule-tool-7NYAK43U.js +2 -0
- package/dist/scheduler-24O7PADJ.js +2 -0
- package/dist/{seat-LQ47SSNN.js → seat-TOM2WHQR.js} +2 -2
- package/dist/{select-PRQP2B6G.js → select-BUWOD47K.js} +2 -2
- package/dist/{set-enabled-E2ML2E33.js → set-enabled-XWSFTICB.js} +2 -2
- package/dist/tool-GUINJ2BQ.js +4 -0
- package/dist/tool-GUINJ2BQ.js.map +1 -0
- package/dist/{tool-4WPUUUE4.js → tool-VOA4HSVP.js} +2 -2
- package/dist/wiki-VFME4T2H.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-GAUAYKWV.js.map +0 -1
- package/dist/chunk-36TJTWG3.js.map +0 -1
- package/dist/chunk-ECEDX6C6.js.map +0 -1
- package/dist/chunk-KBSBMOOL.js.map +0 -1
- package/dist/chunk-Z6G26FWC.js.map +0 -1
- package/dist/client-ABDGDO7S.js +0 -2
- package/dist/config-mutator-WYHQV2XF.js +0 -2
- package/dist/program-KZOBDSXQ.js +0 -2
- package/dist/schedule-tool-ZTL6UZCC.js +0 -2
- package/dist/scheduler-VH7IJ4VA.js +0 -2
- package/dist/tool-67JK7SK6.js +0 -4
- package/dist/tool-67JK7SK6.js.map +0 -1
- package/dist/wiki-AS5YHSR7.js +0 -2
- /package/dist/{App-2UCGXCX3.js.map → App-KVH5POXZ.js.map} +0 -0
- /package/dist/{ChatApp-IRPSBYC7.js.map → ChatApp-LD4TXJWP.js.map} +0 -0
- /package/dist/{agent-UPTK3HFR.js.map → agent-FUMJM6OW.js.map} +0 -0
- /package/dist/{chunk-PT5Z5WW4.js.map → chunk-3UN6CXRL.js.map} +0 -0
- /package/dist/{chunk-KAFUQILA.js.map → chunk-7IGSJGXI.js.map} +0 -0
- /package/dist/{chunk-NMFXY3QU.js.map → chunk-API4IZZG.js.map} +0 -0
- /package/dist/{chunk-3GYCFRBK.js.map → chunk-BJPIRNP6.js.map} +0 -0
- /package/dist/{chunk-Z522XZBL.js.map → chunk-BVZFYBBP.js.map} +0 -0
- /package/dist/{chunk-AIHWGU4P.js.map → chunk-H7253EHW.js.map} +0 -0
- /package/dist/{chunk-I2Z6D3MI.js.map → chunk-MOQNLS5Z.js.map} +0 -0
- /package/dist/{chunk-7EIUNFDF.js.map → chunk-MYRSNJJ4.js.map} +0 -0
- /package/dist/{chunk-2YJ2ZIYC.js.map → chunk-PE55MMLK.js.map} +0 -0
- /package/dist/{chunk-PXIGWFIQ.js.map → chunk-R42S57G6.js.map} +0 -0
- /package/dist/{chunk-BIJB7CNG.js.map → chunk-TEFMZY6B.js.map} +0 -0
- /package/dist/{chunk-PHFOYJUB.js.map → chunk-UB63NQQL.js.map} +0 -0
- /package/dist/{chunk-AFSM3IY3.js.map → chunk-UR3ZIDMA.js.map} +0 -0
- /package/dist/{chunk-4NUF3SXN.js.map → chunk-UXSYVMPK.js.map} +0 -0
- /package/dist/{chunk-O67KV3DX.js.map → chunk-YCI3KUYF.js.map} +0 -0
- /package/dist/{chunk-D3FDPA74.js.map → chunk-Z3XUGXPD.js.map} +0 -0
- /package/dist/{chunk-BBI3HG77.js.map → chunk-ZR3NZLJL.js.map} +0 -0
- /package/dist/{client-ABDGDO7S.js.map → client-TJ5YZOEE.js.map} +0 -0
- /package/dist/{config-XPFCUOQT.js.map → config-4WZ7Y34V.js.map} +0 -0
- /package/dist/{config-mutator-WYHQV2XF.js.map → config-mutator-5Z7EEB5N.js.map} +0 -0
- /package/dist/{doctor-XLLNQRRT.js.map → doctor-7K3NRBNN.js.map} +0 -0
- /package/dist/{facts-YY2364CP.js.map → facts-U7BUYRXN.js.map} +0 -0
- /package/dist/{program-KZOBDSXQ.js.map → program-KMQNX6YK.js.map} +0 -0
- /package/dist/{promote-YUZL3ZU2.js.map → promote-NDC3X54P.js.map} +0 -0
- /package/dist/{query-3XH7I6WX.js.map → query-F7BD3JPE.js.map} +0 -0
- /package/dist/{registry-5OD2IN5G.js.map → registry-5NBHBVY3.js.map} +0 -0
- /package/dist/{request-planner-RNXA2QAH.js.map → request-planner-H74KHFGJ.js.map} +0 -0
- /package/dist/{review-candidates-THKWXS7S.js.map → review-candidates-IPJWEXR2.js.map} +0 -0
- /package/dist/{routing-X45VX723.js.map → routing-3RSG7SKW.js.map} +0 -0
- /package/dist/{schedule-tool-ZTL6UZCC.js.map → schedule-tool-7NYAK43U.js.map} +0 -0
- /package/dist/{scheduler-VH7IJ4VA.js.map → scheduler-24O7PADJ.js.map} +0 -0
- /package/dist/{seat-LQ47SSNN.js.map → seat-TOM2WHQR.js.map} +0 -0
- /package/dist/{select-PRQP2B6G.js.map → select-BUWOD47K.js.map} +0 -0
- /package/dist/{set-enabled-E2ML2E33.js.map → set-enabled-XWSFTICB.js.map} +0 -0
- /package/dist/{tool-4WPUUUE4.js.map → tool-VOA4HSVP.js.map} +0 -0
- /package/dist/{wiki-AS5YHSR7.js.map → wiki-VFME4T2H.js.map} +0 -0
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Ft=class{constructor(e=Li,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}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 n=Oi("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([y],[v])=>y.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ce("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let i=!!r;if(!r){if(this.entries.size>=this.capacity){let y=[...this.entries].find(([,v])=>!v.connection.busy);if(!y)throw new ce("Codex warm process capacity reached");y[1].connection.close(),this.entries.delete(y[0])}try{r={fingerprint:n,connection:new Lt(e,this.launchProcess)}}catch{throw new ce("Could not start Codex app-server")}this.entries.set(e.key,r)}let o=r.connection;o.busy=!0,clearTimeout(o.idle);let a=!1,c="",d,l,u,g=!1,m=()=>o.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let f=setTimeout(()=>o.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>o.close(new Error("Codex initialization timed out")),15e3);try{i||(await o.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),o.write({method:"initialized",params:{}})),o.threadId&&o.threadId!==e.resume&&(await o.rpc("thread/unsubscribe",{threadId:o.threadId}),o.threadId=void 0);let y={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await o.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...y,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,o.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:i,startupMs:Date.now()-t,model:e.model});let I=new Promise((O,D)=>{o.failTurn=D,o.notify=(C,_)=>{if(_?.threadId!==l)return;let L=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...L?{item:{...L,type:E[L.type]||L.type}}:{}}),C==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:i})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let F=_.tokenUsage.last,H=F.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?O():D(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await o.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(y){if(o.close(),!a&&!e.signal?.aborted)throw new ce(y.message);return{content:c,codexSessionId:l,usage:u,error:y.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(f),e.signal?.removeEventListener("abort",m),o.notify=void 0,o.failTurn=void 0,o.busy=!1,o.dead?this.entries.get(e.key)?.connection===o&&this.entries.delete(e.key):(o.idle=setTimeout(()=>{o.close(),this.entries.delete(e.key)},this.idleMs),o.idle.unref())}}},Cs=new Ft;import{execFile as Zi}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as js,readFileSync as Us,rmSync as Bs}from"fs";import{join as ct}from"path";import{tmpdir as Ws}from"os";function it(s){let e=(s||"").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]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,i=typeof r?.type=="string"?r.type:void 0,o=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 o&&/out of extra usage/i.test(o)?{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}:o&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(o)?{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}:o&&/context|prompt is too long|too many tokens|maximum context length/i.test(o)?{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}:i==="authentication_error"||o&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(o)?{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}:i==="permission_error"||c===403?{kind:"permission",retryable:!1,message:o||"The API key doesn't have permission for this request.",raw:e}:i==="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}:i==="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}:i==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:o||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:o||`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 ot(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var As=null;function at(){return As}function Ac(s){As=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function Fi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},$s=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 n=Oe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=Fi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${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 Te(`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 Te(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let o=this.cfg.factory.spawn(e,t);return this.handles.set(n,o),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),o}release(e,t={}){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Oe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let i of this.handles.values()){if(i.state()!=="idle"||e.scope==="agent"&&i.key.agentId!==e.agentId)continue;let o=i.snapshot().lastTurnAt;o<n&&(n=o,t=i)}if(!t)return!1;let r=Oe(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,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let i=e-r.lastTurnAt;if(i>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(i/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(i>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(i/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let o=this.handleWorkspace.get(t);if(o){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,o)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Hi}from"child_process";import{existsSync as ji,readFileSync as Ui}from"fs";import{resolve as Bi}from"path";function Wi(s){let e=Bi(s,"CLAUDE.md");if(!ji(e))return null;try{let t=Ui(e,"utf8");return Qn(t)}catch{return null}}var qi=20*60*1e3,Ki=5e3,Ne=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Le=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Gi(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var Ms=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ht(e,t,this.opts)}},Ht=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",i=this.buildArgs(t),o=n.log??(()=>{});this.child=Hi(r,i,{cwd:t.workspace,env:De(Gi({...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:Wi(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=>o(`[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=>{o(`[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();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),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 i=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:i};let o=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(o+`
|
|
3
|
-
`);let a=e.deadlineMs??
|
|
4
|
-
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),t(null)},e),i=o=>{n||(n=!0,clearTimeout(r),t(o))};this.waiters.push(i)})}onResultEvent(e){let t=e.usage??{},n=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:n,state:"idle"}}};Rt();import{resolve as Rs,join as Ps}from"path";Mt();var
|
|
1
|
+
import{B as xs,D as Ts,a as ts,b as ns,d as rs,f as rt,l as fs,s as ys,u as ws}from"./chunk-6JJ3GODZ.js";import{f as bs}from"./chunk-API4IZZG.js";import{a as es}from"./chunk-WP6KLXTP.js";import{a as _t}from"./chunk-N6EWZGIX.js";import{b as ss}from"./chunk-DP7RTNDM.js";import{a as ms}from"./chunk-W4YR2RO2.js";import{b as os,c as Ot,d as cs,e as ds,h as us}from"./chunk-R42S57G6.js";import{a as Zn}from"./chunk-H7253EHW.js";import{a as Et,b as is}from"./chunk-J3SOEFRE.js";import{a as Dt,b as as}from"./chunk-SIU6STB2.js";import{e as ls,i as gs,j as ps,k as hs}from"./chunk-X5C5W3E4.js";import{a as Un}from"./chunk-BJPIRNP6.js";import{a as Bn,c as Wn}from"./chunk-MYVHVJWZ.js";import{a as qn,b as Kn,c as Gn,d as Jn,f as Qn}from"./chunk-DWADWDMU.js";import{a as zn,b as Xn}from"./chunk-23A5K5UW.js";import{g as Yn,h as Vn}from"./chunk-UB63NQQL.js";import{a as st,c as De}from"./chunk-2GIDVZ4H.js";import{q as Fn,t as Hn,v as xe,w as jn}from"./chunk-PE55MMLK.js";import{a as Ee,b as nt,f as Pt}from"./chunk-72SZI2UW.js";import{a as we,b as Mt}from"./chunk-FCPTN6NF.js";import{c as _n,d as En}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{I as Li,d as Dn,e as ae,f as On,g as Nn,h as Rt,y as Ln}from"./chunk-42Y3BXXS.js";jn();Pt();var Is="session-continuity",ks={continues:Ee("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:Ee("Does the new request refer to something stated earlier in the conversation?")};function Ss(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Nt(s.message,1200),previousRequest:s.previousMessage?Nt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Nt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function vs(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Nt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ut}from"execa";import{spawn as Fi}from"node:child_process";import{createHash as Hi}from"node:crypto";import{createInterface as ji}from"node:readline";var ce=class extends Error{},Ui=s=>Fi("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Lt=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(),ji({input:this.child.stdout}).on("line",r=>{let i;try{i=JSON.parse(r)}catch{return}if(i.method&&i.id!==void 0)this.write({id:i.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(i.id!==void 0){let o=this.pending.get(i.id);if(!o)return;this.pending.delete(i.id),i.error?o.reject(new Error(i.error.message||"Codex RPC failed")):o.resolve(i.result)}else i.method&&this.notify?.(i.method,i.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
|
+
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Ft=class{constructor(e=Ui,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}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 n=Hi("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([y],[v])=>y.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ce("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let i=!!r;if(!r){if(this.entries.size>=this.capacity){let y=[...this.entries].find(([,v])=>!v.connection.busy);if(!y)throw new ce("Codex warm process capacity reached");y[1].connection.close(),this.entries.delete(y[0])}try{r={fingerprint:n,connection:new Lt(e,this.launchProcess)}}catch{throw new ce("Could not start Codex app-server")}this.entries.set(e.key,r)}let o=r.connection;o.busy=!0,clearTimeout(o.idle);let a=!1,c="",d,l,u,g=!1,m=()=>o.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let f=setTimeout(()=>o.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>o.close(new Error("Codex initialization timed out")),15e3);try{i||(await o.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),o.write({method:"initialized",params:{}})),o.threadId&&o.threadId!==e.resume&&(await o.rpc("thread/unsubscribe",{threadId:o.threadId}),o.threadId=void 0);let y={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await o.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...y,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,o.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:i,startupMs:Date.now()-t,model:e.model});let I=new Promise((O,D)=>{o.failTurn=D,o.notify=(C,_)=>{if(_?.threadId!==l)return;let L=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...L?{item:{...L,type:E[L.type]||L.type}}:{}}),C==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:i})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let F=_.tokenUsage.last,H=F.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?O():D(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await o.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(y){if(o.close(),!a&&!e.signal?.aborted)throw new ce(y.message);return{content:c,codexSessionId:l,usage:u,error:y.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(f),e.signal?.removeEventListener("abort",m),o.notify=void 0,o.failTurn=void 0,o.busy=!1,o.dead?this.entries.get(e.key)?.connection===o&&this.entries.delete(e.key):(o.idle=setTimeout(()=>{o.close(),this.entries.delete(e.key)},this.idleMs),o.idle.unref())}}},Cs=new Ft;import{execFile as so}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as js,readFileSync as Us,rmSync as Bs}from"fs";import{join as ct}from"path";import{tmpdir as Ws}from"os";function it(s){let e=(s||"").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]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,i=typeof r?.type=="string"?r.type:void 0,o=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 o&&/out of extra usage/i.test(o)?{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}:o&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(o)?{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}:o&&/context|prompt is too long|too many tokens|maximum context length/i.test(o)?{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}:i==="authentication_error"||o&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(o)?{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}:i==="permission_error"||c===403?{kind:"permission",retryable:!1,message:o||"The API key doesn't have permission for this request.",raw:e}:i==="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}:i==="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}:i==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:o||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:o||`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 ot(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var As=null;function at(){return As}function Pc(s){As=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function Bi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},$s=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 n=Oe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=Bi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${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 Te(`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 Te(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let o=this.cfg.factory.spawn(e,t);return this.handles.set(n,o),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),o}release(e,t={}){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Oe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let i of this.handles.values()){if(i.state()!=="idle"||e.scope==="agent"&&i.key.agentId!==e.agentId)continue;let o=i.snapshot().lastTurnAt;o<n&&(n=o,t=i)}if(!t)return!1;let r=Oe(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,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let i=e-r.lastTurnAt;if(i>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(i/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(i>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(i/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let o=this.handleWorkspace.get(t);if(o){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,o)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Wi}from"child_process";import{existsSync as qi,readFileSync as Ki}from"fs";import{resolve as Gi}from"path";function Ji(s){let e=Gi(s,"CLAUDE.md");if(!qi(e))return null;try{let t=Ki(e,"utf8");return Qn(t)}catch{return null}}var Qi=20*60*1e3,zi=5e3,Ne=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Le=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Xi(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var Ms=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ht(e,t,this.opts)}},Ht=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",i=this.buildArgs(t),o=n.log??(()=>{});this.child=Wi(r,i,{cwd:t.workspace,env:De(Xi({...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:Ji(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=>o(`[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=>{o(`[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();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),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 i=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:i};let o=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(o+`
|
|
3
|
+
`);let a=e.deadlineMs??Qi,c=i+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ne(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Le(this.killReason);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{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 n=await new Promise(r=>{let i=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},zi);this.child.once("exit",()=>{clearTimeout(i),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];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),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
|
+
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),t(null)},e),i=o=>{n||(n=!0,clearTimeout(r),t(o))};this.waiters.push(i)})}onResultEvent(e){let t=e.usage??{},n=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:n,state:"idle"}}};Rt();import{resolve as Rs,join as Ps}from"path";Mt();var Yi=4e3;function _s(s){try{let e=Ps(Rs(s.root),".agentx","db.sqlite"),t=_t({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=we(),r=s.input.command?s.input.command.slice(0,Yi):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
5
5
|
(id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
|
|
6
6
|
verdict, effective_action, mode, severity, approver, ms)
|
|
7
7
|
VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
|
|
8
8
|
@verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:n,ts:Date.now(),agent_id:s.input.agentId??null,task_id:s.taskId??null,tool:s.input.tool,command:r,resolved_target:s.verdict.resolvedTarget,matched_rule:s.verdict.ruleId,verdict:s.verdict.action,effective_action:s.verdict.effectiveAction,mode:s.mode,severity:s.verdict.severity,approver:s.approver??null,ms:s.ms??null}),n}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
|
|
9
|
-
`),null}}function
|
|
9
|
+
`),null}}function Wc(s){let e=Ps(Rs(s.root),".agentx","db.sqlite"),t=_t({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let i="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(i).all(r)}Rt();var Vi=50,Zi=6*60*60*1e3,jt=null,Ie=new Map;function Jc(s){jt=s===null?null:String(s)}function eo(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function Ds(s,e,t){if(!ae(s))return{args:[]};if(!jt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:eo(jt,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function Os(s,e){return!ae(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function to(s){for(let[e,t]of Ie)s-t.at>Zi&&Ie.delete(e)}function no(s,e){let t=Date.now();to(t);let n=Ie.get(s)??{at:t,blocks:[]};n.blocks.length<Vi&&n.blocks.push(e),n.at=t,Ie.set(s,n)}function Ns(s){if(!s)return[];let e=Ie.get(s);return Ie.delete(s),e?.blocks??[]}function Es(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Qc(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let i=Dn.safeParse(e.level),o=i.success?On(i.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(o.allowed)return{stdout:"",blocked:null};let a=i.success?i.data:"report",c=o.ruleId??"autonomy",d=o.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:c,reason:d},u={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return _s({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:u,mode:"enforce",taskId:e.taskId??null}),e.taskId&&no(e.taskId,l),{stdout:Es(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(i){return{stdout:Es(`[agentx-autonomy] Guard error (fail-closed): ${i?.message??i}`),blocked:null}}}var ro=5e3;function Q(s){let e=it(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
10
10
|
`)}return{error:ot(e),errorKind:e.kind}}function qs(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function dt(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function Ls(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function ue(s,e,t){let n=[];if(e.context&&!t){let r=e.context,i=["","[Environment]"],o=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&i.push(`Channel: ${r.channel}`),r.group&&i.push(`Group: ${r.group}`),r.sender&&i.push(`Message from: ${r.sender}`),r.myHandle&&i.push(`Your handle on this channel: ${r.myHandle}`),o&&(i.push(""),i.push("[IMPORTANT: You are responding to a GitLab comment/event]"),i.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),i.push("- Lead with the result or action, not a narration of what you plan to do"),i.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),i.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),i.push("- Do NOT try to delegate to other agents \u2014 reply directly"),i.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){i.push(""),i.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",l=c.role?` \u2014 ${c.role}`:"";i.push(`\u2022 ${c.name}${d}${l}`)}i.push(""),i.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(i.join(`
|
|
11
11
|
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
12
12
|
`)}function Ks(s,e,t,n,r,i,o=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let c=r||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),i&&i.trim().length>0&&a.push("--append-system-prompt",i),a.push(...o),a}function Ut(s,e){return!e||e.trim().length===0?s:`[System]
|
|
13
13
|
${e.trim()}
|
|
14
14
|
|
|
15
15
|
[User]
|
|
16
|
-
${s}`}function
|
|
17
|
-
`))if(o.trim())try{let a=JSON.parse(o);t=Wt(a)||t,n=Qs(a)||n,r=qt(a)||r,i=zs(a)||i}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:i}}function zs(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return Hs(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return Hs(e)}}}function Hs(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function
|
|
18
|
-
`)}function
|
|
16
|
+
${s}`}function io(s,e,t,n,r){let i=["run","--format","json","--thinking"],o=t||s.model;return o&&i.push("--model",o),r&&i.push("--session",r),s.permissionMode==="bypassPermissions"&&i.push("--auto"),i.push(Ut(e,n)),i}function oo(s){if(!s||typeof s!="object"||s.type!=="error")return;let e=s.error?.message??s.error??s.message??s.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function Fs(s){return JSON.stringify(s)}function Gs(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Fs(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(Fs).join(",")}]`]}function Js(s,e,t,n,r,i,o){let a=o?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Gs()),o||a.push("--color","never");let c=n||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):o||a.push("--sandbox","workspace-write"),(t||o||i)&&a.push("--json"),i&&a.push("--output-last-message",i),o&&a.push(o),a.push(Ut(e,r)),a}function lt(s,e){let t=st(s.workspace),n=t.HOME||process.env.HOME,r=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(i=>i.split(":")).filter(Boolean))).join(":"),Bt(t,e)}function Bt(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(s.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function ao(s,e){let t=lt(s,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...n.mcp||{}};for(let[o,a]of Object.entries(s.mcp||{}))r[o]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let i=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,i,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:r}),t}function co(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function de(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Wt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:de(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:de(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:de(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:de(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Wt(n,e+1);if(r)return r}}function Qs(s){if(!(!s||typeof s!="object"))return typeof s.model=="string"&&s.model||typeof s.msg?.model=="string"&&s.msg.model||typeof s.message?.model=="string"&&s.message.model||typeof s.response?.model=="string"&&s.response.model||void 0}function qt(s,e=0){if(!(!s||typeof s!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=s[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[s.msg,s.message,s.response,s.result,s.item]){let n=qt(t,e+1);if(n)return n}}}function uo(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,i;for(let o of e.split(`
|
|
17
|
+
`))if(o.trim())try{let a=JSON.parse(o);t=Wt(a)||t,n=Qs(a)||n,r=qt(a)||r,i=zs(a)||i}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:i}}function zs(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return Hs(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return Hs(e)}}}function Hs(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function lo(s){let e=s.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function Kt(s,e,t,n,r){let i=lo(e),o=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${s} via=${r} model=${o} perm=${i.summary}${a}
|
|
18
|
+
`)}function go(s){try{let e=JSON.parse(s);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function po(s){try{let e=JSON.parse(s),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0}}catch{return{text:s}}}async function Xs(s,e,t,n,r){let i=Date.now(),o=ue(s,e,t),a=Vs(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-i};let c=Ks(s,o,!1,n,e.model,e.systemPromptAppend,a.args);if(Kt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-i};let d;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:g,exitCode:m,killed:f}=await new Promise(v=>{let I=De(Bt(st(s.workspace),e),s.billing),O=!1,D=so("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...I,HOME:I.HOME||"/home/"+(I.USER||"user")}},(C,_,L)=>{v({stdout:_||"",stderr:L||"",exitCode:C?C.code??1:0,killed:O})});if(D.stdin?.end(),r){let C=()=>{O=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.killed||D.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?C():r.addEventListener("abort",C,{once:!0})}});if(f)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-i};if(!u&&m!==0){let v,I=Date.now()-i;return m===143&&I<l-ro?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(I/1e3)}s, before its ${Math.round(l/6e4)}m time limit`,errorKind:"interrupted",duration:I}:(m===143?v=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?v=qs():v=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...Q(v),duration:Date.now()-i})}let T=go(u);if(T)return{content:"",...Q(T),duration:Date.now()-i};let y=po(u);return{content:y.text,duration:Date.now()-i,claudeSessionId:y.sessionId,usage:y.usage,numTurns:y.numTurns,billedModel:y.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-i}}}async function Ys(s,e,t,n,r,i,o){let a=Date.now();if(o?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ue(s,e,n),d=Vs(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let l=Ks(s,c,!0,r,e.model,e.systemPromptAppend,d.args);Kt(e.agentId,s,e.model,r,"stream");let u="",g,m,f,T,y,v;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),O=De(Bt(st(s.workspace),e),s.billing),D=ut("claude",l,{cwd:s.workspace,timeout:I,reject:!1,env:O,extendEnv:!1,buffer:!1,stdin:"ignore"}),C=()=>{},_=new Promise(A=>{C=A}),L=!1,E;if(o){let A=()=>{L=!0,E=o.reason?.message||(typeof o.reason=="string"?o.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.kill("SIGKILL")}catch{}},3e3).unref?.()};o.aborted?A():o.addEventListener("abort",A,{once:!0})}let F="",H=new Fe("utf8");D.stdout&&D.stdout.on("data",A=>{F+=H.write(A);let k=F.split(`
|
|
19
19
|
`);F=k.pop()||"";for(let b of k)if(b.trim())try{let x=JSON.parse(b);if(i)try{i(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let N=x.message.usage,R=(N.input_tokens||0)+(N.cache_read_input_tokens||0)+(N.cache_creation_input_tokens||0);R>0&&(T=R)}if(x.type==="assistant"&&x.message?.content){for(let N of x.message.content)if(N.type==="text"&&N.text){let R=N.text.slice(u.length);R&&(u=N.text,t(R,u))}}if(x.type==="content_block_delta"&&x.delta?.text&&(u+=x.delta.text,t(x.delta.text,u)),x.type==="result"&&C(),x.type==="result"&&x.result){if(x.is_error&&typeof x.result=="string")v=x.result;else{let N=(typeof x.result=="string",x.result);if(typeof N=="string"&&N.length>u.length){let R=N.slice(u.length);u=N,R&&t(R,u)}}x.usage&&(m={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.model=="string"&&(g=x.model),typeof x.session_id=="string"&&(f=x.session_id),typeof x.num_turns=="number"&&(y=x.num_turns)}x.type==="system"&&x.subtype==="init"&&(typeof x.model=="string"&&(g=x.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${x.apiKeySource} version=${x.claude_code_version} model=${x.model} permMode=${x.permissionMode}
|
|
20
20
|
`))}catch{b.trim()&&!b.startsWith("{")&&(u+=b+`
|
|
21
21
|
`,t(b+`
|
|
22
|
-
`,u))}});let j=await
|
|
23
|
-
`);I=b.pop()||"";for(let x of b)if(x.trim())try{let N=JSON.parse(x);if(i)try{i(N)}catch{}g=Wt(N)||g,m=Qs(N)||m,f=qt(N)||f,T=zs(N)||T;let R=
|
|
22
|
+
`,u))}});let j=await xo(D,_),B=H.end();if(B&&(F+=B),L)return{content:"",error:E||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&j.stdout&&(u=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!u){let A=typeof j.stderr=="string"?j.stderr:"",k=j,b;return k.timedOut?b=`Claude Code timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:k.signal?b=A.trim()||`Claude Code killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn claude/i.test((k.shortMessage||"")+" "+A)?b=qs():b=A.trim()||`Claude Code exited with code ${k.exitCode??"unknown"}`,{content:"",...Q(b),duration:Date.now()-a}}return v?{content:"",...Q(v),duration:Date.now()-a,usage:m,contextTokens:T,numTurns:y,billedModel:g,claudeSessionId:f}:{content:u,duration:Date.now()-a,usage:m,contextTokens:T,numTurns:y,billedModel:g,claudeSessionId:f}}catch(I){return{content:u||"",...Q(I.message),duration:Date.now()-a,usage:m,contextTokens:T,numTurns:y,billedModel:g,claudeSessionId:f}}}async function ho(s,e,t,n){let r=Date.now(),i=ue(s,e,t),o=js(ct(Ws(),"agentx-codex-")),a=ct(o,"last-message.txt"),c=Js(s,i,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await ut("codex",c,{cwd:s.workspace,timeout:d,reject:!1,env:lt(s,e),extendEnv:!1,stdin:"ignore"}),u=uo(l.stdout);if(l.exitCode!==0||u.apiError){let m=l,f;return m.timedOut?f=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?f=u.apiError:m.signal?f=l.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+l.stderr)?f=dt():f=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...Q(f),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let g="";try{g=Us(a,"utf8").trim()}catch{}return g||(g=l.stdout.trim()),{content:g,duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}catch(d){let l=/ENOENT|spawn codex/i.test(d?.message||"")?dt():d?.message;return{content:"",...Q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{Bs(o,{recursive:!0,force:!0})}}async function mo(s,e,t,n,r,i){let o=Date.now(),a=ue(s,e,n),c=js(ct(Ws(),"agentx-codex-")),d=ct(c,"last-message.txt"),l=Js(s,a,!0,e.model,e.systemPromptAppend,d,r),u="",g,m,f,T;try{let y=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),v=ut("codex",l,{cwd:s.workspace,timeout:y,reject:!1,env:lt(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(i)try{i({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let I="",O="",D=!1,C=new Fe("utf8"),_=new Fe("utf8"),L=Math.min(y,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),E,F=()=>{E&&clearTimeout(E),E=setTimeout(()=>{D=!0,v.kill("SIGTERM",{forceKillAfterTimeout:5e3})},L)};F(),v.stderr?.on("data",k=>{F(),O+=_.write(k),O.length>16e3&&(O=O.slice(-16e3))}),v.stdout?.on("data",k=>{F(),I+=C.write(k);let b=I.split(`
|
|
23
|
+
`);I=b.pop()||"";for(let x of b)if(x.trim())try{let N=JSON.parse(x);if(i)try{i(N)}catch{}g=Wt(N)||g,m=Qs(N)||m,f=qt(N)||f,T=zs(N)||T;let R=co(N);if(R&&R!==u){let w=R.startsWith(u)?R.slice(u.length):R;u=R.startsWith(u)?R:u+R,w&&t(w,u)}}catch{u+=x+`
|
|
24
24
|
`,t(x+`
|
|
25
|
-
`,u)}});let H=await v;E&&clearTimeout(E);let j=C.end();j&&(I+=j);let B=_.end();if(B&&(O+=B),H.exitCode!==0&&!u||T){let k=O||(typeof H.stderr=="string"?H.stderr:""),b=H,x;return D?x=`Codex CLI produced no output for ${Math.round(L/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:b.timedOut?x=`Codex CLI timed out after ${Math.round(y/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?x=T:b.signal?x=k.trim()||`Codex CLI killed by signal ${b.signal}`:b.code==="ENOENT"||/ENOENT|spawn codex/i.test((b.shortMessage||"")+" "+k)?x=dt():x=k.trim()||`Codex CLI exited with code ${b.exitCode??"unknown"}`,{content:"",...Q(x),duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}let A="";try{A=Us(d,"utf8").trim()}catch{}if(A&&A!==u){let k=A.startsWith(u)?A.slice(u.length):A;u=A,k&&t(k,u)}return{content:u,duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}catch(y){let v=/ENOENT|spawn codex/i.test(y?.message||"")?dt():y?.message;return{content:u,...Q(v||"Codex CLI failed"),duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}finally{Bs(c,{recursive:!0,force:!0})}}async function
|
|
25
|
+
`,u)}});let H=await v;E&&clearTimeout(E);let j=C.end();j&&(I+=j);let B=_.end();if(B&&(O+=B),H.exitCode!==0&&!u||T){let k=O||(typeof H.stderr=="string"?H.stderr:""),b=H,x;return D?x=`Codex CLI produced no output for ${Math.round(L/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:b.timedOut?x=`Codex CLI timed out after ${Math.round(y/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?x=T:b.signal?x=k.trim()||`Codex CLI killed by signal ${b.signal}`:b.code==="ENOENT"||/ENOENT|spawn codex/i.test((b.shortMessage||"")+" "+k)?x=dt():x=k.trim()||`Codex CLI exited with code ${b.exitCode??"unknown"}`,{content:"",...Q(x),duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}let A="";try{A=Us(d,"utf8").trim()}catch{}if(A&&A!==u){let k=A.startsWith(u)?A.slice(u.length):A;u=A,k&&t(k,u)}return{content:u,duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}catch(y){let v=/ENOENT|spawn codex/i.test(y?.message||"")?dt():y?.message;return{content:u,...Q(v||"Codex CLI failed"),duration:Date.now()-o,usage:g,billedModel:m,codexSessionId:f||r}}finally{Bs(c,{recursive:!0,force:!0})}}async function fo(s,e,t,n,r,i,o,a){let c=Date.now();if(o?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=ue(s,e,n),l=io(s,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",g,m=e.freshSession?void 0:r,f,T,y=!0,v;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),O=ao(s,e);if(s.persistentProcess)try{T=await Wn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:O,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:o}),l.splice(1,0,"--server",T.url),O=T.env,i?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(k){if(!(k instanceof Bn))throw k;k.standalone&&l.splice(1,0,"--standalone"),i?.({type:"opencode.fallback",reason:k.message})}if(o?.aborted)throw new Error("task cancelled by operator");let D=ut("opencode",l,{cwd:s.workspace,timeout:I,reject:!1,env:O,extendEnv:!1,buffer:!1,stdin:"ignore"});try{i?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let C=!1,_,L=()=>{T?.invalidate(),C=!0,_=o?.reason?.message||(typeof o?.reason=="string"?o.reason:"task cancelled by operator");try{D.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};o&&o.addEventListener("abort",L,{once:!0}),v=()=>o?.removeEventListener("abort",L),o?.aborted&&L();let E="",F="",H=new Fe("utf8"),j=new Fe("utf8"),B=k=>{if(k.trim())try{let b=JSON.parse(k);try{i?.(b)}catch{}typeof b.sessionID=="string"&&(m=b.sessionID);let x=b.type==="text"&&typeof b.part?.text=="string"?b.part.text:void 0;x&&(u||i?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),u+=x,t?.(x,u));let N=b.type==="reasoning"&&typeof b.part?.text=="string"?b.part.text:void 0;N&&a?.(N);let R=b.type==="step_finish"?b.part?.tokens:void 0;R&&(g={inputTokens:de(R.input),outputTokens:de(R.output),cacheReadTokens:de(R.cache?.read),cacheCreateTokens:de(R.cache?.write)}),f=oo(b)||f}catch{u+=k+`
|
|
26
26
|
`,t?.(k+`
|
|
27
27
|
`,u)}};D.stdout?.on("data",k=>{E+=H.write(k);let b=E.split(`
|
|
28
|
-
`);E=b.pop()||"";for(let x of b)B(x)}),D.stderr?.on("data",k=>{F+=j.write(k)});let A=await D;if(o&&o.removeEventListener("abort",L),E+=H.end(),E.trim()&&B(E),F+=j.end(),C)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(A.exitCode!==0||f){let k=A,b;return k.timedOut?b=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:f?b=f:k.code==="ENOENT"||/ENOENT|spawn opencode/i.test((k.shortMessage||"")+" "+F)?b=Ls():b=F.trim()||`OpenCode exited with code ${k.exitCode??"unknown"}`,{content:"",...Q(b),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return y=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:m}}catch(I){if(o?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let O=/ENOENT|spawn opencode/i.test(I?.message||"")?Ls():I?.message;return{content:u,...Q(O||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{v?.(),T?.release(y)}}async function
|
|
28
|
+
`);E=b.pop()||"";for(let x of b)B(x)}),D.stderr?.on("data",k=>{F+=j.write(k)});let A=await D;if(o&&o.removeEventListener("abort",L),E+=H.end(),E.trim()&&B(E),F+=j.end(),C)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(A.exitCode!==0||f){let k=A,b;return k.timedOut?b=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:f?b=f:k.code==="ENOENT"||/ENOENT|spawn opencode/i.test((k.shortMessage||"")+" "+F)?b=Ls():b=F.trim()||`OpenCode exited with code ${k.exitCode??"unknown"}`,{content:"",...Q(b),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return y=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:m}}catch(I){if(o?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let O=/ENOENT|spawn opencode/i.test(I?.message||"")?Ls():I?.message;return{content:u,...Q(O||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{v?.(),T?.release(y)}}async function yo(s,e,t,n){let r=Date.now();try{let i=await import("@anthropic-ai/claude-agent-sdk"),{query:o}=i,a=ue(s,e,n),c="",d=o({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(i){return{content:"",...Q(`SDK error: ${i.message}`),duration:Date.now()-r}}}async function bo(s,e,t,n,r,i,o,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,g=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let f=setTimeout(()=>{g=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);f.unref?.();let T=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let y=s.provider||"claude-code",v=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,O=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),D=e.context?.channel==="web-chat"&&O?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=Jn(s),_=Object.keys(C).length>0,L={task:v,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:D,providerOpts:i,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:B}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,O=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),D=e.context?.channel==="web-chat"&&O?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=Jn(s),_=Object.keys(C).length>0,L={task:v,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:D,providerOpts:i,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:B}=await import("./agent-FUMJM6OW.js"),A="",k,b,x,N;for await(let R of B(L)){if(c)try{c(R)}catch{}if(R.type==="text_delta")A+=R.text,r(R.text,A);else if(R.type==="thinking_delta")R.text&&o&&o(R.text);else if(R.type==="generate_result"){if(R.result.content&&R.result.content!==A){let w=R.result.content.slice(A.length);w?(A=R.result.content,r(w,A)):A=R.result.content}k=R.result.tokensUsed,R.result.inputTokens!=null&&(b=R.result.inputTokens),R.result.outputTokens!=null&&(x=R.result.outputTokens)}else if(R.type==="done"){if(R.result.content&&R.result.content!==A){let w=R.result.content.slice(A.length);w?(A=R.result.content,r(w,A)):A=R.result.content}R.result.tokensUsed!=null&&(k=R.result.tokensUsed)}else R.type==="error"&&(N=R.error)}return N&&!A?g?T():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-d}:((b===void 0||x===void 0)&&k&&(b=Math.round(k*.7),x=k-b),{content:A||"Done.",tokensUsed:k,usage:b!==void 0||x!==void 0?{inputTokens:b||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:E}=await import("./agent-FUMJM6OW.js"),F=await E(L),H=F.inputTokens,j=F.outputTokens;if((H===void 0||j===void 0)&&F.tokensUsed){let B=F.tokensUsed;H=Math.round(B*.7),j=B-H}return{content:F.content||"Done.",tokensUsed:F.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(y){return g?T():y?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Q(`Orchestrator error: ${y.message}`),duration:Date.now()-d}}finally{clearTimeout(f),a&&a.removeEventListener("abort",m)}}var wo=1e3;async function xo(s,e){let t=Promise.resolve(s).then(o=>({kind:"exit",r:o})),n,r=e.then(()=>new Promise(o=>{n=setTimeout(()=>o({kind:"grace"}),wo),n.unref?.()})),i=await Promise.race([t,r]);return n&&clearTimeout(n),i.kind==="exit"?i.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function To(s,e,t,n,r,i,o){let a=at();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let g,m=!1;try{let A=a.list().length;g=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),m=a.list().length>A}catch(A){return A instanceof Te,null}m&&Kt(e.agentId,s,e.model,n,"persistent");let f=ue(s,e,t),T="",y,v,I,O,D,C,_,L="",E="",F=A=>{if(!o||!A)return;let k;if(E&&A.startsWith(E)?k=A.slice(E.length):k=L&&!L.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
|
-
${A}`:A,E=A,!!k){L+=k;try{o(k,L)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};i&&(i.aborted?j():i.addEventListener("abort",j,{once:!0}));let B=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let k of g.runTurn({message:f,taskId:e.taskId??"unknown",deadlineMs:A})){if(B=!0,r)try{r(k.raw)}catch{}if(k.type==="assistant"){let b=k.raw.message?.content??[];for(let N of b)N.type==="text"&&typeof N.text=="string"?(T=N.text,F(N.text)):N.type==="tool_use"&&(E="");let x=k.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(O=N)}}if(k.type==="result"){let b=k.raw;if(b.is_error){let x=Q(typeof b.result=="string"?b.result:"claude error");y=x.error,v=x.errorKind}else typeof b.result=="string"&&b.result.length>0&&(T=b.result,L||F(b.result));typeof b.session_id=="string"&&(_=b.session_id),b.usage&&(I={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(D=b.num_turns),typeof b.message?.model=="string"?C=b.message.model:typeof b.model=="string"&&(C=b.model)}}}catch(A){if(H)y="task cancelled by operator",v="cancelled";else if(B)if(A instanceof Le)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,v="interrupted";else if(A instanceof Ne){let k=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);y=k.error,v=k.errorKind}else{let k=Q(`persistent claude process error: ${A?.message||String(A)}`);y=k.error,v=k.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),i&&i.removeEventListener("abort",j),null}finally{i&&i.removeEventListener("abort",j)}return H&&!y&&(y="task cancelled by operator",v="cancelled"),{content:H?"":T,error:y,errorKind:v,duration:Date.now()-c,usage:I,contextTokens:O,numTurns:D,billedModel:C,claudeSessionId:_}}function Vs(s){return ae(s.autonomy)?s.taskId?Ds(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function
|
|
33
|
+
${A}`:A,E=A,!!k){L+=k;try{o(k,L)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};i&&(i.aborted?j():i.addEventListener("abort",j,{once:!0}));let B=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let k of g.runTurn({message:f,taskId:e.taskId??"unknown",deadlineMs:A})){if(B=!0,r)try{r(k.raw)}catch{}if(k.type==="assistant"){let b=k.raw.message?.content??[];for(let N of b)N.type==="text"&&typeof N.text=="string"?(T=N.text,F(N.text)):N.type==="tool_use"&&(E="");let x=k.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(O=N)}}if(k.type==="result"){let b=k.raw;if(b.is_error){let x=Q(typeof b.result=="string"?b.result:"claude error");y=x.error,v=x.errorKind}else typeof b.result=="string"&&b.result.length>0&&(T=b.result,L||F(b.result));typeof b.session_id=="string"&&(_=b.session_id),b.usage&&(I={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(D=b.num_turns),typeof b.message?.model=="string"?C=b.message.model:typeof b.model=="string"&&(C=b.model)}}}catch(A){if(H)y="task cancelled by operator",v="cancelled";else if(B)if(A instanceof Le)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,v="interrupted";else if(A instanceof Ne){let k=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);y=k.error,v=k.errorKind}else{let k=Q(`persistent claude process error: ${A?.message||String(A)}`);y=k.error,v=k.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),i&&i.removeEventListener("abort",j),null}finally{i&&i.removeEventListener("abort",j)}return H&&!y&&(y="task cancelled by operator",v="cancelled"),{content:H?"":T,error:y,errorKind:v,duration:Date.now()-c,usage:I,contextTokens:O,numTurns:D,billedModel:C,claudeSessionId:_}}function Vs(s){return ae(s.autonomy)?s.taskId?Ds(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Io(s,e,t,n,r,i,o){let a=e.autonomy,c=Os(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Nn(a)}
|
|
34
34
|
|
|
35
35
|
${e.message}`};process.stderr.write(`[claude-autonomy] agent=${e.agentId} level=${a} task=${d} via=spawn (persistent process bypassed)
|
|
36
|
-
`);let u=t?await Ys(s,l,t,n,r,i,o):await Xs(s,l,n,r,o),g=Ns(d);return{...u,autonomy:a,...g.length?{autonomyBlocks:g}:{}}}async function Zs(s,e,t,n,r,i,o,a,c){if(ae(e.autonomy))return
|
|
37
|
-
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),i=e.after??r,o=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Jt(this.sessionsDir).filter(D=>D.startsWith(`${a}:`)&&D.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=i.slice(0,10),l=o.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(D=>{let C=D.match(u);if(!C)return!1;let _=C[1];return _>=d&&_<=l}),m=[],f=0,T=e.query?.toLowerCase(),y=e.participants?.length?new Set(e.participants):void 0;for(let D of g){let C;try{C=JSON.parse(ke(Se(this.sessionsDir,D),"utf-8"))}catch{continue}if(C.agentId===e.agentId&&!(e.channel&&C.channel!==e.channel)&&!(e.chatId&&C.chatId!==e.chatId))for(let _ of C.messages)f++,!(!_.timestamp||_.timestamp<i||_.timestamp>=o)&&(y&&_.role==="user"&&!y.has(_.name??"")||T&&!_.content.toLowerCase().includes(T)||m.push({ts:_.timestamp,role:_.role,senderName:_.name??"",content:_.content,channel:C.channel,chatId:C.chatId,day:C.day,sessionFile:D}))}m.sort((D,C)=>C.ts.localeCompare(D.ts));let v=m.slice(0,t),I=v.length>0?v[v.length-1].ts:null,O=m.length>t;return{turns:v,oldestTs:I,hasMore:O,totalScanned:f}}recentByChatId(e){let t=Math.min(Math.max(e.limit??He,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),i;try{i=Jt(this.sessionsDir).filter(u=>u.endsWith(".json"))}catch{return[]}let o=`:${e.channel}:${e.chatId}:`,a=i.filter(u=>{if(!u.includes(o))return!1;let g=u.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),c=[];for(let u of a){let g;try{g=JSON.parse(ke(Se(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:u})}let d=new Set,l=[];for(let u of c){let g=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;d.has(g)||(d.add(g),l.push(u))}return l.sort((u,g)=>u.ts.localeCompare(g.ts)),l.slice(-t)}sessionIdleMs(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:Date.now()-new Date(r.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,r){if(r!==void 0&&r!==""&&!
|
|
36
|
+
`);let u=t?await Ys(s,l,t,n,r,i,o):await Xs(s,l,n,r,o),g=Ns(d);return{...u,autonomy:a,...g.length?{autonomyBlocks:g}:{}}}async function Zs(s,e,t,n,r,i,o,a,c){if(ae(e.autonomy))return Io(s,e,n,r,i,o,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let d=await To(s,e,r,i,o,a,n);if(d!==null)return d}return n?Ys(s,e,n,r,i,o,a):Xs(s,e,r,i,a);case"codex-cli":if(s.persistentProcess)try{let d=await Cs.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:lt(s,e),args:Gs(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Ut(ue(s,e,r),e.systemPromptAppend),resume:i,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:o,onDelta:n});return{...d,...d.error?Q(d.error):{}}}catch(d){if(!(d instanceof ce))throw d;if(o?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?mo(s,e,n,r,i,o):ho(s,e,r,i);case"opencode":return fo(s,e,n,r,i,o,a,c);case"sdk":{let d=s.provider||"claude",l=t[d]?.apiKey;return l?yo(s,e,l,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=s.provider||"claude-code",l=t[d],u=l?.apiKey;return bo(s,e,u,r,n,{thinking:l?.thinking},c,a,o)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as ke,writeFileSync as er,mkdirSync as ko,existsSync as Gt,readdirSync as Jt}from"fs";import{resolve as Se}from"path";var Qt=12e3,He=30,So=720,vo=40,Co=18e4,Ao="[Compacted conversation summary",$o=7*864e5,Mo=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Ro(s){return s?Mo.some(e=>e.test(s)):!1}var Po=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function nr(s){if(!s)return null;let e=0;for(let t of Po)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function tr(s,e,t,n){if(s.length===0)return!1;let r=s[s.length-1];return r.role===e&&(r.name??"")===t&&r.content===n}function sr(s,e){let t=(s??[]).filter(i=>i.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function rr(s,e,t){if(t<=0)return[];let n=(s??[]).filter(o=>o.role==="user"),r=n[n.length-1],i=(r&&r.content===e?n.length-1:n.length)-1;return i<=0?[]:n.slice(Math.max(0,i-t),i).map(o=>o.content)}function _o(s){let e=s.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let r=Math.floor(n/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var gt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Se(e,".agentx/sessions"),Gt(this.sessionsDir)||ko(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??So),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??vo),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Co)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let i=this.sessionKey(e,t,n),o=this.seedingPromises.get(i);if(o)return o;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let l=await c.seedHistory(n,{maxMessages:He,maxChars:Qt});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(i,d);try{await d}finally{this.seedingPromises.delete(i)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let i of e.messages)i.externalId&&n.add(i.externalId);let r=0;for(let i of t)i.externalId&&n.has(i.externalId)||(e.messages.push({role:i.role,name:i.name,content:i.content,timestamp:i.timestamp,seeded:!0,externalId:i.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Se(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let r=this.sessionKey(e,t,n);if(this.cache.has(r))return this.cache.get(r);let i=this.sessionFile(r);if(Gt(i))try{let d=JSON.parse(ke(i,"utf-8"));return this.cache.set(r,d),d}catch{}let o=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:o?.updatedAt??new Date().toISOString(),claudeSessionId:o?.claudeSessionId,codexSessionId:o?.codexSessionId,turnCount:o?.turnCount,lastTurnInputTokens:o?.lastTurnInputTokens,lastTurnContextTokens:o?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),i=`${e}:${t}:${n}:${r}`,o=this.sessionFile(i);if(!Gt(o))return null;try{return JSON.parse(ke(o,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,i){let o=this.getSession(e,t,n);tr(o.messages,"user",r,i)||(o.messages.push({role:"user",name:r,content:i,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}removeLastUserMessageIfMatches(e,t,n,r){let i=this.getSession(e,t,n),o=i.messages[i.messages.length-1];return!o||o.role!=="user"||(o.content||"").trim()!==(r||"").trim()?!1:(i.messages.pop(),i.updatedAt=new Date().toISOString(),this.save(i),!0)}addAgentMessage(e,t,n,r){let i=this.getSession(e,t,n);tr(i.messages,"agent",e,r)||(i.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,r){let i=this.getSession(e,t,n);i.claudeSessionId=r,i.updatedAt=new Date().toISOString(),this.save(i)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,r){let i=this.getSession(e,t,n);i.codexSessionId=r,i.updatedAt=new Date().toISOString(),this.save(i)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,r){let i=this.getSession(e,t,n);i.opencodeSessionId=r,i.updatedAt=new Date().toISOString(),this.save(i)}buildHistoryContext(e,t,n,r={}){let i=this.getSession(e,t,n);if(i.messages.length===0)return"";let o=Math.max(1,r.maxMessages??He),a=Math.max(200,r.maxChars??Qt),c=[],d=0;for(let g=i.messages.length-1;g>=0&&c.length<o;g--){let m=i.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let l=[`[Conversation history for today (${i.day})]`],u="";for(let g of c){let m=_o(g.timestamp);m!==u&&(l.push(`\u2014 ${m} \u2014`),u=m);let f=g.name||(g.role==="user"?"User":"Agent");l.push(`${f}: ${g.content}`)}return l.push("[End of history \u2014 respond to the latest message above]"),l.push(""),l.join(`
|
|
37
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),i=e.after??r,o=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Jt(this.sessionsDir).filter(D=>D.startsWith(`${a}:`)&&D.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=i.slice(0,10),l=o.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(D=>{let C=D.match(u);if(!C)return!1;let _=C[1];return _>=d&&_<=l}),m=[],f=0,T=e.query?.toLowerCase(),y=e.participants?.length?new Set(e.participants):void 0;for(let D of g){let C;try{C=JSON.parse(ke(Se(this.sessionsDir,D),"utf-8"))}catch{continue}if(C.agentId===e.agentId&&!(e.channel&&C.channel!==e.channel)&&!(e.chatId&&C.chatId!==e.chatId))for(let _ of C.messages)f++,!(!_.timestamp||_.timestamp<i||_.timestamp>=o)&&(y&&_.role==="user"&&!y.has(_.name??"")||T&&!_.content.toLowerCase().includes(T)||m.push({ts:_.timestamp,role:_.role,senderName:_.name??"",content:_.content,channel:C.channel,chatId:C.chatId,day:C.day,sessionFile:D}))}m.sort((D,C)=>C.ts.localeCompare(D.ts));let v=m.slice(0,t),I=v.length>0?v[v.length-1].ts:null,O=m.length>t;return{turns:v,oldestTs:I,hasMore:O,totalScanned:f}}recentByChatId(e){let t=Math.min(Math.max(e.limit??He,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),i;try{i=Jt(this.sessionsDir).filter(u=>u.endsWith(".json"))}catch{return[]}let o=`:${e.channel}:${e.chatId}:`,a=i.filter(u=>{if(!u.includes(o))return!1;let g=u.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),c=[];for(let u of a){let g;try{g=JSON.parse(ke(Se(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:u})}let d=new Set,l=[];for(let u of c){let g=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;d.has(g)||(d.add(g),l.push(u))}return l.sort((u,g)=>u.ts.localeCompare(g.ts)),l.slice(-t)}sessionIdleMs(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:Date.now()-new Date(r.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,r){if(r!==void 0&&r!==""&&!Ro(r))return"";let i=new Date().toISOString().slice(0,10),o=this.sessionKey(e,t,n);try{let a=Jt(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(i)&&d.endsWith(".json")),c=[];for(let d of a)try{let l=JSON.parse(ke(Se(this.sessionsDir,d),"utf-8"));if(l.id===o||l.messages.length===0)continue;let u=l.messages.slice(-4),m=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,f=u.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${m} (${l.channel}):
|
|
38
38
|
${f.join(`
|
|
39
39
|
`)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
40
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let i=this.getSession(e,t,n),{needsCompaction:o,compactSession:a,applyCompaction:c}=await import("./compaction-MECSN36J.js");if(!o(i.messages))return{compacted:!1};let d=await a(i.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(i.messages=c(i.messages,d),i.updatedAt=new Date().toISOString(),this.save(i),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(ko)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,i){let o=this.getSession(e,t,n);o.turnCount=(o.turnCount??0)+1,o.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),o.lastTurnContextTokens=i,o.updatedAt=new Date().toISOString(),this.save(o)}rotationMemoFile(){return Se(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,i){let o=this.readRotationMemos();o[`${e}:${t}:${n}`]={memo:r,reason:i,capturedAt:new Date().toISOString()},er(this.rotationMemoFile(),JSON.stringify(o,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let i=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(i)||i>So?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>He&&(e.messages=e.messages.slice(-He));let n=e.messages.reduce((i,o)=>i+o.content.length,0);for(;n>Qt&&e.messages.length>2;){let i=e.messages.shift();n-=i.content.length}let r=t-e.messages.length;r>0&&he.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);er(t,JSON.stringify(e,null,2))}catch{}}};var pt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,i=n.filter(c=>c>r),o=t-6e4,a=i.filter(c=>c>o);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(i.length>=this.maxPerHour){let c=i[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${i.length}/${this.maxPerHour} per hour`,waitMs:d}}return i.push(t),this.windows.set(e,i),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,i=!0;for(;;){let o=this.check(e);if(o.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${o.reason} (waited ${Math.round(n/1e3)}s, giving up)`};i&&(i=!1,t.onWait?.(o.reason,o.waitMs));let a=r-Date.now(),c=Math.min(o.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as je,writeFileSync as ir,appendFileSync as Mo,existsSync as ve,mkdirSync as Ro}from"fs";import{resolve as Ce}from"path";var ar={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},cr=2e5,Po=1.5;function _o(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function dr(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>cr?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var or=500,Eo=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,Ro(this.dir,{recursive:!0}),this.pricing=Do()}getPricing(){return this.pricing}static calculateCost(e,t,n=ar){let r=_o(t||e.model||"claude-sonnet"),i=n[r]||n["claude-sonnet"],o=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*i.input+(e.outputTokens||0)/1e6*i.output+(e.cacheReadTokens||0)/1e6*i.cacheRead+(e.cacheCreateTokens||0)/1e6*i.cacheCreate,u=o/1e6*i.input+a/1e6*i.output+c/1e6*i.cacheRead+d/1e6*i.cacheCreate;return l+u*Po}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,i,o,a,c,d){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let g=0,m=0,f=0,T=0,y=0,v=0,I=0,O=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>cr?(y=n.inputTokens,v=n.outputTokens,I=n.cacheReadTokens,O=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,f=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&i!==void 0&&(g=Math.ceil(r/4),m=Math.ceil(i/4)),u.inputTokens+=g,u.outputTokens+=m,u.cacheReadTokens+=f,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+y,u.tier2OutputTokens=(u.tier2OutputTokens||0)+v,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+O,o&&u.errors++,u.byChannel||(u.byChannel={});let D=(c||"other").toLowerCase(),C=u.byChannel[D]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};C.tasks++,C.totalDuration+=t,C.inputTokens+=g,C.outputTokens+=m,C.cacheReadTokens+=f,C.cacheCreateTokens+=T,C.tier2InputTokens+=y,C.tier2OutputTokens+=v,C.tier2CacheReadTokens+=I,C.tier2CacheCreateTokens+=O,o&&C.errors++,u.byChannel[D]=C,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>or&&u.sessionKeys.splice(0,u.sessionKeys.length-or))),l.agents[e]=u,this.save(l)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(ve(t))try{return this.cache=JSON.parse(je(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ve(t))return null;try{return JSON.parse(je(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,i=0,o=0,a=0,c=0,d=0,l="",u=0,g={},m={},f={};for(let[T,y]of Object.entries(n.agents)){let v=this.cost(y);g[T]=v,r+=y.tasks,i+=(y.inputTokens||0)+(y.tier2InputTokens||0),o+=(y.outputTokens||0)+(y.tier2OutputTokens||0),a+=(y.cacheReadTokens||0)+(y.tier2CacheReadTokens||0),c+=(y.cacheCreateTokens||0)+(y.tier2CacheCreateTokens||0),d+=v,v>u&&(u=v,l=T);let I=y.sessionKeys?.length||0;m[T]={sessions:I,avgTasksPerSession:I>0?y.tasks/I:y.tasks};for(let[O,D]of Object.entries(y.byChannel||{})){let C=this.cost(D,y.model);f[O]=(f[O]||0)+C}}return{date:t,totalTasks:r,totalInput:i,totalOutput:o,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:g,agentSessionStats:m,byChannel:f}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),i=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),o=Object.entries(e.agentCosts).sort(([,d],[,l])=>l-d).map(([d,l])=>{let u=e.agentSessionStats[d],g=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${r(l)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,l])=>l-d).map(([d,l])=>`${d}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${i(e.totalInput)} | ${i(e.totalOutput)} | ${i(e.totalCacheRead)} | ${i(e.totalCacheCreate)} | $${r(e.totalCost)} | ${o} | ${a} |`;ve(n)?Mo(n,c+`
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let i=this.getSession(e,t,n),{needsCompaction:o,compactSession:a,applyCompaction:c}=await import("./compaction-MECSN36J.js");if(!o(i.messages))return{compacted:!1};let d=await a(i.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(i.messages=c(i.messages,d),i.updatedAt=new Date().toISOString(),this.save(i),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(Ao)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,i){let o=this.getSession(e,t,n);o.turnCount=(o.turnCount??0)+1,o.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),o.lastTurnContextTokens=i,o.updatedAt=new Date().toISOString(),this.save(o)}rotationMemoFile(){return Se(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,i){let o=this.readRotationMemos();o[`${e}:${t}:${n}`]={memo:r,reason:i,capturedAt:new Date().toISOString()},er(this.rotationMemoFile(),JSON.stringify(o,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let i=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(i)||i>$o?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>He&&(e.messages=e.messages.slice(-He));let n=e.messages.reduce((i,o)=>i+o.content.length,0);for(;n>Qt&&e.messages.length>2;){let i=e.messages.shift();n-=i.content.length}let r=t-e.messages.length;r>0&&he.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);er(t,JSON.stringify(e,null,2))}catch{}}};var pt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,i=n.filter(c=>c>r),o=t-6e4,a=i.filter(c=>c>o);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(i.length>=this.maxPerHour){let c=i[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${i.length}/${this.maxPerHour} per hour`,waitMs:d}}return i.push(t),this.windows.set(e,i),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,i=!0;for(;;){let o=this.check(e);if(o.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${o.reason} (waited ${Math.round(n/1e3)}s, giving up)`};i&&(i=!1,t.onWait?.(o.reason,o.waitMs));let a=r-Date.now(),c=Math.min(o.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as je,writeFileSync as ir,appendFileSync as Eo,existsSync as ve,mkdirSync as Do}from"fs";import{resolve as Ce}from"path";var ar={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},cr=2e5,Oo=1.5;function No(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function dr(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>cr?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var or=500,Lo=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,Do(this.dir,{recursive:!0}),this.pricing=Fo()}getPricing(){return this.pricing}static calculateCost(e,t,n=ar){let r=No(t||e.model||"claude-sonnet"),i=n[r]||n["claude-sonnet"],o=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*i.input+(e.outputTokens||0)/1e6*i.output+(e.cacheReadTokens||0)/1e6*i.cacheRead+(e.cacheCreateTokens||0)/1e6*i.cacheCreate,u=o/1e6*i.input+a/1e6*i.output+c/1e6*i.cacheRead+d/1e6*i.cacheCreate;return l+u*Oo}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,i,o,a,c,d){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let g=0,m=0,f=0,T=0,y=0,v=0,I=0,O=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>cr?(y=n.inputTokens,v=n.outputTokens,I=n.cacheReadTokens,O=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,f=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&i!==void 0&&(g=Math.ceil(r/4),m=Math.ceil(i/4)),u.inputTokens+=g,u.outputTokens+=m,u.cacheReadTokens+=f,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+y,u.tier2OutputTokens=(u.tier2OutputTokens||0)+v,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+O,o&&u.errors++,u.byChannel||(u.byChannel={});let D=(c||"other").toLowerCase(),C=u.byChannel[D]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};C.tasks++,C.totalDuration+=t,C.inputTokens+=g,C.outputTokens+=m,C.cacheReadTokens+=f,C.cacheCreateTokens+=T,C.tier2InputTokens+=y,C.tier2OutputTokens+=v,C.tier2CacheReadTokens+=I,C.tier2CacheCreateTokens+=O,o&&C.errors++,u.byChannel[D]=C,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>or&&u.sessionKeys.splice(0,u.sessionKeys.length-or))),l.agents[e]=u,this.save(l)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(ve(t))try{return this.cache=JSON.parse(je(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ve(t))return null;try{return JSON.parse(je(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,i=0,o=0,a=0,c=0,d=0,l="",u=0,g={},m={},f={};for(let[T,y]of Object.entries(n.agents)){let v=this.cost(y);g[T]=v,r+=y.tasks,i+=(y.inputTokens||0)+(y.tier2InputTokens||0),o+=(y.outputTokens||0)+(y.tier2OutputTokens||0),a+=(y.cacheReadTokens||0)+(y.tier2CacheReadTokens||0),c+=(y.cacheCreateTokens||0)+(y.tier2CacheCreateTokens||0),d+=v,v>u&&(u=v,l=T);let I=y.sessionKeys?.length||0;m[T]={sessions:I,avgTasksPerSession:I>0?y.tasks/I:y.tasks};for(let[O,D]of Object.entries(y.byChannel||{})){let C=this.cost(D,y.model);f[O]=(f[O]||0)+C}}return{date:t,totalTasks:r,totalInput:i,totalOutput:o,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:g,agentSessionStats:m,byChannel:f}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),i=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),o=Object.entries(e.agentCosts).sort(([,d],[,l])=>l-d).map(([d,l])=>{let u=e.agentSessionStats[d],g=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${r(l)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,l])=>l-d).map(([d,l])=>`${d}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${i(e.totalInput)} | ${i(e.totalOutput)} | ${i(e.totalCacheRead)} | ${i(e.totalCacheCreate)} | $${r(e.totalCost)} | ${o} | ${a} |`;ve(n)?Eo(n,c+`
|
|
41
41
|
`):ir(n,`# Token Costs
|
|
42
42
|
|
|
43
43
|
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
@@ -46,18 +46,18 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
|
46
46
|
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
47
47
|
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
48
48
|
`+c+`
|
|
49
|
-
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=je(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(t))return null;try{let r=je(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let i=r.map(o=>o.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(o=>!!o);return i.sort(),i[i.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],i=this.lastTokenCostsDate(t.filePath),o=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(i&&d<=i)break;o.push(d),a.setUTCDate(a.getUTCDate()-1)}o.reverse();for(let c of o){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,i=0,o=0,a=0,c=0,d={},l={};for(let f=0;f<e;f++){let T=new Date(Date.now()-f*864e5).toISOString().slice(0,10),y=this.getDate(T);if(y)for(let[v,I]of Object.entries(y.agents)){let O=this.cost(I);t+=I.tasks;let D=(I.inputTokens||0)+(I.tier2InputTokens||0),C=(I.outputTokens||0)+(I.tier2OutputTokens||0),_=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),L=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=D,r+=C,i+=_,o+=L,a+=I.errors,c+=O;let E=d[v]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};E.tasks+=I.tasks,E.input+=D,E.output+=C,E.cacheRead+=_,E.cacheCreate+=L,E.total=E.input+E.output+E.cacheRead+E.cacheCreate,E.totalDuration+=I.totalDuration,E.avgDuration=E.totalDuration/E.tasks,E.cost+=O,E.sessions+=I.sessionKeys?.length||0,I.model&&(E.model=I.model),d[v]=E;for(let[F,H]of Object.entries(I.byChannel||{})){let j=this.cost(H,I.model),B=l[F]||{tasks:0,cost:0};B.tasks+=H.tasks,B.cost+=j,l[F]=B}}}let u=n+r+i+o,g=i+o>0?i/(i+o):0,m={};for(let[f,T]of Object.entries(d))m[f]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:i,totalCacheCreate:o,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:m}}filePath(e){return Ce(this.dir,`${e}.json`)}save(e){try{ir(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=je(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(t))return null;try{let r=je(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let i=r.map(o=>o.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(o=>!!o);return i.sort(),i[i.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],i=this.lastTokenCostsDate(t.filePath),o=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(i&&d<=i)break;o.push(d),a.setUTCDate(a.getUTCDate()-1)}o.reverse();for(let c of o){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,i=0,o=0,a=0,c=0,d={},l={};for(let f=0;f<e;f++){let T=new Date(Date.now()-f*864e5).toISOString().slice(0,10),y=this.getDate(T);if(y)for(let[v,I]of Object.entries(y.agents)){let O=this.cost(I);t+=I.tasks;let D=(I.inputTokens||0)+(I.tier2InputTokens||0),C=(I.outputTokens||0)+(I.tier2OutputTokens||0),_=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),L=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=D,r+=C,i+=_,o+=L,a+=I.errors,c+=O;let E=d[v]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};E.tasks+=I.tasks,E.input+=D,E.output+=C,E.cacheRead+=_,E.cacheCreate+=L,E.total=E.input+E.output+E.cacheRead+E.cacheCreate,E.totalDuration+=I.totalDuration,E.avgDuration=E.totalDuration/E.tasks,E.cost+=O,E.sessions+=I.sessionKeys?.length||0,I.model&&(E.model=I.model),d[v]=E;for(let[F,H]of Object.entries(I.byChannel||{})){let j=this.cost(H,I.model),B=l[F]||{tasks:0,cost:0};B.tasks+=H.tasks,B.cost+=j,l[F]=B}}}let u=n+r+i+o,g=i+o>0?i/(i+o):0,m={};for(let[f,T]of Object.entries(d))m[f]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:i,totalCacheCreate:o,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:m}}filePath(e){return Ce(this.dir,`${e}.json`)}save(e){try{ir(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Fo(){let s=JSON.parse(JSON.stringify(ar));try{let e=Ce(process.cwd(),Lo);if(!ve(e))return s;let t=JSON.parse(je(e,"utf-8"));for(let[n,r]of Object.entries(t))s[n]||(s[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(s[n],r)}catch{}return s}var Ho={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,memory:400,history:1200,"cross-chat":800,wiki:2500}},ur=4;function lr(s,e=Ho){let t=jo(s,e);t.sort((o,a)=>o.priority-a.priority);let n=[],r=0,i=e.totalBudget*ur;for(let o of t){if(!o.content)continue;let a=o.maxTokens*ur,c=o.content.length>a?o.content.slice(0,a)+"...":o.content;if(r+c.length>i){let d=i-r;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),r+=c.length}return n.join(`
|
|
50
50
|
|
|
51
|
-
`)}function
|
|
51
|
+
`)}function jo(s,e){let t=(o,a)=>e.layerBudgets?.[o]??a,n=[];if(n.push(Uo(s,t("channel",200))),n.push(Bo(s,t("scope",200))),s.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:s.landscape,tags:["landscape","world-model"]}),s.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:s.systemPrompt.split(`
|
|
52
52
|
`)[0],tags:["identity",s.agentId]}),s.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:s.bootstrapContext,tags:["bootstrap","identity","personality"]}),s.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:s.references,tags:["references","verified","deterministic"]}),s.intent&&s.intent.path.length>0){let o=[`[Intent path: ${s.intent.pathLabel}${s.intent.status==="pending"?" (pending approval)":""}]`],a=s.intent.path[s.intent.path.length-1],c=s.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([l,u])=>` ${l}: ${u}`).join(`
|
|
53
53
|
`);o.push(d)}s.intent.leaf?.input&&o.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:o.join(`
|
|
54
|
-
`),tags:["intent",...s.intent.path]})}else{let o=
|
|
54
|
+
`),tags:["intent",...s.intent.path]})}else{let o=Wo(s.message);o.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${o.join(", ")}]`,tags:o})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
55
55
|
`),tags:["artifacts",...s.mediaType?["media"]:[]]}),s.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:s.skillInjection,tags:["skills","auto-inject"]}),s.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:s.patternContext,tags:["patterns","behavioral","self-improving"]}),s.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:s.procedureContext,tags:["procedures","sop"]}),s.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:s.memoryContext,tags:["memory","persistent"]});let i=s.groupHistory||s.sessionHistory;if(i&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:i,tags:["history","conversation"]}),s.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:s.crossChatContext,tags:["history","cross-chat"]}),s.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:s.longMemoryRecall,tags:["history","long-memory"]}),s.handoverNote){let o=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&o.push(`Operator summary: ${s.handoverNote.summary}`),o.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:o.join(`
|
|
56
56
|
`),tags:["handover",s.handoverNote.fromAgent]})}return s.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${s.rotationMemo.reason}, ${s.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner:]`,s.rotationMemo.memo].join(`
|
|
57
|
-
`),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function
|
|
58
|
-
`),tags:r,rules:n}}function
|
|
59
|
-
`),tags:n}}function
|
|
60
|
-
`),sender:i[i.length-1].sender,timestamp:Date.now(),channel:i[0].channel,chatId:i[0].chatId,originalContext:i[i.length-1].originalContext,queuedAt:Math.min(...i.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(i),i;case"drop":return[];default:return i}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as
|
|
57
|
+
`),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function Uo(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(i=>`- ${i}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
58
|
+
`),tags:r,rules:n}}function Bo(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(i=>i.handle||i.name||i.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let i of r.facts)t.push(`\u2022 ${i}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:n}}function Wo(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var qo="resumeDelivery";function kd(s){if(!s||s.kind!=="direct"||!s.context||s.context[qo]||String(s.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let n=String(s.context.sender??"").match(/^agent:([^\s]+)$/);return n?n[1]:null}var Ko=32e3;function gr(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=Ko?e:null}catch{return null}}function Sd(s){if(!s)return null;try{let e=JSON.parse(s);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}function pr(s){return new Date(s).toISOString().slice(11,16)}function hr(s,e=Date.now()){return!Number.isFinite(s)||e-s<=6e4?null:`[queued at ${pr(s)} UTC, running at ${pr(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var ht=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let i=this.getOrCreate(e,t,n);if(!i.running)return null;switch(i.mode){case"drop":return"drop";case"collect":case"followup":return i.pending.push(r),i.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let i=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:i.length===1?i[0].text:i.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
60
|
+
`),sender:i[i.length-1].sender,timestamp:Date.now(),channel:i[0].channel,chatId:i[0].chatId,originalContext:i[i.length-1].originalContext,queuedAt:Math.min(...i.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(i),i;case"drop":return[];default:return i}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Go,writeFileSync as mr,appendFileSync as Jo,mkdirSync as Qo,existsSync as fr}from"fs";import{resolve as zt}from"path";var yr=50,zo="claude-haiku-4-5-20251001",Xo=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
61
61
|
|
|
62
62
|
Extract patterns like:
|
|
63
63
|
- "When asked about X, the approach that works is Y"
|
|
@@ -73,20 +73,20 @@ SKIP:
|
|
|
73
73
|
Output a JSON array:
|
|
74
74
|
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
75
75
|
|
|
76
|
-
If nothing worth extracting, output: []`,mt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=zt(e,".agentx/patterns"),fr(this.patternsDir)||
|
|
77
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};
|
|
76
|
+
If nothing worth extracting, output: []`,mt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=zt(e,".agentx/patterns"),fr(this.patternsDir)||Qo(this.patternsDir,{recursive:!0})}filePath(e){return zt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!fr(t))return[];try{return Go(t,"utf-8").split(`
|
|
77
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Jo(this.filePath(e),JSON.stringify(n)+`
|
|
78
78
|
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let i=r.map(l=>`${l.context} ${l.pattern}`),o=zt(this.patternsDir,`${t}_bm25_cache.json`),a=En(i,o),d=_n(e,a).slice(0,n).map(l=>r[l.docIndex]).filter(l=>l.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(l=>l.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
79
79
|
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let o=i.pattern.toLowerCase();return r.filter(c=>o.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),i=!1;for(let o of n)r.has(o.id)&&(o.accessCount++,o.lastUsed=new Date().toISOString(),o.confidence=Math.min(1,o.confidence+.05),i=!0);i&&mr(this.filePath(e),n.map(o=>JSON.stringify(o)).join(`
|
|
80
80
|
`)+`
|
|
81
81
|
`)}prune(e){let t=this.getAll(e);t.length<=yr||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,yr),mr(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
82
82
|
`)+`
|
|
83
|
-
`))}};async function br(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:i}=await import("./providers-ES5KVLI4.js"),c=(await i("claude").generate([{role:"system",content:
|
|
83
|
+
`))}};async function br(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:i}=await import("./providers-ES5KVLI4.js"),c=(await i("claude").generate([{role:"system",content:Xo},{role:"user",content:`User: ${e.slice(0,500)}
|
|
84
84
|
|
|
85
|
-
Agent: ${t.slice(0,1e3)}`}],{model:
|
|
86
|
-
\u2026[truncated ${s.length-e} chars]`}
|
|
87
|
-
`);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${o} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function
|
|
85
|
+
Agent: ${t.slice(0,1e3)}`}],{model:zo,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let l of d)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as Yo}from"events";var Vo=2e4,Yt=class{inner=new Yo;envelopeListeners=new Set;ring=new us;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let n=this.inner.emit(e,t);try{this.publish(Zo(e,t))}catch{}return n}publish(e){let t=ds(),n=e.id??cs(),r={id:n,rootId:e.rootId??t?.rootId??n,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Ot(e.summary)},i=e.parentId??t?.parentId;i&&(r.parentId=i),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let o of this.envelopeListeners)try{o(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>Vo&&this.seen.delete(this.seen.keys().next().value);let n={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Ot(e.summary??"")};e.parentId&&(n.parentId=e.parentId),e.agentId&&(n.agentId=e.agentId),e.ref&&(n.ref=e.ref),this.ring.push(n);for(let r of this.envelopeListeners)try{r(n)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function Zo(s,e){let t=e,n={type:s,at:t.at,agentId:t.agentId,ref:t.taskId};switch(s){case"message:matched":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:started":return{...n,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...n,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...n,kind:"agent",summary:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...n,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...n,kind:"agent",summary:String(s)}}}var Xt;function Z(){return Xt||(Xt=new Yt),Xt}Mt();Mt();var wr=["manual","notify","auto"];function ea(s){return typeof s=="string"&&wr.includes(s)}var Vt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var ta=7*24*60*6e4,Ue=class{constructor(e={},t){this.store=t;this.opts={...Vt,...e};let n={};try{n=t?.load()??{}}catch{n={}}let r=Date.now()-ta;for(let[i,o]of Object.entries(n))o&&Array.isArray(o.agentIds)&&(o.agentIds.length>0||o.watch)&&o.savedAt>=r&&this.saved.set(i,o)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let i=this.saved.get(e),o={sessionId:e,cwd:t.cwd??i?.cwd??"",agentIds:i?i.agentIds.filter(a=>!this.sessionFor(a)):[],mode:i?.mode??"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return i?.watch&&(o.watch={...i.watch}),this.sessions.set(e,o),i&&this.remember(o,n),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n?(n.lastSeenAt=t,n):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let r=this.sessions.get(e);if(r){for(let i of this.sessions.values())i.sessionId!==e&&(i.agentIds=i.agentIds.filter(o=>o!==t));for(let[i,o]of this.saved)i!==e&&(o.agentIds=o.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r.watch=void 0,this.remember(r),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],t||(n.watch=void 0),this.remember(n),n}watch(e,t,n=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,n,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:n},this.remember(r,n),r}advanceWatch(e,t){let n=this.sessions.get(e);n?.watch&&(n.watch.cursor.id===t.id&&n.watch.cursor.at===t.at||(n.watch.cursor=t,this.remember(n)))}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,this.remember(n),n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),n={}){this.sessions.delete(e),n.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,n){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,n)}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:we(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:na(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(i=>{this.waiters.set(r.id,{resolve:i})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let i=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!i||i.state!=="claimed"))return i.answer=t,this.settle(i,"answered",n),i}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let i=this.sessions.get(r.sessionId);return i?.awaitingAnswer===r.id&&(i.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let n={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(n.watch={...e.watch}),this.saved.set(e.sessionId,n)}for(let[n,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(n);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,i]of this.items)(i.state==="answered"||i.state==="expired")&&e-(i.settledAt??i.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let i=this.waiters.get(e.id);i&&(this.waiters.delete(e.id),i.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function na(s,e){return s.length<=e?s:`${s.slice(0,e)}
|
|
86
|
+
\u2026[truncated ${s.length-e} chars]`}Li();import{z as sa}from"zod";var Tr=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function ra(s){if(s==null)return{ok:!0,subscriptions:Tr};let e=sa.array(Ln).min(1).safeParse(s);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var ia=15,oa=1500,xr=200;function Ir(s,e=Date.now()){let t=s[s.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function aa(s,e){if(e.id){let n=s.findIndex(r=>r.id===e.id);if(n>=0)return s.slice(n+1)}let t=Date.parse(e.at);return Number.isNaN(t)?s:e.id?s.filter(n=>Date.parse(n.at)>t):s.filter(n=>Date.parse(n.at)>=t)}function Ud(s,e,t={}){let n=aa(e,s.cursor),r=n.length?Ir(n):s.cursor,i=n.filter(d=>s.subscriptions.some(l=>ls(l,d)));if(i.length===0)return{cursor:r,matched:0,shown:0};let o=s.cursor.id??s.cursor.at,{text:a,shown:c}=ca(i,o,t);return{text:a,cursor:r,matched:i.length,shown:c}}function ca(s,e,t={}){let n=Math.max(3,t.maxLines??ia),r=Math.max(200,t.maxChars??oa),i=s.map(a=>da(`- ${ps(a)}`)),o=i.length;for(let a=Math.min(o,n-1);a>=0;a--){let c=o-a,l=[c?`[agentx watch] ${o} events since your last turn, newest ${a} shown:`:`[agentx watch] ${o} event${o===1?"":"s"} since your last turn:`,...i.slice(o-a)];c&&l.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let u=l.join(`
|
|
87
|
+
`);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${o} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function da(s){return s.length<=xr?s:`${s.slice(0,xr-1)}\u2026`}import{existsSync as ua,mkdirSync as la,readFileSync as ga,renameSync as pa,writeFileSync as ha}from"node:fs";import{homedir as ma}from"node:os";import{dirname as fa,join as ya}from"node:path";function ba(s){return{load:()=>ua(s)?JSON.parse(ga(s,"utf-8")):{},save:e=>{la(fa(s),{recursive:!0});let t=`${s}.tmp`;ha(t,JSON.stringify(e,null,2),{mode:384}),pa(t,s)}}}function wa(){if(!process.env.VITEST)return ba(process.env.AGENTX_ATTACH_BINDINGS_FILE??ya(ma(),".agentx","attach-bindings.json"))}var Zt;function kr(){return Zt||(Zt=new Ue({},wa())),Zt}Rt();import{readFileSync as xa}from"fs";import{homedir as Ta}from"os";import{join as Ia}from"path";var Be=null,ka=6e4;function Sa(){try{let s=Ia(Ta(),".claude.json"),e=xa(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function va(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Ca(s=!1){let e=Date.now();return!s&&Be&&e-Be.checkedAt<ka||(Be=va(Sa(),e)),Be}function Sr(s){let e=Ca();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var vr={warnRatio:.8},X={...vr},Aa=5*60*60*1e3,$a=60*60*1e3,me=[];function Cr(s){X={...vr,...s||{}}}function Ar(s){let e=s-Aa,t=0;for(;t<me.length&&me[t]<e;)t++;t>0&&me.splice(0,t)}function $r(s=Date.now()){Ar(s),me.push(s)}function Mr(s=Date.now()){Ar(s);let e=s-$a,t=0;for(let i=me.length-1;i>=0&&me[i]>=e;i--)t++;let n=me.length,r={lastHour:t,last5h:n,maxPerHour:X.maxPerHour,maxPer5h:X.maxPer5h};return X.maxPerHour&&X.maxPerHour>0&&(r.hourlyRatio=t/X.maxPerHour),X.maxPer5h&&X.maxPer5h>0&&(r.fiveHourRatio=n/X.maxPer5h),r}function Rr(s,e=Date.now()){let t=Mr(e);return s?null:X.maxPerHour&&t.lastHour>=X.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${X.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:X.maxPer5h&&t.last5h>=X.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${X.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function Pr(s=Date.now()){let e=Mr(s),t=X.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var en=new Map;function _r(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function Er(s,e,t,n=Date.now()){let r=en.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},en.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function Dr(s){let e=en.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as ee,mkdirSync as dc,readdirSync as re,readFileSync as Ge,rmSync as uc,writeFileSync as lc}from"fs";import{resolve as G}from"path";import{existsSync as ye,mkdirSync as tn,readFileSync as Ma,readdirSync as Ra,renameSync as Pa,unlinkSync as _a,writeFileSync as ft}from"fs";import{resolve as le,relative as yt}from"path";import{z as J}from"zod";var fe=J.object({id:J.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:J.string().min(1),trigger:J.string().min(1,"procedures must describe when they apply"),inputs:J.array(J.string()).default([]),expected:J.string().optional(),kpis:J.array(J.string()).default([]),owner:J.string().optional(),tags:J.array(J.string()).default([]),status:J.enum(["draft","active","deprecated"]).default("active"),source:J.string().optional(),evidence:J.array(J.string()).default([]),created:J.string().optional(),updated:J.string().optional(),related:J.array(J.string()).default([])});function Ea(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
|
|
88
88
|
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let i=r[1],o=r[2].trim();if(o.startsWith("[")&&o.endsWith("]")){try{t[i]=JSON.parse(o);continue}catch{}t[i]=o.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),t[i]=o}return{meta:t,body:e[2]}}function bt(s){let e=["---"];return e.push(`id: ${s.id}`),e.push(`title: "${s.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${s.trigger.replace(/"/g,'\\"')}"`),s.inputs?.length&&e.push(`inputs: ${JSON.stringify(s.inputs)}`),s.expected&&e.push(`expected: "${s.expected.replace(/"/g,'\\"')}"`),s.kpis?.length&&e.push(`kpis: ${JSON.stringify(s.kpis)}`),s.owner&&e.push(`owner: ${s.owner}`),s.tags?.length&&e.push(`tags: ${JSON.stringify(s.tags)}`),e.push(`status: ${s.status}`),s.source&&e.push(`source: "${s.source.replace(/"/g,'\\"')}"`),s.evidence?.length&&e.push(`evidence: ${JSON.stringify(s.evidence)}`),s.related?.length&&e.push(`related: ${JSON.stringify(s.related)}`),s.created&&e.push(`created: ${s.created}`),s.updated&&e.push(`updated: ${s.updated}`),e.push("---"),e.join(`
|
|
89
|
-
`)}var We=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??le(process.cwd(),".agentx/procedures"),tn(this.baseDir,{recursive:!0})}pathFor(e){return le(this.baseDir,`${e}.md`)}get draftsDir(){return le(this.baseDir,"_drafts")}draftPathFor(e){return le(this.draftsDir,`${e}.md`)}parseFile(e){let t=
|
|
89
|
+
`)}var We=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??le(process.cwd(),".agentx/procedures"),tn(this.baseDir,{recursive:!0})}pathFor(e){return le(this.baseDir,`${e}.md`)}get draftsDir(){return le(this.baseDir,"_drafts")}draftPathFor(e){return le(this.draftsDir,`${e}.md`)}parseFile(e){let t=Ma(e,"utf-8"),{meta:n,body:r}=Ea(t),i=fe.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return i.success?{meta:i.data,body:r.trim(),path:yt(this.baseDir,e)}:null}listDir(e){if(!ye(e))return[];let t=[];for(let n of Ra(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(le(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return ye(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return ye(t)?this.parseFile(t):null}add(e,t){let n=fe.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(ye(r))throw new Error(`Procedure already exists: ${n.id}`);return ft(r,bt(n)+`
|
|
90
90
|
|
|
91
91
|
`+t.trim()+`
|
|
92
92
|
`),{meta:n,body:t.trim(),path:yt(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let i=fe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),o=n!==void 0?n:r.body;return ft(this.pathFor(e),bt(i)+`
|
|
@@ -98,15 +98,15 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ko,maxTokens:512})).content.trim().match(/\[[
|
|
|
98
98
|
`),{meta:n,body:t.trim(),path:yt(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=fe.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return ft(this.pathFor(e),bt(n)+`
|
|
99
99
|
|
|
100
100
|
`+t.body+`
|
|
101
|
-
`)
|
|
102
|
-
`)}function
|
|
101
|
+
`),_a(this.draftPathFor(e)),{meta:n,body:t.body,path:yt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!ye(t))throw new Error(`Draft not found: ${e}`);let n=le(this.draftsDir,"_rejected");tn(n,{recursive:!0}),Pa(t,le(n,`${e}.md`))}isRejected(e){return ye(le(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Da,mkdirSync as Oa,readFileSync as Na,writeFileSync as La}from"fs";import{dirname as Fa,resolve as Ha}from"path";import{z as V}from"zod";var ja=V.object({key:V.string(),count:V.number().int().min(0).default(0),firstSeen:V.string(),lastSeen:V.string(),taskIds:V.array(V.string()).default([]),sampleMessage:V.string().default(""),status:V.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:V.string().optional()}),Ua=V.object({minedThrough:V.string().optional(),candidates:V.array(ja).default([])});function Or(s){return Ha(s,"_candidates.json")}function Ba(s){let e=Or(s);if(!Da(e))return{candidates:[]};try{let t=Ua.safeParse(JSON.parse(Na(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Wa(s,e){let t=Or(s);Oa(Fa(t),{recursive:!0}),La(t,JSON.stringify(e,null,2)+`
|
|
102
|
+
`)}function qa(s,e,t,n,r){let i=s.candidates.find(o=>o.key===e);return i||(i={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(i)),i.taskIds.includes(t)||(i.taskIds.push(t),i.count+=1,n<i.firstSeen&&(i.firstSeen=n),n>i.lastSeen&&(i.lastSeen=n),i.sampleMessage||(i.sampleMessage=r)),i}function Ka(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Ga(s,e,t,n){let r=s.candidates.find(i=>i.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function nn(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Nr(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function sn(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,i=nn(s),o=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Nr(i,nn(a.meta.trigger));d>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=Nr(i,nn(l));u>0&&c.push("title/tags");let g=Math.min(1,d*.7+u*.5);g>=r&&o.push({procedure:a,score:g,reasons:c})}return o.sort((a,c)=>c.score-a.score).slice(0,n)}function rn(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
|
|
103
103
|
`)})].join(`
|
|
104
104
|
|
|
105
|
-
`)}jn();Pt();var an="turn-progress",Lr={progress:nt({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},on=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function Fr(s){return{agent:s.agent,request:on(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:on(e.input,300),...e.result!==void 0?{result:on(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Pt();var Hr="turn-handoff",jr="approval-binding",Ur={nextStep:nt({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},Br={approves:Ee("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},
|
|
106
|
-
`).slice(-3).join(" ")):!1}var
|
|
105
|
+
`)}jn();Pt();var an="turn-progress",Lr={progress:nt({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},on=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function Fr(s){return{agent:s.agent,request:on(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:on(e.input,300),...e.result!==void 0?{result:on(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Pt();var Hr="turn-handoff",jr="approval-binding",Ur={nextStep:nt({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},Br={approves:Ee("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},Ja=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,Wr=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,Qa=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function cn(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Qa.test(e.split(`
|
|
106
|
+
`).slice(-3).join(" ")):!1}var za=/^\s*(yes|yep|yeah|ok(ay)?|sure|go( ahead)?|proceed|do it|please do|confirmed?|approved?|go-ahead|let'?s go|oui|نعم)\b/i;function qr(s){return s.trim().length<=160&&za.test(s)}function Kr(s){return s.trim().length<=160}function Gr(s){return{agent:s.agent,channel:s.channel,request:Ja(s.request,1500),agentReplyEnding:Wr(s.reply,1200)}}function Jr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:Wr(s.previousReply,1200)}}var Xa=5*6e4,Ya=3,Va=12,Za=24*60*6e4,Qr=new Set(["cron","heartbeat","bench","a2a","business"]),ec={observe(){},stop(){}};function zr(s){if(Hn(an)==="off")return ec;let e=s.now??Date.now,t=e(),n=[],r=new Map,i=new Map,o=new Set,a=0,c=!1,d=()=>{let g;for(let[m,f]of i)f>1&&(!g||f>g.times)&&(g={call:m,times:f});return g},l=g=>{if(c)return;c=!0,a=n.length;let m=Fr({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-Va),repeated:d(),trigger:g});xe(an,m,Lr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:g}}).finally(()=>{c=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Xa);return u.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let f of m){if(f?.type!=="tool_use")continue;let T=f.input?JSON.stringify(f.input):"",y={tool:f.name||"tool",input:T};n.push(y),typeof f.id=="string"&&r.set(f.id,y);let v=`${y.tool}(${T})`,I=(i.get(v)??0)+1;i.set(v,I),I>=Ya&&!o.has(v)&&(o.add(v),l("repetition"))}else if(g?.type==="user")for(let f of m){if(f?.type!=="tool_result")continue;let T=r.get(f.tool_use_id);T&&(T.result=Array.isArray(f.content)?f.content.map(y=>typeof y?.text=="string"?y.text:"").join(""):typeof f.content=="string"?f.content:"",f.is_error&&(T.error=!0))}},stop(){clearInterval(u)}}}var dn=new Map,Xr=(s,e,t)=>`${s}\0${e}\0${t}`;function Yr(s){if(Qr.has(s.channel)||!cn(s.reply))return;let e=Xr(s.agent,s.channel,s.chatId);xe(Hr,Gr(s),Ur,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&dn.set(e,{callId:t.callId,at:Date.now()})})}function Vr(s){if(Qr.has(s.channel))return;let e=Xr(s.agent,s.channel,s.chatId),t=dn.get(e);if(t){dn.delete(e);let n=Fn().store;if(n&&Date.now()-t.at<Za)try{n.label(t.callId,"userReply",qr(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!Kr(s.message)||!cn(s.previousReply)||xe(jr,Jr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),Br,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}var ni="requests",si=Symbol("requests.pickup");function $u(s){return Object.assign({channel:ni,chatId:s,sender:"operator"},{[si]:!0})}function ri(s){return!!s&&s[si]===!0}var tc=new Set(["voice","app","dashboard","webrtc"]),nc=new Set(["camera"]),Zr=s=>s.toLowerCase().split("@")[0],sc=new Set(["github","gitlab"]),ei=(s,e)=>s==="whatsapp"?e.replace(/@.*$/,"").replace(/\D/g,""):e.trim().toLowerCase().replace(/^@/,"");function rc(s,e,t){let n=Zr(e);if(s.channels.length&&!s.channels.map(Zr).includes(n))return!1;if(tc.has(n))return!nc.has((t?.name??"").toLowerCase());let r=sc.has(n)?t?.username:t?.id,i=r?ei(n,r):"";return i?s.from.some(o=>{let a=o.trim().toLowerCase(),c=a.indexOf(":");return c>0&&a.slice(0,c)===n&&ei(n,a.slice(c+1))===i}):!1}function ii(s){if(!s)return;let e=n=>typeof n=="string"&&n?n.slice(0,120):void 0,t={name:e(s.sender),id:e(s.senderId),username:e(s.senderUsername)};return t.name||t.id||t.username?t:void 0}function ic(s){return/\btimed? ?out\b|timeout/i.test(s)?"timed out":"failed"}var wt=(s,e=200)=>{let t=s.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t},qe=(s,e,t)=>`${s}\0${e}\0${t}`,ti=class{constructor(e,t,n,r=Date.now){this.store=e;this.settings=t;this.log=n;this.now=r}live=new Map;guard(e,t){try{t()}catch(n){this.log(`[requests] ${e} failed: ${n?.message??n}`)}}liveRequestId(e,t,n){return this.live.get(qe(e,t,n))?.requestId??null}taskStarted(e){e.taskId&&this.guard("capture",()=>{if(!this.settings().enabled)return;let t=this.now(),n=e.resumedFrom?this.store.byLink("run",e.resumedFrom):null,r=qe(e.agentId,e.channel,e.chatId);if(n){this.store.link(n.id,"run",e.taskId,t),n.state==="candidate"?this.store.touch(n.id,t):this.store.progress(n.id,t),this.live.set(r,{requestId:n.id,runId:e.taskId});return}let i=e.pickup&&e.channel===ni?this.store.get(e.chatId):null;if(i&&i.agentId===e.agentId){this.store.link(i.id,"run",e.taskId,t),this.store.touch(i.id,t),this.live.set(r,{requestId:i.id,runId:e.taskId});return}!e.humanRoot||!rc(this.settings(),e.channel,e.sender)||(this.live.set(r,{requestId:`req-${e.taskId}`,runId:e.taskId}),this.store.addCandidate({id:`req-${e.taskId}`,runId:e.taskId,channel:e.channel,chatId:e.chatId,sender:e.sender?.name??e.sender?.username??e.sender?.id??null,agentId:e.agentId,text:e.fullMessage??e.messagePreview,now:t}))})}taskCompleted(e){e.taskId&&this.guard("run end",()=>{let t=qe(e.agentId,e.channel,e.chatId);this.live.get(t)?.runId===e.taskId&&this.live.delete(t);let n=this.store.byLink("run",e.taskId);if(!n)return;let r=this.now();if(!e.interrupted){if(e.error&&e.errorKind!=="cancelled"){let i=ic(e.error);this.store.needsAttention(n.id,`${e.agentId} ${i}: ${wt(e.error)}`,r)&&this.log(`[requests] ${n.id} needs attention: run ${e.taskId} ${i}`);return}n.state==="candidate"?this.store.discardCandidate(n.id):this.store.touch(n.id,r)}})}delegationStarted(e){this.guard("delegation start",()=>{if(!this.settings().enabled)return;let t=this.live.get(qe(e.caller,e.origin.channel,e.origin.chatId));if(!t)return;let n=this.now();this.store.link(t.requestId,"delegation",e.id,n),this.store.progress(t.requestId,n,"waiting_other")})}delegationDone(e,t,n){this.guard("delegation end",()=>{let r=this.store.byLink("delegation",e.id);if(!r)return;let i=this.now(),o=e.peer?`${e.callee} on ${e.peer}`:e.callee;if(t==="done"){this.store.progress(r.id,i);return}let a={error:"failed",timeout:"did not answer in time",lost:"was lost in a restart"}[t];this.store.needsAttention(r.id,`The work handed to ${o} ${a}: ${wt(n)}`,i)&&this.log(`[requests] ${r.id} needs attention: delegation ${e.id} ${t}`)})}cardRaised(e,t){t&&this.guard("card",()=>{if(!this.settings().enabled)return;let n=this.live.get(qe(e.raised_by,t.channel,t.chatId))?.requestId;if(!n)return;let r=this.now();this.store.link(n,"card",e.id,r),this.store.waitOnOwner(n,e.ask,r)})}cardResolved(e){this.guard("card result",()=>{let t=this.store.byLink("card",e.id);if(!t)return;let n=this.now(),r=e.outcome??e.if_silent;e.status==="decided"||r==="approve"?t.state==="waiting_owner"&&this.store.progress(t.id,n):this.store.needsAttention(t.id,`Your answer did not come before the card expired (${wt(e.ask)}); "${r}" was applied`,n)&&this.log(`[requests] ${t.id} needs attention: card ${e.id} expired unanswered`)})}closingNote(e){try{let t=this.store.byLink("delegation",e);return!t||!ws.includes(t.state)?void 0:`This is part of the owner's open request ${t.id}. It stays on their list until it is closed. If it is finished now, close it with agentx_request: {action:"done", id:"${t.id}", evidence:"<link to the proof>"}. If you will not do it, use decline with the reason. If work goes on, leave it open.`}catch{return}}resumeOutcome(e){this.guard("restart",()=>{let t=this.store.byLink("run",e.taskId);if(!t)return;let n=this.now();e.decision==="resumed"?t.state==="candidate"?this.store.touch(t.id,n):this.store.progress(t.id,n):(e.decision==="reported"||e.decision==="resume-failed"||e.decision==="skipped")&&this.store.needsAttention(t.id,`Cut off by a restart and not picked up again (${wt(e.reason)})`,n)&&this.log(`[requests] ${t.id} needs attention: run ${e.taskId} cut off by a restart`)})}};function oi(s,e,t=0){return new Promise((n,r)=>{let i,o=()=>{i=setTimeout(()=>r(Ke(e)),t)},a=()=>{e.removeEventListener("abort",o),i&&clearTimeout(i)};s.then(c=>{a(),n(c)},c=>{a(),r(c)}),e.aborted?o():e.addEventListener("abort",o,{once:!0})})}function Ke(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var $e=class extends Error{constructor(t,n){super(`step "${t}" exceeded its ${Math.round(n/1e3)}s budget`);this.step=t;this.budgetMs=n;this.name="StepBudgetExceeded"}};function ai(s,e,t){return e>0?new Promise((n,r)=>{let i=setTimeout(()=>r(new $e(t,e)),e);i.unref?.(),s.then(o=>{clearTimeout(i),n(o)},o=>{clearTimeout(i),r(o)})}):s}var ac=250,cc=5e3,gc={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3};function ci(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var hi;function Cl(s){hi=s}function Al(){return hi}var di=64*1024,pc=5*60*1e3,hc=3e4,mc=300,Me=".agentx/task-history",fc=30;function Je(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function yc(s,e){let t={};return s?.path?.length&&(t.intentPath=s.path,t.intentPathLabel=s.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function bc(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=gs(s,e,Z().recent());return hs(t,n)}function wc(s,e,t={}){let n;try{n=s.listArticles(e)}catch{return""}if(n.length===0)return"";let r=new Map;for(let l of n){let u=l.meta.type||"untyped",g=r.get(u)||[];g.push(l.meta.title),r.set(u,g)}let i=t.maxArticles??400,o=n.length<=i,a=Array.from(r.entries()).sort().map(([l,u])=>o?`**${l}** (${u.length}) \u2014 ${u.sort().join(" \xB7 ")}`:`**${l}** \u2014 ${u.length} article${u.length===1?"":"s"}`).join(`
|
|
107
107
|
`),c=process.argv[1]||"dist/cli.js",d=s.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
108
108
|
node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${c} wiki facts list --dir ${d}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,"[End Institutional Wiki]"].join(`
|
|
109
|
-
`)}var un=8*1024;function
|
|
109
|
+
`)}var un=8*1024;function xc(s,e){if(s)try{Ts(s)}catch{}return e}function ui(s){if(s.length<=un)return s;let e=s.length-un;return s.slice(0,un)+`\u2026[+${e}]`}function li(s,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let r=typeof n.name=="string"?n.name:"";r&&s.set(r,(s.get(r)??0)+1)}}function Tc(s,e){if(!s||s.length===0)return null;for(let t of s)if((e.get(t)??0)===0)return t;return null}function gi(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),i=Z();if(n==="assistant"&&t.message?.content){for(let o of t.message.content)if(o.type==="tool_use"){let a=o.input!=null?JSON.stringify(o.input):"";i.emit("task:step",{taskId:s,agentId:e,name:"tool_use",action:typeof o.name=="string"?o.name:null,status:"in-flight",inputSummary:a?ui(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let o of t.message.content)if(o.type==="tool_result"){let a=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"";i.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:o.is_error?"error":"ok",outputSummary:a?ui(a):null,at:r})}return}}function Ic(){let s="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
110
110
|
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
111
111
|
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
112
112
|
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
@@ -127,26 +127,26 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ko,maxTokens:512})).content.trim().match(/\[[
|
|
|
127
127
|
\u2192 ${o}(${a})
|
|
128
128
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let i of t.message.content)if(i.type==="tool_result"){let o=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"",a=i.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Je(o,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
|
-
`:""}}var
|
|
130
|
+
`:""}}var pi=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new ss;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new ts;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new gt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Zn(void 0,void 0,"unified"),this.memoryStore=new ns,this.patternStore=new mt,this.rateLimiter=new pt,this.tokenTracker=new Ae,this.messageQueue=new ht,Cr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Yn({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Vn({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let i=this.handoverStore.consumeSummary(t,n);if(!(!i&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:i||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,i=0;for(let[o,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>i&&(r=o,i=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,i]of this.agents)for(let o of i.def.mentions)if(t.includes(o.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,i){let o=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,r);o=sr(g.messages,e.message??""),c=rr(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:o,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await xe(Is,Ss(d),ks,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n},timeoutMs:1500});return!l||l.mode!=="active"||!vs(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,i,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),Z().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,i,o){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${o}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-A4YW6FSK.js"),l=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:i,reason:o,memo:c.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${o}, ${c.durationMs}ms, ${c.memo.length} chars, ${l.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,i]of this.agents)r!==e&&n.push({name:i.def.name,handle:this.getChannelHandle(r,t),role:i.def.systemPrompt?.split(`
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let i=Date.now(),o;try{o=await this.executeInternal(e,t,n,r)}catch(d){o={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),o={...o,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(o);let c=!a&&o.error&&/^timed out before spawn after/.test(o.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${o.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(c){let d=o.error.match(/in step "([^"]+)"/)?.[1]??"start";o={...o,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=o.error?rt(o.error)?"queued":/timed out|timeout/i.test(o.error)?"timed-out":"failed":"completed";os().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-i,resultSummary:o.error?o.error.slice(0,200):o.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return o}async executeInternal(e,t,n,r){let i=ae(e.autonomy),o=i?null:kr().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(o){let p=await o;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let p=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(S=>S.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:p.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="a2a"||c==="mcp"||c==="reminder"||c==="events"||i){let p=Date.now(),h=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let p=Date.now(),h=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-p>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let p=a.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context,queuedAt:e.queuedAt});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:rs(h,S)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,h)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};if(e.queuedAt!==void 0){let p=hr(e.queuedAt);p&&(e.message=`${p}
|
|
132
|
-
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let g={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(g),e.runningTaskId=g.id,this.runningContexts.set(g.id,e.context??{}),e.onStart)try{e.onStart(g.id)}catch{}let m=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:m});let f={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,f);let T=p=>{if(p){f.buffer+=p,f.buffer.length>
|
|
132
|
+
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let g={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(g),e.runningTaskId=g.id,this.runningContexts.set(g.id,e.context??{}),e.onStart)try{e.onStart(g.id)}catch{}let m=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:m});let f={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,f);let T=p=>{if(p){f.buffer+=p,f.buffer.length>di&&(f.buffer=f.buffer.slice(f.buffer.length-di));for(let h of f.subscribers)try{h(p)}catch{}}},y=we();e.taskId=y;let v=new Map,I=(p,h,S)=>{try{Z().emit("task:step",{taskId:y,agentId:e.agentId,name:"pipeline",action:p,status:S,ms:Date.now()-h,at:new Date().toISOString()})}catch{}},O=0,D=!1,C=()=>{D||(D=!0,O&&I("first-event",O,"ok"))},_;if(t){let p=Ic();_=h=>{C();let S=p(h);if(S&&T(S),gi(y,e.agentId,h),li(v,h),r)try{r(h)}catch{}}}else _=p=>{if(C(),gi(y,e.agentId,p),li(v,p),r)try{r(p)}catch{}};let L=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=L?setTimeout(()=>m.abort(new Error(`timed out after ${Math.round(L/1e3)}s`)),L):void 0;E?.unref?.();let F=(a.def.preSpawnTimeoutSec??mc)*1e3,H=setTimeout(()=>{m.abort(new Error(`timed out before spawn after ${Math.round(F/1e3)}s in step "${g.step??"start"}"`))},F);H.unref?.();let j=()=>{H&&clearTimeout(H),H=void 0},B=()=>`task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`,A;m.signal.addEventListener("abort",()=>{let p=Ke(m.signal).message;/^timed out/.test(p)&&(A=g.step??"start"),this.log(`[${e.agentId}] task ${g.id} aborted in step "${g.step??"start"}" \u2014 ${p} ${B()}`)},{once:!0});let k=p=>{g.step=p,this.log(`[${e.agentId}] step ${p} ${B()}`)},b=(p,h,S=0)=>{if(m.signal.aborted)return Promise.reject(Ke(m.signal));k(p),(p==="agent"||p==="workflow-auto-run")&&(j(),O=Date.now());let P=Date.now(),W=ai(h(),gc[p]??0,p);return oi(W,m.signal,S).then(K=>(I(p,P,"ok"),K),K=>{throw I(p,P,"error"),K instanceof $e&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${B()}`),K})},x=async(p,h,S,P=0)=>{try{return await b(p,h,P)}catch(W){if(W instanceof $e)return S();throw W}},N=!1,R=p=>{if(N)return;N=!0,this.runReleases.delete(g.id),E&&clearTimeout(E),j(),a.activeTasks--;let h=a.runningTasks.findIndex(S=>S.id===g.id);h!==-1&&a.runningTasks.splice(h,1),this.runningContexts.delete(g.id),this.taskAborts.delete(g.id),f.done=!0,f.endedAt=new Date;for(let S of f.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}f.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),
|
|
134
|
+
`)}catch{}f.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),pc).unref?.();try{let S=f.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:f.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let K=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:K,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(K=>this.postQueuedResponseToChannel(e.agentId,W,K)).catch(K=>{this.log(`[${e.agentId}] queued message failed: ${K.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(g.id,R),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${B()}`);let w=e.context?.channel||"api",{evaluateRequest:mi,selectRequestContext:fi}=await import("./request-planner-H74KHFGJ.js"),ge=await x("request-gate",()=>mi(e.message,e.agentId,w),()=>({active:!1,preprocess:!1}));ge.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let $=e.context?.chatId||e.context?.group||e.context?.sender||"default",xt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,w,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${$}`),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await x("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,$,e.seedHistory),()=>{});let yi=[...this.sessions.getSession(e.agentId,w,$).messages].reverse().find(p=>p.role==="agent")?.content;Vr({agent:e.agentId,channel:w,chatId:$,message:e.message,previousReply:yi,taskId:y}),this.sessions.addUserMessage(e.agentId,w,$,xt,e.message);let ln=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:w,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(ln).toISOString(),taskId:y,resumeOrigin:gr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:ii(e.context),humanRoot:bs(e.context),pickup:ri(e.context)});let Y,Tt,gn=this.classifier;if(gn&&w!=="a2a"&&!te){k("classify");let p=Date.now();Tt=gn.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:$,agentId:e.agentId}).then(h=>{Y=h||void 0,Y?.path?.length&&(g.intentPath=Y.path.slice()),I("classify",p,"ok")},h=>{this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`),I("classify",p,"error")})}let pn=async p=>{if(!Tt)return;let h;await Promise.race([Tt,new Promise(S=>{h=setTimeout(S,p),h.unref?.()})]),h&&clearTimeout(h)};await pn(ac);let Re=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&Re?.enabled&&!i)try{let p=new fs({baseDir:G(process.cwd(),this.config.workflows.dir)}),h=ys({agentId:e.agentId,channel:w,message:e.message,intentPath:Y?.path},p.list());h&&h.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${Re.mode} reasons=${h.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&h.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let bi=this.wikiHub.getAgentWiki(e.agentId),hn=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),mn=this.memoryStore.buildContext(hn),fn=this.memoryStore.contextFacts(hn),wi=this.patternStore.findRelevant(e.message,e.agentId,5),xi=this.patternStore.buildContext(wi),yn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:h}=await import("./loader-YFVSSYSL.js"),S=await b("skills",()=>p(a.def.workspace));yn=h(S,e.message)}catch{}let U=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,$):void 0;if(U&&this.sessions.isSessionStale(e.agentId,w,$)&&(this.log(`[${e.agentId}] session stale for ${w}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,w,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,w,$);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,w,$)){let p=this.sessions.getTurnCount(e.agentId,w,$);this.log(`[${e.agentId}] max-turns rotation for ${w}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&a.def.tier==="claude-code"){let p=U;await x("rotate",()=>this.maybeRotateForContinuity(e,a,w,$,p),()=>!1)&&(U=void 0)}try{let p=await b("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,$,this.memoryStore));if(p.compacted){let h=p.qualityScore??"?",S=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${$} (quality: ${h}%, ${S} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let P=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let Ti=process.env.AGENTX_CONTEXT_SURGERY==="1",Ii=te?{maxMessages:8,maxChars:2400}:Ti&&ci(w,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,ki=!U&&!te?wc(bi,e.agentId):void 0,Qe=U?void 0:this.sessions.buildHistoryContext(e.agentId,w,$,Ii),Si=U?void 0:this.sessions.getRotationMemo(e.agentId,w,$)??void 0,bn,wn=[];if(this.config.procedures?.injection?.enabled&&!U&&!te)try{let p=new We({baseDir:G(process.cwd(),this.config.procedures.dir)}),h=sn(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){bn=rn(h),wn=h.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of h)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(he&&he.cat)try{let h=this.sessions.getSession(e.agentId,w,$).messages,S=h[0],P=h[h.length-1],W=Qe===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Qe.length}c/${Qe.split(`
|
|
135
135
|
`).length}L`,K=`[${e.agentId}] ${w}:${$} ${W} | session.messages=${h.length}`+(h.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",K)}catch(p){he.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let xn;if(a.def.contextReferences&&!U)try{let p=a.def.workspace,h=this.referencesCache.get(p);if(!h){let[P,W]=await b("references",()=>Promise.all([Et(a.def.workspace),Dt(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[K,pe]=await b("references",()=>Promise.all([Et(process.cwd()),Dt(process.cwd())]));h={refs:K,recipes:pe}}else h={refs:P,recipes:W};this.referencesCache.set(p,h)}let S=as({agentId:e.agentId,intentTags:Y?.path,message:e.message},h.recipes,h.refs);S.cards.length>0&&(xn=is(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let Tn=this.sessions.getCrossSessionSummary(e.agentId,w,$,e.message),In,ze=nr(e.message);if(ze)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:$,lookbackDays:ze.lookbackDays,limit:12});if(p.turns.length>0){let h=[`[Long-memory recall \u2014 last ${ze.lookbackDays}d on this chat (cue-triggered)]`],S=[...p.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,K=P.role==="user"?P.senderName||"User":P.senderName||"Agent";h.push(`${W} ${K}: ${P.content}`)}p.hasMore&&h.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),In=h.join(`
|
|
136
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${ze.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let
|
|
137
|
-
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",
|
|
136
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${ze.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let vi=te?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",kn,Sn,vn=!1;if(vi==="planner"&&!ge.active&&w!=="voice"&&w!=="desktop"){try{let{planContext:p}=await import("./context-planner-JU7CNXCB.js"),h=await b("plan-context",()=>p({agentId:e.agentId,channel:w,chatId:$,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));h?(vn=!0,kn=h.sessionHistory,mn=h.memoryContext,fn=h.memoryFacts,Tn=h.crossChatContext,Sn=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}vn&&U&&(this.sessions.clearClaudeSessionId(e.agentId,w,$),U=void 0)}let It=`${e.agentId}:${w}:${$}`,Xe=Gn(e.message);Xe&&(Xe==="default"?(this.activeSouls.delete(It),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(It,Xe),this.log(`[${e.agentId}] Soul switched to: ${Xe}`)));let Ci=this.activeSouls.get(It),Ai=qn(a.def.workspace,Ci),$i=Kn(Ai),Mi=this.agentMemory.indexMarkdown(e.agentId),Ri=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
137
|
+
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",Pi=kc(a.def.richMessages,w),Cn="";if(a.def.workspace){let p=G(a.def.workspace,"CLAUDE.md");if(ee(p))try{let h=Ge(p,"utf-8");Cn=`[Project CLAUDE.md]
|
|
138
138
|
${h.length>4e3?h.slice(0,4e3)+`
|
|
139
139
|
|
|
140
140
|
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let Ye=e.context?.runbookPath,kt=[];if(Ye&&ee(Ye)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,S=4e3,P=16e3;for(let W of p){if(h>=P)break;let K=G(Ye,W);if(ee(K))try{let pe=Ge(K,"utf-8"),M=pe.length>S?pe.slice(0,S)+`
|
|
141
141
|
|
|
142
142
|
[${W} truncated to ${S} bytes]`:pe;kt.push(`[Project Runbook \u2014 ${W} from ${Ye}]
|
|
143
|
-
${M}`),h+=M.length}catch{}}}let
|
|
143
|
+
${M}`),h+=M.length}catch{}}}let _i=kt.length>0?kt.join(`
|
|
144
144
|
|
|
145
|
-
`):"",St=[a.def.systemPrompt||"",
|
|
145
|
+
`):"",St=[a.def.systemPrompt||"",Ri,Pi,Cn,_i,$i||"",Mi||""].filter(p=>p.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,vt={channel:w,chatId:$,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:a.def.systemPrompt,sender:xt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||
|
|
148
|
-
`),P=!1)},pe=h?S:S?(q,z)=>{K(),S(q,z)}:void 0,M=await b("agent",()=>Zs(a.def,
|
|
147
|
+
`)||void 0,vt={channel:w,chatId:$,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:a.def.systemPrompt,sender:xt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||ci(w,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:te?void 0:xi||void 0,procedureContext:bn,references:xn,skillInjection:yn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:kn??Qe,memoryContext:mn||void 0,crossChatContext:Tn||void 0,longMemoryRecall:In||void 0,wikiContext:ki,handoverNote:this.buildHandoverNote(e.agentId,w,$),rotationMemo:Si,eventDigest:U?void 0:bc(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=xs(w,!U,a.def.richMessages);return p?xc(a.def.workspace,p):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},Ve=ge.active&&ge.preprocess?await x("select-context",()=>fi(vt),()=>({input:vt,excluded:[]})):{input:vt,excluded:[]};Ve.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ve.excluded.join(", ")}`);let Ze=lr(Ve.input,te?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Ei=es(Ze,{memory:fn,procedures:wn,wikiContext:Ve.input.wikiContext}),Ct=(Ze?.length??0)+(St?.length??0)+(e.message?.length??0),et={history:Ze?.length??0,sysPrompt:St?.length??0,message:e.message?.length??0},An=_r(e.agentId,w,$);Er(An,Ct,et);let $n=Dr(An);$n&&this.log(`[${e.agentId}] ${$n}`),Ct>16e3&&this.log(`[${e.agentId}] large context for ${w}:${$}: ${Ct} bytes (history=${et.history}, sysPrompt=${et.sysPrompt}, message=${et.message})`);let At,Mn=Un(a.def.tier,this.config.decisions.routing);if(!e.model&&Mn&&(!ge.active||ge.preprocess))try{let{routeTaskModel:p}=await import("./routing-3RSG7SKW.js"),h=await b("route-model",()=>p({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,w,$),cheapModel:Mn}));h.downgraded&&(At=h.model,this.log(`[${e.agentId}] ${h.reason}`))}catch{}let Di={...e,systemPromptAppend:St,...At?{model:At}:{}},ne,Rn=!1,Pn=zr({agent:e.agentId,request:e.message,taskId:y,budgetMinutes:a.def.maxExecutionMinutes??20}),Oi=_;_=p=>{Pn.observe(p),Oi?.(p)};try{let p=this.workflowAutoRunner;if(be&&p){let q=be;try{let z=await b("workflow-auto-run",()=>p({workflowId:q.workflowId,agentId:e.agentId,channel:w,chatId:$,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:w,chatId:$,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),ne={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},ne}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(a.def.tier==="claude-code"){k("dispatch-gate");let q=a.def.persistentProcess?at():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:w,chatId:$}),oe=!!U||z,se=[Sr(oe),Rr(oe)].find(_e=>_e&&_e.abort);if(se){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${se.reason}`);let _e={content:"",error:se.message,duration:0};if(!t){f.buffer=`[error] ${se.message}`;for(let Ni of f.subscribers)try{Ni(f.buffer)}catch{}}return ne=_e,_e}$r();let Pe=Pr();Pe&&this.log(`[${e.agentId}] ${Pe}`)}let h=a.def.tier==="claude-code",S=h?t:(q,z)=>{q&&T(q),t&&t(q,z)},P=!1,W=h?n:q=>{q&&(P?T(q):(T(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},K=()=>{P&&(T(`
|
|
148
|
+
`),P=!1)},pe=h?S:S?(q,z)=>{K(),S(q,z)}:void 0,M=await b("agent",()=>Zs(a.def,Di,this.providers,pe,Ze,U,_,m.signal,W),hc);if(!M.error){let q=Tc(a.def.toolUseRequired,v);if(q){let z=Array.from(v.entries()).map(([oe,tt])=>`${oe}=${tt}`).join(", ")||"none";M.error=`tool_required_not_called: ${q} (invoked: ${z})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let $t=this.interruptedRuns.get(g.id);$t&&(M.content="",M.error=$t,M.errorKind="interrupted"),ne=M;let ie=M.usage?dr(M.usage):void 0;if(Rn=!0,Z().emit("task:completed",{taskId:y,agentId:e.agentId,channel:w,chatId:$,durationMs:Date.now()-ln,error:M.error||void 0,errorKind:M.error?M.errorKind:void 0,interrupted:$t?!0:void 0,inputTokens:ie?.inputTokens,outputTokens:ie?.outputTokens,cacheReadTokens:ie?.cacheReadTokens,cacheCreateTokens:ie?.cacheCreateTokens,tier2InputTokens:ie?.tier2InputTokens,tier2OutputTokens:ie?.tier2OutputTokens,tier2CacheReadTokens:ie?.tier2CacheReadTokens,tier2CacheCreateTokens:ie?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:ge.arm,numTurns:M.numTurns,injectedContext:Ei,finalResponse:M.content||void 0,billedModel:M.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let q=M.error?`[error] ${M.error}`:M.content;f.buffer=q;for(let z of f.subscribers)try{z(q)}catch{}}if(M.error)a.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,$,M.content),Yr({agent:e.agentId,channel:w,chatId:$,request:e.message,reply:M.content,taskId:y}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,$,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,$,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,$,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,w,$,M.usage,M.contextTokens),M.usage){let se=M.contextTokens,Pe=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(se??Pe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${$}: context=${se??"n/a"} tokens (cumulative turn total=${Pe}) \u2014 next turn will rotate`)}if(zn({channel:w,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await pn(cc);try{let se=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:se,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
|
-
Agent: ${M.content}`,meta:
|
|
151
|
-
`)}export{Cs as a,
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
Agent: ${M.content}`,meta:yc(Y,e.context)})}catch{}Xn(e.agentId,e.message,M.content,{channel:w,chatId:$,sender:xt},this.memoryStore).catch(()=>{}),br(e.agentId,e.message,M.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=M.billedModel||e.model||a.def.model,oe=e.context?.channel,tt=oe&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${oe}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,M.duration||0,M.usage,e.message.length,M.content.length,!1,z,oe,tt),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${B()}`)}return M}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let h=it(p.message);return ne={content:"",error:ot(h),errorKind:h.kind},ne}finally{if(Pn.stop(),!Rn)try{Z().emit("task:completed",{taskId:y,agentId:e.agentId,channel:c,chatId:d,durationMs:Date.now()-g.startedAt.getTime(),error:ne?.error||(m.signal.aborted?Ke(m.signal).message:"run ended before completion"),errorKind:ne?.errorKind,interrupted:this.interruptedRuns.has(g.id)?!0:void 0,at:new Date().toISOString()})}catch{}R(ne)}}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:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=G(process.cwd(),Me,this.safe(e.agentId),t);ee(n)||dc(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);lc(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let i=new Array(t).fill(0),o=n-t*36e5,a=G(process.cwd(),Me,this.safe(e));if(!ee(a))return this.sparklineCache.set(e,{hourly:i,at:n}),i;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let g=G(a,u);if(ee(g))try{for(let m of re(g)){if(!m.endsWith(".json"))continue;let f=m.split("-")[0],T=parseInt(f,10);if(!Number.isFinite(T)||T<o||T>n)continue;let y=Math.floor((n-T)/36e5),v=t-1-y;v>=0&&v<t&&i[v]++}}catch{}}return this.sparklineCache.set(e,{hourly:i,at:n}),i}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Me);if(!ee(e))return 0;let t=0;for(let n of re(e)){let r=G(e,n),i;try{i=re(r).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse()}catch{continue}e:for(let o of i){let a=G(r,o),c;try{c=re(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ge(G(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let g=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=fc){let t=G(process.cwd(),Me);if(!ee(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let i of re(t)){let o=G(t,i),a;try{a=re(o)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{uc(G(o,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Me,this.safe(e));if(!ee(n))return[];let r=re(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse(),i=[];for(let o of r){if(i.length>=t)break;let a=G(n,o),c;try{c=re(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(i.length>=t)break;try{let l=JSON.parse(Ge(G(a,d),"utf-8")),{transcript:u,responseText:g,...m}=l;i.push(m)}catch{}}}return i}getTaskRecord(e,t){let n=G(process.cwd(),Me,this.safe(e));if(!ee(n))return null;let r=this.safe(t),i=re(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse();for(let o of i){let a=G(n,o,`${r}.json`);if(ee(a))try{return JSON.parse(Ge(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ms();if(!r)return;let i=t?.channel,o=t?.chatId;if(!i||!o||n.errorKind==="cancelled"||n.errorKind==="interrupted"||rt(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:i,chatId:o,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(o=>o.id===t.taskId);else if(t.channel&&t.chatId){let o=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=o.length===1?o[0]:void 0}if(!r)return null;let i=this.runningContexts.get(r.id);return i?{taskId:r.id,context:i}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let i;for(let o of r.runningTasks)o.channel!==t||o.chatId!==n||(!i||o.startedAt>i.startedAt)&&(i=o);return i?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let i=0;for(let[o,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(o,r)&&i++;return i}queueFollowUp(e,t,n,r={}){let i=this.taskAborts.get(e);if(!i)return null;let{agentId:o,channel:a,chatId:c,originalMessage:d}=i,l=i.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(o,a,c,d)),this.messageQueue.enqueue(o,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(o,a,c),m=!1;if(r.replace){let f=r.reason||`replaced by follow-up from ${n}`;try{i.controller.abort(new Error(f))}catch{}this.log(`[${o}] task ${e} replaced by follow-up \u2014 ${f}`),m=!0}else this.log(`[${o}] follow-up queued for task ${e} (pending=${g}${u?", edited cancelled turn":""})`);return{agentId:o,channel:a,chatId:c,replaced:m,edited:u,pending:g}}async continueFinishedTask(e,t,n,r,i={}){let o=this.getTaskRecord(e,t);if(!o)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(o.channel!=="cron"||!o.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=o.channel,c=o.chatId;return new Promise(d=>{let l=!1,u=g=>{l||(l=!0,d(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:i.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{rt(g.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?u({ok:!1,status:500,error:g.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>u({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function kc(s,e){return s===!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(`
|
|
151
|
+
`)}export{Cs as a,Pc as b,$s as c,Ji as d,Ms as e,_s as f,Wc as g,Jc as h,Qc as i,lo as j,Xs as k,fo as l,yo as m,bo as n,Zs as o,gt as p,pt as q,qo as r,kd as s,Sd as t,Yt as u,Z as v,wr as w,ea as x,ra as y,Ir as z,Ud as A,kr as B,We as C,Ba as D,Wa as E,qa as F,Ka as G,Ga as H,sn as I,$u as J,ti as K,Cl as L,Al as M,yc as N,bc as O,wc as P,un as Q,ui as R,li as S,Tc as T,gi as U,pi as V,kc as W};
|
|
152
|
+
//# sourceMappingURL=chunk-NOAAK2XI.js.map
|