agentix-cli 0.71.0 → 0.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-PRD5JNO4.js → App-LXQUWRY6.js} +2 -2
- package/dist/{ChatApp-BKS6OJ3L.js → ChatApp-PCVXNFEJ.js} +2 -2
- package/dist/{agent-QF2JQ72Z.js → agent-AJOPKBST.js} +2 -2
- package/dist/{board-dashboard-AROMOAKS.js → board-dashboard-A56FT4U6.js} +576 -219
- package/dist/board-dashboard-A56FT4U6.js.map +1 -0
- package/dist/chunk-5QCFJ5GO.js +156 -0
- package/dist/chunk-5QCFJ5GO.js.map +1 -0
- package/dist/{chunk-AAA6NGY5.js → chunk-6AUW7HPX.js} +2 -2
- package/dist/{chunk-JBVABB26.js → chunk-73MVBAFG.js} +2 -2
- package/dist/chunk-7XB2CVC3.js +2 -0
- package/dist/chunk-7XB2CVC3.js.map +1 -0
- package/dist/{chunk-XJQNIFZ4.js → chunk-B45SJSFP.js} +2 -2
- package/dist/{chunk-IK2XG65P.js → chunk-C555JABY.js} +2 -2
- package/dist/{chunk-4XBYHKYG.js → chunk-D5BPN3JR.js} +2 -2
- package/dist/{chunk-HXW4NAWF.js → chunk-GULZIVVA.js} +2 -2
- package/dist/{chunk-BO4WLXXC.js → chunk-JKGWQNUL.js} +2 -2
- package/dist/{chunk-EMRQ6W5J.js → chunk-L43CVWCL.js} +2 -2
- package/dist/chunk-MQ5SG3VF.js +15 -0
- package/dist/chunk-MQ5SG3VF.js.map +1 -0
- package/dist/chunk-MYVHVJWZ.js +2 -0
- package/dist/chunk-MYVHVJWZ.js.map +1 -0
- package/dist/{chunk-SFWA67GQ.js → chunk-PHG5FJOC.js} +2 -2
- package/dist/{chunk-OTMDMGHE.js → chunk-PNTFOROF.js} +65 -65
- package/dist/chunk-PNTFOROF.js.map +1 -0
- package/dist/{chunk-DJMUP6TK.js → chunk-PVNDAEWC.js} +2 -2
- package/dist/{chunk-6LTD7XL5.js → chunk-RF3HJHFP.js} +2 -2
- package/dist/{chunk-RCKICCTT.js → chunk-RR2P5FLW.js} +2 -2
- package/dist/{chunk-K6CHA6JJ.js → chunk-U75OD25W.js} +2 -2
- package/dist/{chunk-3C2SQDIH.js → chunk-UXH6IX7V.js} +251 -224
- package/dist/chunk-UXH6IX7V.js.map +1 -0
- package/dist/{chunk-5Y7QRFSL.js → chunk-WMGB25WL.js} +2 -2
- package/dist/{chunk-WLX4766Y.js → chunk-XBLL3T2F.js} +2 -2
- package/dist/{chunk-MT3BD6WG.js → chunk-XN4ZOLVQ.js} +186 -183
- package/dist/chunk-XN4ZOLVQ.js.map +1 -0
- package/dist/{chunk-SELIVR6U.js → chunk-Y2425AFZ.js} +2 -2
- package/dist/{chunk-D233M73Q.js → chunk-ZSIWNIUK.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-V7YJR55E.js +2 -0
- package/dist/{config-UY5K6SCL.js → config-HI4ECCSU.js} +2 -2
- package/dist/config-mutator-OHXSKALT.js +2 -0
- package/dist/doctor-IAY3GUHJ.js +2 -0
- package/dist/{facts-X44PF73W.js → facts-2K6UX5GD.js} +6 -6
- package/dist/facts-2K6UX5GD.js.map +1 -0
- package/dist/index.d.ts +296 -17
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/opencode-launch-ECMEY2QZ.js +2 -0
- package/dist/opencode-launch-ECMEY2QZ.js.map +1 -0
- package/dist/opencode-process-ENS4MXHM.js +2 -0
- package/dist/program-IQVDNQS6.js +2 -0
- package/dist/{promote-YLKNYYIU.js → promote-PWUCBE57.js} +2 -2
- package/dist/{query-CVRXEG43.js → query-U6QKWGAG.js} +2 -2
- package/dist/registry-SYY47NXH.js +2 -0
- package/dist/{request-planner-76NCBYBW.js → request-planner-BXU5GECQ.js} +2 -2
- package/dist/{review-candidates-ZUXMX6BJ.js → review-candidates-TVVYKJ2K.js} +2 -2
- package/dist/{routing-EIGWDKH7.js → routing-O2WE73C7.js} +2 -2
- package/dist/schedule-tool-5CSP47M4.js +2 -0
- package/dist/scheduler-FBG6Q5L7.js +2 -0
- package/dist/{seat-QOY6FA4N.js → seat-OR5IXRA5.js} +2 -2
- package/dist/{select-JHKHO5BO.js → select-LN4TSDRS.js} +2 -2
- package/dist/{set-enabled-DVJIUOKX.js → set-enabled-6H3YQOVB.js} +2 -2
- package/dist/{tool-WKSLNQ6H.js → tool-U4PSEWS2.js} +2 -2
- package/dist/wiki-YQFIR7HR.js +2 -0
- package/dist/wiki-YQFIR7HR.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-AROMOAKS.js.map +0 -1
- package/dist/chunk-3C2SQDIH.js.map +0 -1
- package/dist/chunk-AHOGFVHA.js +0 -15
- package/dist/chunk-AHOGFVHA.js.map +0 -1
- package/dist/chunk-JU67IZLC.js +0 -131
- package/dist/chunk-JU67IZLC.js.map +0 -1
- package/dist/chunk-MT3BD6WG.js.map +0 -1
- package/dist/chunk-NMFXY3QU.js +0 -2
- package/dist/chunk-NMFXY3QU.js.map +0 -1
- package/dist/chunk-OTMDMGHE.js.map +0 -1
- package/dist/client-UPBQVXYM.js +0 -2
- package/dist/config-mutator-7KOSRAQF.js +0 -2
- package/dist/doctor-GFPSIJGB.js +0 -2
- package/dist/facts-X44PF73W.js.map +0 -1
- package/dist/program-XMGZOYX3.js +0 -2
- package/dist/registry-HZL363TA.js +0 -2
- package/dist/schedule-tool-PSZMP7C4.js +0 -2
- package/dist/scheduler-S24PXNB6.js +0 -2
- package/dist/wiki-PTXUMSIR.js +0 -2
- /package/dist/{App-PRD5JNO4.js.map → App-LXQUWRY6.js.map} +0 -0
- /package/dist/{ChatApp-BKS6OJ3L.js.map → ChatApp-PCVXNFEJ.js.map} +0 -0
- /package/dist/{agent-QF2JQ72Z.js.map → agent-AJOPKBST.js.map} +0 -0
- /package/dist/{chunk-AAA6NGY5.js.map → chunk-6AUW7HPX.js.map} +0 -0
- /package/dist/{chunk-JBVABB26.js.map → chunk-73MVBAFG.js.map} +0 -0
- /package/dist/{chunk-XJQNIFZ4.js.map → chunk-B45SJSFP.js.map} +0 -0
- /package/dist/{chunk-IK2XG65P.js.map → chunk-C555JABY.js.map} +0 -0
- /package/dist/{chunk-4XBYHKYG.js.map → chunk-D5BPN3JR.js.map} +0 -0
- /package/dist/{chunk-HXW4NAWF.js.map → chunk-GULZIVVA.js.map} +0 -0
- /package/dist/{chunk-BO4WLXXC.js.map → chunk-JKGWQNUL.js.map} +0 -0
- /package/dist/{chunk-EMRQ6W5J.js.map → chunk-L43CVWCL.js.map} +0 -0
- /package/dist/{chunk-SFWA67GQ.js.map → chunk-PHG5FJOC.js.map} +0 -0
- /package/dist/{chunk-DJMUP6TK.js.map → chunk-PVNDAEWC.js.map} +0 -0
- /package/dist/{chunk-6LTD7XL5.js.map → chunk-RF3HJHFP.js.map} +0 -0
- /package/dist/{chunk-RCKICCTT.js.map → chunk-RR2P5FLW.js.map} +0 -0
- /package/dist/{chunk-K6CHA6JJ.js.map → chunk-U75OD25W.js.map} +0 -0
- /package/dist/{chunk-5Y7QRFSL.js.map → chunk-WMGB25WL.js.map} +0 -0
- /package/dist/{chunk-WLX4766Y.js.map → chunk-XBLL3T2F.js.map} +0 -0
- /package/dist/{chunk-SELIVR6U.js.map → chunk-Y2425AFZ.js.map} +0 -0
- /package/dist/{chunk-D233M73Q.js.map → chunk-ZSIWNIUK.js.map} +0 -0
- /package/dist/{client-UPBQVXYM.js.map → client-V7YJR55E.js.map} +0 -0
- /package/dist/{config-UY5K6SCL.js.map → config-HI4ECCSU.js.map} +0 -0
- /package/dist/{config-mutator-7KOSRAQF.js.map → config-mutator-OHXSKALT.js.map} +0 -0
- /package/dist/{doctor-GFPSIJGB.js.map → doctor-IAY3GUHJ.js.map} +0 -0
- /package/dist/{program-XMGZOYX3.js.map → opencode-process-ENS4MXHM.js.map} +0 -0
- /package/dist/{promote-YLKNYYIU.js.map → program-IQVDNQS6.js.map} +0 -0
- /package/dist/{query-CVRXEG43.js.map → promote-PWUCBE57.js.map} +0 -0
- /package/dist/{registry-HZL363TA.js.map → query-U6QKWGAG.js.map} +0 -0
- /package/dist/{routing-EIGWDKH7.js.map → registry-SYY47NXH.js.map} +0 -0
- /package/dist/{request-planner-76NCBYBW.js.map → request-planner-BXU5GECQ.js.map} +0 -0
- /package/dist/{review-candidates-ZUXMX6BJ.js.map → review-candidates-TVVYKJ2K.js.map} +0 -0
- /package/dist/{schedule-tool-PSZMP7C4.js.map → routing-O2WE73C7.js.map} +0 -0
- /package/dist/{scheduler-S24PXNB6.js.map → schedule-tool-5CSP47M4.js.map} +0 -0
- /package/dist/{seat-QOY6FA4N.js.map → scheduler-FBG6Q5L7.js.map} +0 -0
- /package/dist/{wiki-PTXUMSIR.js.map → seat-OR5IXRA5.js.map} +0 -0
- /package/dist/{select-JHKHO5BO.js.map → select-LN4TSDRS.js.map} +0 -0
- /package/dist/{set-enabled-DVJIUOKX.js.map → set-enabled-6H3YQOVB.js.map} +0 -0
- /package/dist/{tool-WKSLNQ6H.js.map → tool-U4PSEWS2.js.map} +0 -0
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
import{a as Yn,b as Vn,d as es,f as
|
|
2
|
-
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),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()}},Nt=class{constructor(e=Oo,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=Eo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[S])=>b.localeCompare(S))])).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 o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,S])=>!S.connection.busy);if(!b)throw new ce("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new Ot(e,this.launchProcess)}}catch{throw new ce("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,g=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let T=new Promise((D,M)=>{i.failTurn=M,i.notify=(C,_)=>{if(_?.threadId!==l)return;let N=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...N?{item:{...N,type:E[N.type]||N.type}}:{}}),C==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let L=_.tokenUsage.last,F=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?D():M(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return T.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await T,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new ce(b.message);return{content:c,codexSessionId:l,usage:u,error:b.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(y),e.signal?.removeEventListener("abort",f),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Ts=new Nt;import{execFile as Yo}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as Os,readFileSync as Ns,rmSync as Ls}from"fs";import{join as it}from"path";import{tmpdir as Fs}from"os";function st(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,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function rt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ks=null;function ot(){return ks}function Tc(s){ks=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function No(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 ke=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Is=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=No(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 ke(`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 ke(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}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 o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}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 o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}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 Lo}from"child_process";import{existsSync as Fo,readFileSync as Ho}from"fs";import{resolve as jo}from"path";function Uo(s){let e=jo(s,"CLAUDE.md");if(!Fo(e))return null;try{let t=Ho(e,"utf8");return qn(t)}catch{return null}}var Bo=20*60*1e3,Wo=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 qo(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 Ss=class{constructor(e={}){this.opts=e}spawn(e,t){return new Lt(e,t,this.opts)}},Lt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Lo(r,o,{cwd:t.workspace,env:De(qo({...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:Uo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();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 o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
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 i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}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"}}};
|
|
1
|
+
import{a as Yn,b as Vn,d as es,f as tt,l as gs,r as ps,x as hs,z as ms}from"./chunk-RF3HJHFP.js";import{a as Xn}from"./chunk-WP6KLXTP.js";import{a as $t}from"./chunk-N6EWZGIX.js";import{b as Zn}from"./chunk-DP7RTNDM.js";import{a as ls}from"./chunk-W4YR2RO2.js";import{b as ns,c as Pt,d as rs,e as os,h as is}from"./chunk-WMGB25WL.js";import{a as zn}from"./chunk-RR2P5FLW.js";import{a as Mt,b as ts}from"./chunk-J3SOEFRE.js";import{a as Rt,b as ss}from"./chunk-SIU6STB2.js";import{e as as,i as cs,j as ds,k as us}from"./chunk-X5C5W3E4.js";import{a as Ln}from"./chunk-U75OD25W.js";import{a as Fn,c as Hn}from"./chunk-MYVHVJWZ.js";import{a as jn,b as Un,c as Bn,d as Wn,f as Kn}from"./chunk-DWADWDMU.js";import{a as qn,b as Gn}from"./chunk-23A5K5UW.js";import{g as Jn,h as Qn}from"./chunk-6AUW7HPX.js";import{a as et,c as Ee}from"./chunk-2GIDVZ4H.js";import{q as Dn,t as On,v as xe,w as Nn}from"./chunk-PVNDAEWC.js";import{a as _e,b as Ze,f as At}from"./chunk-72SZI2UW.js";import{a as we,b as vt}from"./chunk-FCPTN6NF.js";import{c as $n,d as Mn}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{C as Io,d as Rn,e as ie,f as Pn,g as _n,h as Ct,u as En}from"./chunk-MQ5SG3VF.js";Nn();At();var fs="session-continuity",ys={continues:_e("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:_e("Does the new request refer to something stated earlier in the conversation?")};function bs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:_t(s.message,1200),previousRequest:s.previousMessage?_t(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>_t(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ws(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 _t(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as at}from"execa";import{spawn as So}from"node:child_process";import{createHash as vo}from"node:crypto";import{createInterface as Co}from"node:readline";var ae=class extends Error{},Ao=s=>So("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Et=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(),Co({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
|
+
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),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()}},Dt=class{constructor(e=Ao,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=vo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[v])=>b.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,v])=>!v.connection.busy);if(!b)throw new ae("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new Et(e,this.launchProcess)}}catch{throw new ae("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,g=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let k=new Promise((D,E)=>{i.failTurn=E,i.notify=(C,P)=>{if(P?.threadId!==l)return;let N=P.item,_={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...P,type:C.replace("/","."),...N?{item:{...N,type:_[N.type]||N.type}}:{}}),C==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=P.delta,e.onDelta?.(P.delta,c)),C==="thread/tokenUsage/updated"){let L=P.tokenUsage.last,F=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(P.turn.status==="completed"?D():E(new Error(P.turn.error?.message||`Codex turn ${P.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new ae(b.message);return{content:c,codexSessionId:l,usage:u,error:b.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(y),e.signal?.removeEventListener("abort",f),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},xs=new Dt;import{execFile as Wo}from"child_process";import{StringDecoder as Le}from"string_decoder";import{mkdtempSync as Ds,readFileSync as Os,rmSync as Ns}from"fs";import{join as ot}from"path";import{tmpdir as Ls}from"os";function nt(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,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function st(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Ts=null;function rt(){return Ts}function cc(s){Ts=s}function De(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function $o(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"}},ks=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=De(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=$o(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 i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=De(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=De(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=De(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 o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=De(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 o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}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 Mo}from"child_process";import{existsSync as Ro,readFileSync as Po}from"fs";import{resolve as _o}from"path";function Eo(s){let e=_o(s,"CLAUDE.md");if(!Ro(e))return null;try{let t=Po(e,"utf8");return Kn(t)}catch{return null}}var Do=20*60*1e3,Oo=5e3,Oe=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ne=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function No(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 Is=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ot(e,t,this.opts)}},Ot=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Mo(r,o,{cwd:t.workspace,env:Ee(No({...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:Eo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();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 o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
|
+
`);let a=e.deadlineMs??Do,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Oe(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 Ne(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 o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Oo);this.child.once("exit",()=>{clearTimeout(o),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 i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}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"}}};Ct();import{resolve as Ss,join as vs}from"path";vt();var Lo=4e3;function Cs(s){try{let e=vs(Ss(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,Lo):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
|
|
10
|
-
`)}return{error:
|
|
9
|
+
`),null}}function xc(s){let e=vs(Ss(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 o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}Ct();var Fo=50,Ho=6*60*60*1e3,Nt=null,ke=new Map;function Sc(s){Nt=s===null?null:String(s)}function jo(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 $s(s,e,t){if(!ie(s))return{args:[]};if(!Nt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:jo(Nt,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 Ms(s,e){return!ie(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 Uo(s){for(let[e,t]of ke)s-t.at>Ho&&ke.delete(e)}function Bo(s,e){let t=Date.now();Uo(t);let n=ke.get(s)??{at:t,blocks:[]};n.blocks.length<Fo&&n.blocks.push(e),n.at=t,ke.set(s,n)}function Rs(s){if(!s)return[];let e=ke.get(s);return ke.delete(s),e?.blocks??[]}function As(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function vc(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 o=Rn.safeParse(e.level),i=o.success?Pn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.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 Cs({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&&Bo(e.taskId,l),{stdout:As(`[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(o){return{stdout:As(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}var Ko=5e3;function G(s){let e=nt(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
|
+
`)}return{error:st(e),errorKind:e.kind}}function Fs(){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 it(){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 Ps(){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 de(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.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}`:"";o.push(`\u2022 ${c.name}${d}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.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
|
-
`)}function
|
|
12
|
+
`)}function Hs(s,e,t,n,r,o,i=[]){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"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Lt(s,e){return!e||e.trim().length===0?s:`[System]
|
|
13
13
|
${e.trim()}
|
|
14
14
|
|
|
15
15
|
[User]
|
|
16
|
-
${s}`}function
|
|
17
|
-
`))if(i.trim())try{let a=JSON.parse(i);t=
|
|
18
|
-
`)}function
|
|
19
|
-
`);L=I.pop()||"";for(let w of I)if(w.trim())try{let
|
|
16
|
+
${s}`}function qo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s.model;return i&&o.push("--model",i),r&&o.push("--session",r),s.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Lt(e,n)),o}function Go(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 _s(s){return JSON.stringify(s)}function js(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${_s(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(_s).join(",")}]`]}function Us(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...js()),i||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"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Lt(e,r)),a}function ct(s,e){let t=et(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(o=>o.split(":")).filter(Boolean))).join(":"),Ft(t,e)}function Ft(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 Jo(s,e){let t=ct(s,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...n.mcp||{}};for(let[i,a]of Object.entries(s.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:r}),t}function Qo(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 ce(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Ht(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:ce(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ce(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ce(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ce(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Ht(n,e+1);if(r)return r}}function Bs(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 jt(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=jt(t,e+1);if(n)return n}}}function zo(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
|
|
17
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=Ht(a)||t,n=Bs(a)||n,r=jt(a)||r,o=Ws(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function Ws(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return Es(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return Es(e)}}}function Es(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 Xo(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 Ut(s,e,t,n,r){let o=Xo(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${s} via=${r} model=${i} perm=${o.summary}${a}
|
|
18
|
+
`)}function Yo(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 Vo(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 Ks(s,e,t,n,r){let o=Date.now(),i=de(s,e,t),a=Gs(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=Hs(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Ut(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:g,exitCode:f,killed:y}=await new Promise(v=>{let k=Ee(Ft(et(s.workspace),e),s.billing),D=!1,E=Wo("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...k,HOME:k.HOME||"/home/"+(k.USER||"user")}},(C,P,N)=>{v({stdout:P||"",stderr:N||"",exitCode:C?C.code??1:0,killed:D})});if(E.stdin?.end(),r){let C=()=>{D=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{E.kill("SIGTERM")}catch{}setTimeout(()=>{try{E.killed||E.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?C():r.addEventListener("abort",C,{once:!0})}});if(y)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&f!==0){let v,k=Date.now()-o;return f===143&&k<l-Ko?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(k/1e3)}s, before its ${Math.round(l/6e4)}m time limit`,errorKind:"interrupted",duration:k}:(f===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.`:f==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?v=Fs():v=g?.trim()||`Claude Code exited with code ${f}`,{content:"",...G(v),duration:Date.now()-o})}let T=Yo(u);if(T)return{content:"",...G(T),duration:Date.now()-o};let b=Vo(u);return{content:b.text,duration:Date.now()-o,claudeSessionId:b.sessionId,usage:b.usage,numTurns:b.numTurns,billedModel:b.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function qs(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=de(s,e,n),d=Gs(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let l=Hs(s,c,!0,r,e.model,e.systemPromptAppend,d.args);Ut(e.agentId,s,e.model,r,"stream");let u="",g,f,y,T,b,v;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),D=Ee(Ft(et(s.workspace),e),s.billing),E=at("claude",l,{cwd:s.workspace,timeout:k,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"}),C=()=>{},P=new Promise(A=>{C=A}),N=!1,_;if(i){let A=()=>{N=!0,_=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{E.kill("SIGTERM")}catch{}setTimeout(()=>{try{E.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?A():i.addEventListener("abort",A,{once:!0})}let L="",F=new Le("utf8");E.stdout&&E.stdout.on("data",A=>{L+=F.write(A);let I=L.split(`
|
|
19
|
+
`);L=I.pop()||"";for(let w of I)if(w.trim())try{let x=JSON.parse(w);if(o)try{o(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let O=x.message.usage,h=(O.input_tokens||0)+(O.cache_read_input_tokens||0)+(O.cache_creation_input_tokens||0);h>0&&(T=h)}if(x.type==="assistant"&&x.message?.content){for(let O of x.message.content)if(O.type==="text"&&O.text){let h=O.text.slice(u.length);h&&(u=O.text,t(h,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 O=(typeof x.result=="string",x.result);if(typeof O=="string"&&O.length>u.length){let h=O.slice(u.length);u=O,h&&t(h,u)}}x.usage&&(f={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"&&(y=x.session_id),typeof x.num_turns=="number"&&(b=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{w.trim()&&!w.startsWith("{")&&(u+=w+`
|
|
21
21
|
`,t(w+`
|
|
22
|
-
`,u))}});let H=await
|
|
23
|
-
`);
|
|
24
|
-
`,t(
|
|
25
|
-
`,u)}});let F=await
|
|
22
|
+
`,u))}});let H=await oi(E,P),U=F.end();if(U&&(L+=U),N)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&H.stdout&&(u=typeof H.stdout=="string"?H.stdout:""),H.exitCode!==0&&!u){let A=typeof H.stderr=="string"?H.stderr:"",I=H,w;return I.timedOut?w=`Claude Code timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:I.signal?w=A.trim()||`Claude Code killed by signal ${I.signal}`:I.code==="ENOENT"||/ENOENT|spawn claude/i.test((I.shortMessage||"")+" "+A)?w=Fs():w=A.trim()||`Claude Code exited with code ${I.exitCode??"unknown"}`,{content:"",...G(w),duration:Date.now()-a}}return v?{content:"",...G(v),duration:Date.now()-a,usage:f,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:y}:{content:u,duration:Date.now()-a,usage:f,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:y}}catch(k){return{content:u||"",...G(k.message),duration:Date.now()-a,usage:f,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:y}}}async function Zo(s,e,t,n){let r=Date.now(),o=de(s,e,t),i=Ds(ot(Ls(),"agentx-codex-")),a=ot(i,"last-message.txt"),c=Us(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await at("codex",c,{cwd:s.workspace,timeout:d,reject:!1,env:ct(s,e),extendEnv:!1,stdin:"ignore"}),u=zo(l.stdout);if(l.exitCode!==0||u.apiError){let f=l,y;return f.timedOut?y=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?y=u.apiError:f.signal?y=l.stderr.trim()||`Codex CLI killed by signal ${f.signal}`:f.code==="ENOENT"||/ENOENT|spawn codex/i.test((f.shortMessage||"")+" "+l.stderr)?y=it():y=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${f.exitCode??"unknown"}`,{content:"",...G(y),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let g="";try{g=Os(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||"")?it():d?.message;return{content:"",...G(l||"Codex CLI failed"),duration:Date.now()-r}}finally{Ns(i,{recursive:!0,force:!0})}}async function ei(s,e,t,n,r,o){let i=Date.now(),a=de(s,e,n),c=Ds(ot(Ls(),"agentx-codex-")),d=ot(c,"last-message.txt"),l=Us(s,a,!0,e.model,e.systemPromptAppend,d,r),u="",g,f,y,T;try{let b=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),v=at("codex",l,{cwd:s.workspace,timeout:b,reject:!1,env:ct(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let k="",D="",E=!1,C=new Le("utf8"),P=new Le("utf8"),N=Math.min(b,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),_,L=()=>{_&&clearTimeout(_),_=setTimeout(()=>{E=!0,v.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};L(),v.stderr?.on("data",I=>{L(),D+=P.write(I),D.length>16e3&&(D=D.slice(-16e3))}),v.stdout?.on("data",I=>{L(),k+=C.write(I);let w=k.split(`
|
|
23
|
+
`);k=w.pop()||"";for(let x of w)if(x.trim())try{let O=JSON.parse(x);if(o)try{o(O)}catch{}g=Ht(O)||g,f=Bs(O)||f,y=jt(O)||y,T=Ws(O)||T;let h=Qo(O);if(h&&h!==u){let ee=h.startsWith(u)?h.slice(u.length):h;u=h.startsWith(u)?h:u+h,ee&&t(ee,u)}}catch{u+=x+`
|
|
24
|
+
`,t(x+`
|
|
25
|
+
`,u)}});let F=await v;_&&clearTimeout(_);let H=C.end();H&&(k+=H);let U=P.end();if(U&&(D+=U),F.exitCode!==0&&!u||T){let I=D||(typeof F.stderr=="string"?F.stderr:""),w=F,x;return E?x=`Codex CLI produced no output for ${Math.round(N/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.`:w.timedOut?x=`Codex CLI timed out after ${Math.round(b/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?x=T:w.signal?x=I.trim()||`Codex CLI killed by signal ${w.signal}`:w.code==="ENOENT"||/ENOENT|spawn codex/i.test((w.shortMessage||"")+" "+I)?x=it():x=I.trim()||`Codex CLI exited with code ${w.exitCode??"unknown"}`,{content:"",...G(x),duration:Date.now()-i,usage:g,billedModel:f,codexSessionId:y||r}}let A="";try{A=Os(d,"utf8").trim()}catch{}if(A&&A!==u){let I=A.startsWith(u)?A.slice(u.length):A;u=A,I&&t(I,u)}return{content:u,duration:Date.now()-i,usage:g,billedModel:f,codexSessionId:y||r}}catch(b){let v=/ENOENT|spawn codex/i.test(b?.message||"")?it():b?.message;return{content:u,...G(v||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:f,codexSessionId:y||r}}finally{Ns(c,{recursive:!0,force:!0})}}async function ti(s,e,t,n,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=de(s,e,n),l=qo(s,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",g,f=e.freshSession?void 0:r,y,T,b=!0,v;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),D=Jo(s,e);if(s.persistentProcess)try{T=await Hn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:D,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",T.url),D=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(I){if(!(I instanceof Fn))throw I;I.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:I.message})}if(i?.aborted)throw new Error("task cancelled by operator");let E=at("opencode",l,{cwd:s.workspace,timeout:k,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let C=!1,P,N=()=>{T?.invalidate(),C=!0,P=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{E.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),v=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let _="",L="",F=new Le("utf8"),H=new Le("utf8"),U=I=>{if(I.trim())try{let w=JSON.parse(I);try{o?.(w)}catch{}typeof w.sessionID=="string"&&(f=w.sessionID);let x=w.type==="text"&&typeof w.part?.text=="string"?w.part.text:void 0;x&&(u||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),u+=x,t?.(x,u));let O=w.type==="reasoning"&&typeof w.part?.text=="string"?w.part.text:void 0;O&&a?.(O);let h=w.type==="step_finish"?w.part?.tokens:void 0;h&&(g={inputTokens:ce(h.input),outputTokens:ce(h.output),cacheReadTokens:ce(h.cache?.read),cacheCreateTokens:ce(h.cache?.write)}),y=Go(w)||y}catch{u+=I+`
|
|
26
26
|
`,t?.(I+`
|
|
27
|
-
`,u)}};
|
|
28
|
-
`);
|
|
27
|
+
`,u)}};E.stdout?.on("data",I=>{_+=F.write(I);let w=_.split(`
|
|
28
|
+
`);_=w.pop()||"";for(let x of w)U(x)}),E.stderr?.on("data",I=>{L+=H.write(I)});let A=await E;if(i&&i.removeEventListener("abort",N),_+=F.end(),_.trim()&&U(_),L+=H.end(),C)return{content:"",error:P||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if(A.exitCode!==0||y){let I=A,w;return I.timedOut?w=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:y?w=y:I.code==="ENOENT"||/ENOENT|spawn opencode/i.test((I.shortMessage||"")+" "+L)?w=Ps():w=L.trim()||`OpenCode exited with code ${I.exitCode??"unknown"}`,{content:"",...G(w),duration:Date.now()-c,usage:g,opencodeSessionId:f}}return b=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:f}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(k?.message||"")?Ps():k?.message;return{content:u,...G(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:f}}finally{v?.(),T?.release(b)}}async function ni(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({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(o){return{content:"",...G(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function si(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,g=!1,f=()=>{let b=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(b))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let y=setTimeout(()=>{g=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);y.unref?.();let T=()=>({content:"",...G(`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 b=s.provider||"claude-code",v=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,
|
|
30
|
+
${e.message}`:e.message,k=e.context?.sender,D=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),E=e.context?.channel==="web-chat"&&D?{userId:k,agentId:e.agentId||"acme-public"}:void 0,C=Wn(s),P=Object.keys(C).length>0,N={task:v,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:u.signal,mcpServers:P?C:void 0};if(r){let{generateStream:U}=await import("./agent-AJOPKBST.js"),A="",I,w,x,O;for await(let h of U(N)){if(c)try{c(h)}catch{}if(h.type==="text_delta")A+=h.text,r(h.text,A);else if(h.type==="thinking_delta")h.text&&i&&i(h.text);else if(h.type==="generate_result"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}I=h.result.tokensUsed,h.result.inputTokens!=null&&(w=h.result.inputTokens),h.result.outputTokens!=null&&(x=h.result.outputTokens)}else if(h.type==="done"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}h.result.tokensUsed!=null&&(I=h.result.tokensUsed)}else h.type==="error"&&(O=h.error)}return O&&!A?g?T():O==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${O}`),duration:Date.now()-d}:((w===void 0||x===void 0)&&I&&(w=Math.round(I*.7),x=I-w),{content:A||"Done.",tokensUsed:I,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:_}=await import("./agent-AJOPKBST.js"),L=await _(N),F=L.inputTokens,H=L.outputTokens;if((F===void 0||H===void 0)&&L.tokensUsed){let U=L.tokensUsed;F=Math.round(U*.7),H=U-F}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:F!==void 0||H!==void 0?{inputTokens:F||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(b){return g?T():b?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${b.message}`),duration:Date.now()-d}}finally{clearTimeout(y),a&&a.removeEventListener("abort",f)}}var ri=1e3;async function oi(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),ri),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function ii(s,e,t,n,r,o,i){let a=rt();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,f=!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}),f=a.list().length>A}catch(A){return A instanceof Te,null}f&&Ut(e.agentId,s,e.model,n,"persistent");let y=de(s,e,t),T="",b,v,k,D,E,C,P,N="",_="",L=A=>{if(!i||!A)return;let I;if(_&&A.startsWith(_)?I=A.slice(_.length):I=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
|
-
${A}`:A,
|
|
33
|
+
${A}`:A,_=A,!!I){N+=I;try{i(I,N)}catch{}}},F=!1,H=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?H():o.addEventListener("abort",H,{once:!0}));let U=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let I of g.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:A})){if(U=!0,r)try{r(I.raw)}catch{}if(I.type==="assistant"){let w=I.raw.message?.content??[];for(let O of w)O.type==="text"&&typeof O.text=="string"?(T=O.text,L(O.text)):O.type==="tool_use"&&(_="");let x=I.raw.message?.usage;if(x){let O=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);O>0&&(D=O)}}if(I.type==="result"){let w=I.raw;if(w.is_error){let x=G(typeof w.result=="string"?w.result:"claude error");b=x.error,v=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(T=w.result,N||L(w.result));typeof w.session_id=="string"&&(P=w.session_id),w.usage&&(k={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(E=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(F)b="task cancelled by operator",v="cancelled";else if(U)if(A instanceof Ne)b=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,v="interrupted";else if(A instanceof Oe){let I=G(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);b=I.error,v=I.errorKind}else{let I=G(`persistent claude process error: ${A?.message||String(A)}`);b=I.error,v=I.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"}),o&&o.removeEventListener("abort",H),null}finally{o&&o.removeEventListener("abort",H)}return F&&!b&&(b="task cancelled by operator",v="cancelled"),{content:F?"":T,error:b,errorKind:v,duration:Date.now()-c,usage:k,contextTokens:D,numTurns:E,billedModel:C,claudeSessionId:P}}function Gs(s){return ie(s.autonomy)?s.taskId?$s(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function ai(s,e,t,n,r,o,i){let a=e.autonomy,c=Ms(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:`${_n(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
|
|
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(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=
|
|
36
|
+
`);let u=t?await qs(s,l,t,n,r,o,i):await Ks(s,l,n,r,i),g=Rs(d);return{...u,autonomy:a,...g.length?{autonomyBlocks:g}:{}}}async function Js(s,e,t,n,r,o,i,a,c){if(ie(e.autonomy))return ai(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let d=await ii(s,e,r,o,i,a,n);if(d!==null)return d}return n?qs(s,e,n,r,o,i,a):Ks(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let d=await xs.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ct(s,e),args:js(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Lt(de(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...d,...d.error?G(d.error):{}}}catch(d){if(!(d instanceof ae))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?ei(s,e,n,r,o,i):Zo(s,e,r,o);case"opencode":return ti(s,e,n,r,o,i,a,c);case"sdk":{let d=s.provider||"claude",l=t[d]?.apiKey;return l?ni(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 si(s,e,u,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as Ie,writeFileSync as Qs,mkdirSync as ci,existsSync as Bt,readdirSync as Wt}from"fs";import{resolve as Se}from"path";var Kt=12e3,Fe=30,di=720,ui=40,li=18e4,gi="[Compacted conversation summary",pi=7*864e5,hi=[/\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 mi(s){return s?hi.some(e=>e.test(s)):!1}var fi=[{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 Xs(s){if(!s)return null;let e=0;for(let t of fi)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function zs(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 Ys(s,e){let t=(s??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function Vs(s,e,t){if(t<=0)return[];let n=(s??[]).filter(i=>i.role==="user"),r=n[n.length-1],o=(r&&r.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function yi(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 dt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Se(e,".agentx/sessions"),Bt(this.sessionsDir)||ci(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??di),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ui),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??li)}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 o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;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:Fe,maxChars:Kt});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.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 o=this.sessionFile(r);if(Bt(o))try{let d=JSON.parse(Ie(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=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:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.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),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!Bt(i))return null;try{return JSON.parse(Ie(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);zs(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,r){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,r){let o=this.getSession(e,t,n);zs(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,r={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??Fe),a=Math.max(200,r.maxChars??Kt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let f=o.messages[g];if(d+=f.content.length,c.push(f),d>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let g of c){let f=yi(g.timestamp);f!==u&&(l.push(`\u2014 ${f} \u2014`),u=f);let y=g.name||(g.role==="user"?"User":"Agent");l.push(`${y}: ${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(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Wt(this.sessionsDir).filter(E=>E.startsWith(`${a}:`)&&E.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(E=>{let C=E.match(u);if(!C)return!1;let P=C[1];return P>=d&&P<=l}),f=[],y=0,T=e.query?.toLowerCase(),b=e.participants?.length?new Set(e.participants):void 0;for(let E of g){let C;try{C=JSON.parse(Ie(Se(this.sessionsDir,E),"utf-8"))}catch{continue}if(C.agentId===e.agentId&&!(e.channel&&C.channel!==e.channel)&&!(e.chatId&&C.chatId!==e.chatId))for(let P of C.messages)y++,!(!P.timestamp||P.timestamp<o||P.timestamp>=i)&&(b&&P.role==="user"&&!b.has(P.name??"")||T&&!P.content.toLowerCase().includes(T)||f.push({ts:P.timestamp,role:P.role,senderName:P.name??"",content:P.content,channel:C.channel,chatId:C.chatId,day:C.day,sessionFile:E}))}f.sort((E,C)=>C.ts.localeCompare(E.ts));let v=f.slice(0,t),k=v.length>0?v[v.length-1].ts:null,D=f.length>t;return{turns:v,oldestTs:k,hasMore:D,totalScanned:y}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Fe,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=Wt(this.sessionsDir).filter(u=>u.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(u=>{if(!u.includes(i))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(Ie(Se(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let f of g.messages)!f.timestamp||f.timestamp<n||c.push({ts:f.timestamp,role:f.role,senderName:f.name??"",content:f.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!==""&&!mi(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Wt(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let l=JSON.parse(Ie(Se(this.sessionsDir,d),"utf-8"));if(l.id===i||l.messages.length===0)continue;let u=l.messages.slice(-4),f=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,y=u.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${f} (${l.channel}):
|
|
38
38
|
${y.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 o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{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(xi)}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,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return ve(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Se(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},zs(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>Ti?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((o,i)=>o+i.content.length,0);for(;n>Gt&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&me.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);zs(t,JSON.stringify(e,null,2))}catch{}}};var lt=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,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);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(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.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 er,appendFileSync as Ci,existsSync as Ce,mkdirSync as Ai}from"fs";import{resolve as Ae}from"path";var nr={"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}},sr=2e5,$i=1.5;function Mi(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 rr(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>sr?{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 tr=500,Ri=".agentx/pricing/custom.json",$e=class{dir;cache=null;pricing;constructor(e=Ae(process.cwd(),".agentx/usage")){this.dir=e,Ai(this.dir,{recursive:!0}),this.pricing=Pi()}getPricing(){return this.pricing}static calculateCost(e,t,n=nr){let r=Mi(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,u=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return l+u*$i}cost(e,t){return $e.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,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,f=0,y=0,x=0,b=0,S=0,T=0,D=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>sr?(b=n.inputTokens,S=n.outputTokens,T=n.cacheReadTokens,D=n.cacheCreateTokens):(g=n.inputTokens,f=n.outputTokens,y=n.cacheReadTokens,x=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(g=Math.ceil(r/4),f=Math.ceil(o/4)),u.inputTokens+=g,u.outputTokens+=f,u.cacheReadTokens+=y,u.cacheCreateTokens+=x,u.tier2InputTokens=(u.tier2InputTokens||0)+b,u.tier2OutputTokens=(u.tier2OutputTokens||0)+S,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+T,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+D,i&&u.errors++,u.byChannel||(u.byChannel={});let M=(c||"other").toLowerCase(),C=u.byChannel[M]||{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+=f,C.cacheReadTokens+=y,C.cacheCreateTokens+=x,C.tier2InputTokens+=b,C.tier2OutputTokens+=S,C.tier2CacheReadTokens+=T,C.tier2CacheCreateTokens+=D,i&&C.errors++,u.byChannel[M]=C,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>tr&&u.sessionKeys.splice(0,u.sessionKeys.length-tr))),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(Ce(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(!Ce(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,o=0,i=0,a=0,c=0,d=0,l="",u=0,g={},f={},y={};for(let[x,b]of Object.entries(n.agents)){let S=this.cost(b);g[x]=S,r+=b.tasks,o+=(b.inputTokens||0)+(b.tier2InputTokens||0),i+=(b.outputTokens||0)+(b.tier2OutputTokens||0),a+=(b.cacheReadTokens||0)+(b.tier2CacheReadTokens||0),c+=(b.cacheCreateTokens||0)+(b.tier2CacheCreateTokens||0),d+=S,S>u&&(u=S,l=x);let T=b.sessionKeys?.length||0;f[x]={sessions:T,avgTasksPerSession:T>0?b.tasks/T:b.tasks};for(let[D,M]of Object.entries(b.byChannel||{})){let C=this.cost(M,b.model);y[D]=(y[D]||0)+C}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:g,agentSessionStats:f,byChannel:y}}appendToTokenCosts(e,t){let n=t||Ae(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=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} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;Ce(n)?Ci(n,c+`
|
|
41
|
-
`):
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{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(gi)}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,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Se(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ie(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Qs(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>pi?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>Fe&&(e.messages=e.messages.slice(-Fe));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Kt&&e.messages.length>2;){let o=e.messages.shift();n-=o.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);Qs(t,JSON.stringify(e,null,2))}catch{}}};var ut=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,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);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(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.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 He,writeFileSync as Zs,appendFileSync as bi,existsSync as ve,mkdirSync as wi}from"fs";import{resolve as Ce}from"path";var tr={"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}},nr=2e5,xi=1.5;function Ti(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 sr(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>nr?{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 er=500,ki=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,wi(this.dir,{recursive:!0}),this.pricing=Ii()}getPricing(){return this.pricing}static calculateCost(e,t,n=tr){let r=Ti(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,u=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return l+u*xi}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,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,f=0,y=0,T=0,b=0,v=0,k=0,D=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>nr?(b=n.inputTokens,v=n.outputTokens,k=n.cacheReadTokens,D=n.cacheCreateTokens):(g=n.inputTokens,f=n.outputTokens,y=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(g=Math.ceil(r/4),f=Math.ceil(o/4)),u.inputTokens+=g,u.outputTokens+=f,u.cacheReadTokens+=y,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+b,u.tier2OutputTokens=(u.tier2OutputTokens||0)+v,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+k,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+D,i&&u.errors++,u.byChannel||(u.byChannel={});let E=(c||"other").toLowerCase(),C=u.byChannel[E]||{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+=f,C.cacheReadTokens+=y,C.cacheCreateTokens+=T,C.tier2InputTokens+=b,C.tier2OutputTokens+=v,C.tier2CacheReadTokens+=k,C.tier2CacheCreateTokens+=D,i&&C.errors++,u.byChannel[E]=C,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>er&&u.sessionKeys.splice(0,u.sessionKeys.length-er))),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(He(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(He(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,o=0,i=0,a=0,c=0,d=0,l="",u=0,g={},f={},y={};for(let[T,b]of Object.entries(n.agents)){let v=this.cost(b);g[T]=v,r+=b.tasks,o+=(b.inputTokens||0)+(b.tier2InputTokens||0),i+=(b.outputTokens||0)+(b.tier2OutputTokens||0),a+=(b.cacheReadTokens||0)+(b.tier2CacheReadTokens||0),c+=(b.cacheCreateTokens||0)+(b.tier2CacheCreateTokens||0),d+=v,v>u&&(u=v,l=T);let k=b.sessionKeys?.length||0;f[T]={sessions:k,avgTasksPerSession:k>0?b.tasks/k:b.tasks};for(let[D,E]of Object.entries(b.byChannel||{})){let C=this.cost(E,b.model);y[D]=(y[D]||0)+C}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:g,agentSessionStats:f,byChannel:y}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=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} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;ve(n)?bi(n,c+`
|
|
41
|
+
`):Zs(n,`# Token Costs
|
|
42
42
|
|
|
43
43
|
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
44
44
|
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
@@ -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||
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=He(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=He(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){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,o=0,i=0,a=0,c=0,d={},l={};for(let y=0;y<e;y++){let T=new Date(Date.now()-y*864e5).toISOString().slice(0,10),b=this.getDate(T);if(b)for(let[v,k]of Object.entries(b.agents)){let D=this.cost(k);t+=k.tasks;let E=(k.inputTokens||0)+(k.tier2InputTokens||0),C=(k.outputTokens||0)+(k.tier2OutputTokens||0),P=(k.cacheReadTokens||0)+(k.tier2CacheReadTokens||0),N=(k.cacheCreateTokens||0)+(k.tier2CacheCreateTokens||0);n+=E,r+=C,o+=P,i+=N,a+=k.errors,c+=D;let _=d[v]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};_.tasks+=k.tasks,_.input+=E,_.output+=C,_.cacheRead+=P,_.cacheCreate+=N,_.total=_.input+_.output+_.cacheRead+_.cacheCreate,_.totalDuration+=k.totalDuration,_.avgDuration=_.totalDuration/_.tasks,_.cost+=D,_.sessions+=k.sessionKeys?.length||0,k.model&&(_.model=k.model),d[v]=_;for(let[L,F]of Object.entries(k.byChannel||{})){let H=this.cost(F,k.model),U=l[L]||{tasks:0,cost:0};U.tasks+=F.tasks,U.cost+=H,l[L]=U}}}let u=n+r+o+i,g=o+i>0?o/(o+i):0,f={};for(let[y,T]of Object.entries(d))f[y]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:f}}filePath(e){return Ce(this.dir,`${e}.json`)}save(e){try{Zs(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Ii(){let s=JSON.parse(JSON.stringify(tr));try{let e=Ce(process.cwd(),ki);if(!ve(e))return s;let t=JSON.parse(He(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 Si={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}},rr=4;function or(s,e=Si){let t=vi(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*rr;for(let i of t){if(!i.content)continue;let a=i.maxTokens*rr,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let d=o-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 vi(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(Ci(s,t("channel",200))),n.push(Ai(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 i=[`[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
|
`);i.push(d)}s.intent.leaf?.input&&i.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
54
|
-
`),tags:["intent",...s.intent.path]})}else{let i
|
|
54
|
+
`),tags:["intent",...s.intent.path]})}else{let i=$i(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}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 o=s.groupHistory||s.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,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 i=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&i.push(`Operator summary: ${s.handoverNote.summary}`),i.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.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:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}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 Ci(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(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
58
|
+
`),tags:r,rules:n}}function Ai(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(o=>o.handle||o.name||o.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 o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:n}}function $i(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}function ir(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=32e3?e:null}catch{return null}}function ed(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 ar(s){return new Date(s).toISOString().slice(11,16)}function cr(s,e=Date.now()){return!Number.isFinite(s)||e-s<=6e4?null:`[queued at ${ar(s)} UTC, running at ${ar(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 lt=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 o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
60
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}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 Mi,writeFileSync as dr,appendFileSync as Ri,mkdirSync as Pi,existsSync as ur}from"fs";import{resolve as qt}from"path";var lr=50,_i="claude-haiku-4-5-20251001",Ei=`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,40 +73,40 @@ 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: []`,
|
|
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()};
|
|
78
|
-
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=
|
|
79
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&
|
|
76
|
+
If nothing worth extracting, output: []`,gt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=qt(e,".agentx/patterns"),ur(this.patternsDir)||Pi(this.patternsDir,{recursive:!0})}filePath(e){return qt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ur(t))return[];try{return Mi(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()};Ri(this.filePath(e),JSON.stringify(n)+`
|
|
78
|
+
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=qt(this.patternsDir,`${t}_bm25_cache.json`),a=Mn(o,i),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
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&dr(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
80
80
|
`)+`
|
|
81
|
-
`)}prune(e){let t=this.getAll(e);t.length<=
|
|
81
|
+
`)}prune(e){let t=this.getAll(e);t.length<=lr||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,lr),dr(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
82
82
|
`)+`
|
|
83
|
-
`))}};async function
|
|
83
|
+
`))}};async function gr(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-ES5KVLI4.js"),c=(await o("claude").generate([{role:"system",content:Ei},{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] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function
|
|
88
|
-
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function
|
|
89
|
-
`)}var
|
|
85
|
+
Agent: ${t.slice(0,1e3)}`}],{model:_i,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 Di}from"events";var Oi=2e4,Jt=class{inner=new Di;envelopeListeners=new Set;ring=new is;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(Ni(e,t))}catch{}return n}publish(e){let t=os(),n=e.id??rs(),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:Pt(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(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>Oi&&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:Pt(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 Ni(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 Gt;function V(){return Gt||(Gt=new Jt),Gt}vt();vt();var pr=["manual","notify","auto"];function Li(s){return typeof s=="string"&&pr.includes(s)}var Qt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Fi=7*24*60*6e4,je=class{constructor(e={},t){this.store=t;this.opts={...Qt,...e};let n={};try{n=t?.load()??{}}catch{n={}}let r=Date.now()-Fi;for(let[o,i]of Object.entries(n))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}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 o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,n),i}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 o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.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:Hi(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(o=>{this.waiters.set(r.id,{resolve:o})})}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 o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}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 o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.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,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Hi(s,e){return s.length<=e?s:`${s.slice(0,e)}
|
|
86
|
+
\u2026[truncated ${s.length-e} chars]`}Io();import{z as ji}from"zod";var mr=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Ui(s){if(s==null)return{ok:!0,subscriptions:mr};let e=ji.array(En).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 Bi=15,Wi=1500,hr=200;function fr(s,e=Date.now()){let t=s[s.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Ki(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 yd(s,e,t={}){let n=Ki(e,s.cursor),r=n.length?fr(n):s.cursor,o=n.filter(d=>s.subscriptions.some(l=>as(l,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=s.cursor.id??s.cursor.at,{text:a,shown:c}=qi(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function qi(s,e,t={}){let n=Math.max(3,t.maxLines??Bi),r=Math.max(200,t.maxChars??Wi),o=s.map(a=>Gi(`- ${ds(a)}`)),i=o.length;for(let a=Math.min(i,n-1);a>=0;a--){let c=i-a,l=[c?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-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] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Gi(s){return s.length<=hr?s:`${s.slice(0,hr-1)}\u2026`}import{existsSync as Ji,mkdirSync as Qi,readFileSync as zi,renameSync as Xi,writeFileSync as Yi}from"node:fs";import{homedir as Vi}from"node:os";import{dirname as Zi,join as ea}from"node:path";function ta(s){return{load:()=>Ji(s)?JSON.parse(zi(s,"utf-8")):{},save:e=>{Qi(Zi(s),{recursive:!0});let t=`${s}.tmp`;Yi(t,JSON.stringify(e,null,2),{mode:384}),Xi(t,s)}}}function na(){if(!process.env.VITEST)return ta(process.env.AGENTX_ATTACH_BINDINGS_FILE??ea(Vi(),".agentx","attach-bindings.json"))}var zt;function yr(){return zt||(zt=new je({},na())),zt}Ct();import{readFileSync as sa}from"fs";import{homedir as ra}from"os";import{join as oa}from"path";var Ue=null,ia=6e4;function aa(){try{let s=oa(ra(),".claude.json"),e=sa(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function ca(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 da(s=!1){let e=Date.now();return!s&&Ue&&e-Ue.checkedAt<ia||(Ue=ca(aa(),e)),Ue}function br(s){let e=da();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 wr={warnRatio:.8},z={...wr},ua=5*60*60*1e3,la=60*60*1e3,me=[];function xr(s){z={...wr,...s||{}}}function Tr(s){let e=s-ua,t=0;for(;t<me.length&&me[t]<e;)t++;t>0&&me.splice(0,t)}function kr(s=Date.now()){Tr(s),me.push(s)}function Ir(s=Date.now()){Tr(s);let e=s-la,t=0;for(let o=me.length-1;o>=0&&me[o]>=e;o--)t++;let n=me.length,r={lastHour:t,last5h:n,maxPerHour:z.maxPerHour,maxPer5h:z.maxPer5h};return z.maxPerHour&&z.maxPerHour>0&&(r.hourlyRatio=t/z.maxPerHour),z.maxPer5h&&z.maxPer5h>0&&(r.fiveHourRatio=n/z.maxPer5h),r}function Sr(s,e=Date.now()){let t=Ir(e);return s?null:z.maxPerHour&&t.lastHour>=z.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${z.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}:z.maxPer5h&&t.last5h>=z.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${z.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 vr(s=Date.now()){let e=Ir(s),t=z.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 Xt=new Map;function Cr(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function Ar(s,e,t,n=Date.now()){let r=Xt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Xt.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 $r(s){let e=Xt.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 Z,mkdirSync as Ua,readdirSync as se,readFileSync as We,rmSync as Ba,writeFileSync as Wa}from"fs";import{resolve as K}from"path";import{existsSync as ye,mkdirSync as Yt,readFileSync as ga,readdirSync as pa,renameSync as ha,unlinkSync as ma,writeFileSync as pt}from"fs";import{resolve as ue,relative as ht}from"path";import{z as q}from"zod";var fe=q.object({id:q.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:q.string().min(1),trigger:q.string().min(1,"procedures must describe when they apply"),inputs:q.array(q.string()).default([]),expected:q.string().optional(),kpis:q.array(q.string()).default([]),owner:q.string().optional(),tags:q.array(q.string()).default([]),status:q.enum(["draft","active","deprecated"]).default("active"),source:q.string().optional(),evidence:q.array(q.string()).default([]),created:q.string().optional(),updated:q.string().optional(),related:q.array(q.string()).default([])});function fa(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
|
+
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function mt(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 Be=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ue(process.cwd(),".agentx/procedures"),Yt(this.baseDir,{recursive:!0})}pathFor(e){return ue(this.baseDir,`${e}.md`)}get draftsDir(){return ue(this.baseDir,"_drafts")}draftPathFor(e){return ue(this.draftsDir,`${e}.md`)}parseFile(e){let t=ga(e,"utf-8"),{meta:n,body:r}=fa(t),o=fe.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:ht(this.baseDir,e)}:null}listDir(e){if(!ye(e))return[];let t=[];for(let n of pa(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(ue(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 pt(r,mt(n)+`
|
|
90
90
|
|
|
91
91
|
`+t.trim()+`
|
|
92
|
-
`),{meta:n,body:t.trim(),path:
|
|
92
|
+
`),{meta:n,body:t.trim(),path:ht(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=fe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return pt(this.pathFor(e),mt(o)+`
|
|
93
93
|
|
|
94
94
|
`+i.trim()+`
|
|
95
|
-
`),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let n=
|
|
95
|
+
`),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let n=fe.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(n.id))throw new Error(`Procedure already exists: ${n.id}`);let r=this.draftPathFor(n.id);if(ye(r))throw new Error(`Draft already exists: ${n.id}`);return Yt(this.draftsDir,{recursive:!0}),pt(r,mt(n)+`
|
|
96
96
|
|
|
97
97
|
`+t.trim()+`
|
|
98
|
-
`),{meta:n,body:t.trim(),path:
|
|
98
|
+
`),{meta:n,body:t.trim(),path:ht(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 pt(this.pathFor(e),mt(n)+`
|
|
99
99
|
|
|
100
100
|
`+t.body+`
|
|
101
|
-
`),
|
|
102
|
-
`)}function
|
|
101
|
+
`),ma(this.draftPathFor(e)),{meta:n,body:t.body,path:ht(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!ye(t))throw new Error(`Draft not found: ${e}`);let n=ue(this.draftsDir,"_rejected");Yt(n,{recursive:!0}),ha(t,ue(n,`${e}.md`))}isRejected(e){return ye(ue(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as ya,mkdirSync as ba,readFileSync as wa,writeFileSync as xa}from"fs";import{dirname as Ta,resolve as ka}from"path";import{z as Y}from"zod";var Ia=Y.object({key:Y.string(),count:Y.number().int().min(0).default(0),firstSeen:Y.string(),lastSeen:Y.string(),taskIds:Y.array(Y.string()).default([]),sampleMessage:Y.string().default(""),status:Y.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:Y.string().optional()}),Sa=Y.object({minedThrough:Y.string().optional(),candidates:Y.array(Ia).default([])});function Mr(s){return ka(s,"_candidates.json")}function va(s){let e=Mr(s);if(!ya(e))return{candidates:[]};try{let t=Sa.safeParse(JSON.parse(wa(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Ca(s,e){let t=Mr(s);ba(Ta(t),{recursive:!0}),xa(t,JSON.stringify(e,null,2)+`
|
|
102
|
+
`)}function Aa(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function $a(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Ma(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Vt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Rr(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 Zt(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Vt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Rr(o,Vt(a.meta.trigger));d>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=Rr(o,Vt(l));u>0&&c.push("title/tags");let g=Math.min(1,d*.7+u*.5);g>=r&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function en(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
|
-
`)}
|
|
106
|
-
`).slice(-3).join(" ")):!1}var
|
|
105
|
+
`)}Nn();At();var nn="turn-progress",Pr={progress:Ze({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.")},tn=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function _r(s){return{agent:s.agent,request:tn(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:tn(e.input,300),...e.result!==void 0?{result:tn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}At();var Er="turn-handoff",Dr="approval-binding",Or={nextStep:Ze({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.")},Nr={approves:_e("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."})},Ra=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,Lr=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,Pa=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function sn(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Pa.test(e.split(`
|
|
106
|
+
`).slice(-3).join(" ")):!1}var _a=/^\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 Fr(s){return s.trim().length<=160&&_a.test(s)}function Hr(s){return s.trim().length<=160}function jr(s){return{agent:s.agent,channel:s.channel,request:Ra(s.request,1500),agentReplyEnding:Lr(s.reply,1200)}}function Ur(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:Lr(s.previousReply,1200)}}var Ea=5*6e4,Da=3,Oa=12,Na=24*60*6e4,Br=new Set(["cron","heartbeat","bench","a2a","business"]),La={observe(){},stop(){}};function Wr(s){if(On(nn)==="off")return La;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let g;for(let[f,y]of o)y>1&&(!g||y>g.times)&&(g={call:f,times:y});return g},l=g=>{if(c)return;c=!0,a=n.length;let f=_r({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-Oa),repeated:d(),trigger:g});xe(nn,f,Pr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:g}}).finally(()=>{c=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Ea);return u.unref?.(),{observe(g){let f=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let y of f){if(y?.type!=="tool_use")continue;let T=y.input?JSON.stringify(y.input):"",b={tool:y.name||"tool",input:T};n.push(b),typeof y.id=="string"&&r.set(y.id,b);let v=`${b.tool}(${T})`,k=(o.get(v)??0)+1;o.set(v,k),k>=Da&&!i.has(v)&&(i.add(v),l("repetition"))}else if(g?.type==="user")for(let y of f){if(y?.type!=="tool_result")continue;let T=r.get(y.tool_use_id);T&&(T.result=Array.isArray(y.content)?y.content.map(b=>typeof b?.text=="string"?b.text:"").join(""):typeof y.content=="string"?y.content:"",y.is_error&&(T.error=!0))}},stop(){clearInterval(u)}}}var rn=new Map,Kr=(s,e,t)=>`${s}\0${e}\0${t}`;function qr(s){if(Br.has(s.channel)||!sn(s.reply))return;let e=Kr(s.agent,s.channel,s.chatId);xe(Er,jr(s),Or,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&rn.set(e,{callId:t.callId,at:Date.now()})})}function Gr(s){if(Br.has(s.channel))return;let e=Kr(s.agent,s.channel,s.chatId),t=rn.get(e);if(t){rn.delete(e);let n=Dn().store;if(n&&Date.now()-t.at<Na)try{n.label(t.callId,"userReply",Fr(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!Hr(s.message)||!sn(s.previousReply)||xe(Dr,Ur({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),Nr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function Jr(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(ft(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(c=>{a(),n(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function ft(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Ha=250,ja=5e3;function Qr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var eo;function Yu(s){eo=s}function Vu(){return eo}var zr=64*1024,Ka=5*60*1e3,qa=3e4,Ga=300,$e=".agentx/task-history",Ja=30;function Ke(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Qa(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 za(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=cs(s,e,V().recent());return us(t,n)}function Xa(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 o=t.maxArticles??400,i=n.length<=o,a=Array.from(r.entries()).sort().map(([l,u])=>i?`**${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
|
|
109
|
+
`)}var on=8*1024;function Ya(s,e){if(s)try{ms(s)}catch{}return e}function Xr(s){if(s.length<=on)return s;let e=s.length-on;return s.slice(0,on)+`\u2026[+${e}]`}function Yr(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 Va(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 Vr(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=V();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Xr(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Xr(a):null,at:r})}return}}function Za(){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:ji,maxTokens:512})).content.trim().match(/\[[
|
|
|
127
127
|
\u2192 ${i}(${a})
|
|
128
128
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Ke(i,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
|
-
`:""}}var
|
|
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 o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;if(a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let c=i.error?
|
|
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 f=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:f});let y={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,y);let
|
|
130
|
+
`:""}}var Zr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Zn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Yn;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 dt(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 Vn,this.patternStore=new gt,this.rateLimiter=new ut,this.tokenTracker=new Ae,this.messageQueue=new lt,xr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Jn({baseDir:K(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Qn({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 o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,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>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.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,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,r);i=Ys(g.messages,e.message??""),c=Vs(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:i,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(fs,bs(d),ys,{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"||!ws(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),V().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${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:o,reason:i,memo:c.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${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,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
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 o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;if(a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let c=i.error?tt(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ns().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=ie(e.autonomy),i=o?null:yr().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(i){let p=await i;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(o)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(m=>m.healthy&&m.skills.some(S=>S.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let m=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:m}),viaMesh:p.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}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"||o){let p=Date.now(),m=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(R=>setTimeout(R,S))}}else if(c==="voice"){let p=Date.now(),m=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(R=>setTimeout(R,500))}l=S,this.voiceClaims.add(S)}else{let p=a.def.queueMode||"collect",m=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(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${a.runningTasks.map(R=>R.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:es(m,S)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,m)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/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=cr(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 f=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:f});let y={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,y);let T=p=>{if(p){y.buffer+=p,y.buffer.length>zr&&(y.buffer=y.buffer.slice(y.buffer.length-zr));for(let m of y.subscribers)try{m(p)}catch{}}},b=we();e.taskId=b;let v=new Map,k=(p,m,S)=>{try{V().emit("task:step",{taskId:b,agentId:e.agentId,name:"pipeline",action:p,status:S,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,E=!1,C=()=>{E||(E=!0,D&&k("first-event",D,"ok"))},P;if(t){let p=Za();P=m=>{C();let S=p(m);if(S&&T(S),Vr(b,e.agentId,m),Yr(v,m),r)try{r(m)}catch{}}}else P=p=>{if(C(),Vr(b,e.agentId,p),Yr(v,p),r)try{r(p)}catch{}};let N=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,_=N?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(N/1e3)}s`)),N):void 0;_?.unref?.();let L=(a.def.preSpawnTimeoutSec??Ga)*1e3,F=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(L/1e3)}s in step "${g.step??"start"}"`))},L);F.unref?.();let H=()=>{F&&clearTimeout(F),F=void 0},U=()=>`task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`,A;f.signal.addEventListener("abort",()=>{let p=ft(f.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} ${U()}`)},{once:!0});let I=p=>{g.step=p,this.log(`[${e.agentId}] step ${p} ${U()}`)},w=(p,m,S=0)=>{if(f.signal.aborted)return Promise.reject(ft(f.signal));I(p),(p==="agent"||p==="workflow-auto-run")&&(H(),D=Date.now());let R=Date.now();return Jr(m(),f.signal,S).then(W=>(k(p,R,"ok"),W),W=>{throw k(p,R,"error"),W})},x=!1,O=p=>{if(x)return;x=!0,this.runReleases.delete(g.id),_&&clearTimeout(_),H(),a.activeTasks--;let m=a.runningTasks.findIndex(S=>S.id===g.id);m!==-1&&a.runningTasks.splice(m,1),this.runningContexts.delete(g.id),this.taskAborts.delete(g.id),y.done=!0,y.endedAt=new Date;for(let S of y.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),
|
|
135
|
-
`).length}L`,Q=`[${e.agentId}] ${h}:${$} ${W} | session.messages=${m.length}`+(m.length>0?` first=${
|
|
136
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${
|
|
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.`:"",
|
|
134
|
+
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Ka).unref?.();try{let S=y.endedAt,R={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:y.buffer};this.persistTaskRecord(R);let W=(R.responseText||R.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:S,ok:R.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 R of S){let W=R.originalContext||{channel:R.channel,sender:R.sender,chatId:R.chatId};this.execute({message:R.text,agentId:e.agentId,context:W,queuedAt:R.queuedAt??R.timestamp}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(g.id,O),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${U()}`);let h=e.context?.channel||"api",{evaluateRequest:ee,selectRequestContext:to}=await import("./request-planner-BXU5GECQ.js"),le=await w("request-gate",()=>ee(e.message,e.agentId,h));le.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",yt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,h,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${h}:${$}`),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await w("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,h,$,e.seedHistory));let no=[...this.sessions.getSession(e.agentId,h,$).messages].reverse().find(p=>p.role==="agent")?.content;Gr({agent:e.agentId,channel:h,chatId:$,message:e.message,previousReply:no,taskId:b}),this.sessions.addUserMessage(e.agentId,h,$,yt,e.message);let an=Date.now();V().emit("task:started",{agentId:e.agentId,channel:h,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(an).toISOString(),taskId:b,resumeOrigin:ir(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let X,bt,cn=this.classifier;if(cn&&h!=="a2a"&&!te){I("classify");let p=Date.now();bt=cn.classify({text:e.message,channel:h,sender:e.context?.sender,chatId:$,agentId:e.agentId}).then(m=>{X=m||void 0,X?.path?.length&&(g.intentPath=X.path.slice()),k("classify",p,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),k("classify",p,"error")})}let dn=async p=>{if(!bt)return;let m;await Promise.race([bt,new Promise(S=>{m=setTimeout(S,p),m.unref?.()})]),m&&clearTimeout(m)};await dn(Ha);let Me=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&Me?.enabled&&!o)try{let p=new gs({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=ps({agentId:e.agentId,channel:h,message:e.message,intentPath:X?.path},p.list());m&&m.confidence>=Me.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Me.mode} reasons=${m.reasons.join(",")||"n/a"}`),Me.mode==="auto"&&m.confidence>=Me.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:m.workflow.id,confidence:m.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 so=this.wikiHub.getAgentWiki(e.agentId),un=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),ln=this.memoryStore.buildContext(un),gn=this.memoryStore.contextFacts(un),ro=this.patternStore.findRelevant(e.message,e.agentId,5),oo=this.patternStore.buildContext(ro),pn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await w("skills",()=>p(a.def.workspace));pn=m(S,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,h,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,h,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,h,$):void 0;if(j&&this.sessions.isSessionStale(e.agentId,h,$)&&(this.log(`[${e.agentId}] session stale for ${h}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,h,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,h,$);this.log(`[${e.agentId}] tier-2 rotation for ${h}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,h,$)){let p=this.sessions.getTurnCount(e.agentId,h,$);this.log(`[${e.agentId}] max-turns rotation for ${h}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let p=j;await w("rotate",()=>this.maybeRotateForContinuity(e,a,h,$,p))&&(j=void 0)}try{let p=await w("compact",()=>this.sessions.compactIfNeeded(e.agentId,h,$,this.memoryStore));if(p.compacted){let m=p.qualityScore??"?",S=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${h}:${$} (quality: ${m}%, ${S} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let R=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${R.overallScore} (lexicon=${R.lexiconDecay}, tools=${R.toolShift}, semantic=${R.semanticDrift})`),R.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${R.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let io=process.env.AGENTX_CONTEXT_SURGERY==="1",ao=te?{maxMessages:8,maxChars:2400}:io&&Qr(h,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,co=!j&&!te?Xa(so,e.agentId):void 0,qe=j?void 0:this.sessions.buildHistoryContext(e.agentId,h,$,ao),uo=j?void 0:this.sessions.getRotationMemo(e.agentId,h,$)??void 0,hn,mn=[];if(this.config.procedures?.injection?.enabled&&!j&&!te)try{let p=new Be({baseDir:K(process.cwd(),this.config.procedures.dir)}),m=Zt(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){hn=en(m),mn=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)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 m=this.sessions.getSession(e.agentId,h,$).messages,S=m[0],R=m[m.length-1],W=qe===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${qe.length}c/${qe.split(`
|
|
135
|
+
`).length}L`,Q=`[${e.agentId}] ${h}:${$} ${W} | session.messages=${m.length}`+(m.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${R.timestamp.slice(11,19)}(${R.role}:${(R.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",Q)}catch(p){he.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let fn;if(a.def.contextReferences&&!j)try{let p=a.def.workspace,m=this.referencesCache.get(p);if(!m){let[R,W]=await w("references",()=>Promise.all([Mt(a.def.workspace),Rt(a.def.workspace)]));if(R.byId.size===0&&W.recipes.length===0){let[Q,pe]=await w("references",()=>Promise.all([Mt(process.cwd()),Rt(process.cwd())]));m={refs:Q,recipes:pe}}else m={refs:R,recipes:W};this.referencesCache.set(p,m)}let S=ss({agentId:e.agentId,intentTags:X?.path,message:e.message},m.recipes,m.refs);S.cards.length>0&&(fn=ts(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 yn=this.sessions.getCrossSessionSummary(e.agentId,h,$,e.message),bn,Ge=Xs(e.message);if(Ge)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:h,chatId:$,lookbackDays:Ge.lookbackDays,limit:12});if(p.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Ge.lookbackDays}d on this chat (cue-triggered)]`],S=[...p.turns].sort((R,W)=>R.ts.localeCompare(W.ts));for(let R of S){let W=R.ts.slice(11,16)+" "+R.day,Q=R.role==="user"?R.senderName||"User":R.senderName||"Agent";m.push(`${W} ${Q}: ${R.content}`)}p.hasMore&&m.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),bn=m.join(`
|
|
136
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ge.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let lo=te?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",wn,xn,Tn=!1;if(lo==="planner"&&!le.active&&h!=="voice"&&h!=="desktop"){try{let{planContext:p}=await import("./context-planner-JU7CNXCB.js"),m=await w("plan-context",()=>p({agentId:e.agentId,channel:h,chatId:$,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Tn=!0,wn=m.sessionHistory,ln=m.memoryContext,gn=m.memoryFacts,yn=m.crossChatContext,xn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.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)`)}Tn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,h,$),j=void 0)}let wt=`${e.agentId}:${h}:${$}`,Je=Bn(e.message);Je&&(Je==="default"?(this.activeSouls.delete(wt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(wt,Je),this.log(`[${e.agentId}] Soul switched to: ${Je}`)));let go=this.activeSouls.get(wt),po=jn(a.def.workspace,go),ho=Un(po),mo=this.agentMemory.indexMarkdown(e.agentId),fo=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.`:"",yo=ec(a.def.richMessages,h),kn="";if(a.def.workspace){let p=K(a.def.workspace,"CLAUDE.md");if(Z(p))try{let m=We(p,"utf-8");kn=`[Project CLAUDE.md]
|
|
138
138
|
${m.length>4e3?m.slice(0,4e3)+`
|
|
139
139
|
|
|
140
|
-
[CLAUDE.md truncated to 4KB]`:m}`}catch{}}let
|
|
140
|
+
[CLAUDE.md truncated to 4KB]`:m}`}catch{}}let Qe=e.context?.runbookPath,xt=[];if(Qe&&Z(Qe)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],m=0,S=4e3,R=16e3;for(let W of p){if(m>=R)break;let Q=K(Qe,W);if(Z(Q))try{let pe=We(Q,"utf-8"),M=pe.length>S?pe.slice(0,S)+`
|
|
141
141
|
|
|
142
|
-
[${W} truncated to ${
|
|
143
|
-
${
|
|
142
|
+
[${W} truncated to ${S} bytes]`:pe;xt.push(`[Project Runbook \u2014 ${W} from ${Qe}]
|
|
143
|
+
${M}`),m+=M.length}catch{}}}let bo=xt.length>0?xt.join(`
|
|
144
144
|
|
|
145
|
-
`):"",
|
|
145
|
+
`):"",Tt=[a.def.systemPrompt||"",fo,yo,kn,bo,ho||"",mo||""].filter(p=>p.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,
|
|
148
|
-
`),
|
|
147
|
+
`)||void 0,In={channel:h,chatId:$,channelScope:e.context?.group?"group":h==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,h),systemPrompt:a.def.systemPrompt,sender:yt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||Qr(h,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:oo||void 0,procedureContext:hn,references:fn,skillInjection:pn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:wn??qe,memoryContext:ln||void 0,crossChatContext:yn||void 0,longMemoryRecall:bn||void 0,wikiContext:co,handoverNote:this.buildHandoverNote(e.agentId,h,$),rotationMemo:uo,eventDigest:j?void 0:za(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=hs(h,!j,a.def.richMessages);return p?Ya(a.def.workspace,p):void 0})(),intent:X?{path:X.path,pathLabel:X.pathLabel,pathId:X.pathId,axes:X.axes,leaf:X.leaf,status:X.status}:void 0,message:e.message},ze=le.active&&le.preprocess?await w("select-context",()=>to(In)):{input:In,excluded:[]};ze.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${ze.excluded.join(", ")}`);let Xe=or(ze.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),wo=Xn(Xe,{memory:gn,procedures:mn,wikiContext:ze.input.wikiContext}),kt=(Xe?.length??0)+(Tt?.length??0)+(e.message?.length??0),Ye={history:Xe?.length??0,sysPrompt:Tt?.length??0,message:e.message?.length??0},Sn=Cr(e.agentId,h,$);Ar(Sn,kt,Ye);let vn=$r(Sn);vn&&this.log(`[${e.agentId}] ${vn}`),kt>16e3&&this.log(`[${e.agentId}] large context for ${h}:${$}: ${kt} bytes (history=${Ye.history}, sysPrompt=${Ye.sysPrompt}, message=${Ye.message})`);let It,Cn=Ln(a.def.tier,this.config.decisions.routing);if(!e.model&&Cn&&(!le.active||le.preprocess))try{let{routeTaskModel:p}=await import("./routing-O2WE73C7.js"),m=await w("route-model",()=>p({message:e.message,agent:e.agentId,channel:h,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,h,$),cheapModel:Cn}));m.downgraded&&(It=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let xo={...e,systemPromptAppend:Tt,...It?{model:It}:{}},ge,An=Wr({agent:e.agentId,request:e.message,taskId:b,budgetMinutes:a.def.maxExecutionMinutes??20}),To=P;P=p=>{An.observe(p),To?.(p)};try{let p=this.workflowAutoRunner;if(be&&p){let B=be;try{let J=await w("workflow-auto-run",()=>p({workflowId:B.workflowId,agentId:e.agentId,channel:h,chatId:$,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:h,chatId:$,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:X?.path,matchedWorkflowId:B.workflowId,matchConfidence:B.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),ge={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:J.runId,workflowMatchConfidence:be.confidence}},ge}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(a.def.tier==="claude-code"){I("dispatch-gate");let B=a.def.persistentProcess?rt():null,J=B!=null&&B.hasLive({agentId:e.agentId,channel:h,chatId:$}),oe=!!j||J,ne=[br(oe),Sr(oe)].find(Pe=>Pe&&Pe.abort);if(ne){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ne.reason}`);let Pe={content:"",error:ne.message,duration:0};if(!t){y.buffer=`[error] ${ne.message}`;for(let ko of y.subscribers)try{ko(y.buffer)}catch{}}return ge=Pe,Pe}kr();let Re=vr();Re&&this.log(`[${e.agentId}] ${Re}`)}let m=a.def.tier==="claude-code",S=m?t:(B,J)=>{B&&T(B),t&&t(B,J)},R=!1,W=m?n:B=>{B&&(R?T(B):(T(`\u{1F4AD} ${B}`),R=!0)),n&&n(B)},Q=()=>{R&&(T(`
|
|
148
|
+
`),R=!1)},pe=m?S:S?(B,J)=>{Q(),S(B,J)}:void 0,M=await w("agent",()=>Js(a.def,xo,this.providers,pe,Xe,j,P,f.signal,W),qa);if(!M.error){let B=Va(a.def.toolUseRequired,v);if(B){let J=Array.from(v.entries()).map(([oe,Ve])=>`${oe}=${Ve}`).join(", ")||"none";M.error=`tool_required_not_called: ${B} (invoked: ${J})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${B}, observed ${J}`)}}let St=this.interruptedRuns.get(g.id);St&&(M.content="",M.error=St,M.errorKind="interrupted"),ge=M;let re=M.usage?sr(M.usage):void 0;if(V().emit("task:completed",{taskId:b,agentId:e.agentId,channel:h,chatId:$,durationMs:Date.now()-an,error:M.error||void 0,interrupted:St?!0:void 0,inputTokens:re?.inputTokens,outputTokens:re?.outputTokens,cacheReadTokens:re?.cacheReadTokens,cacheCreateTokens:re?.cacheCreateTokens,tier2InputTokens:re?.tier2InputTokens,tier2OutputTokens:re?.tier2OutputTokens,tier2CacheReadTokens:re?.tier2CacheReadTokens,tier2CacheCreateTokens:re?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:le.arm,numTurns:M.numTurns,injectedContext:wo,finalResponse:M.content||void 0,billedModel:M.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let B=M.error?`[error] ${M.error}`:M.content;y.buffer=B;for(let J of y.subscribers)try{J(B)}catch{}}if(M.error)a.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,h,$,M.content),qr({agent:e.agentId,channel:h,chatId:$,request:e.message,reply:M.content,taskId:b}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,h,$,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,h,$,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,h,$,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,h,$,M.usage,M.contextTokens),M.usage){let ne=M.contextTokens,Re=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(ne??Re)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${h}:${$}: context=${ne??"n/a"} tokens (cumulative turn total=${Re}) \u2014 next turn will rotate`)}if(qn({channel:h,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await dn(ja);try{let ne=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ne,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:h,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
|
-
Agent: ${
|
|
151
|
-
`)}export{xs as a,
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
Agent: ${M.content}`,meta:Qa(X,e.context)})}catch{}Gn(e.agentId,e.message,M.content,{channel:h,chatId:$,sender:yt},this.memoryStore).catch(()=>{}),gr(e.agentId,e.message,M.content,{channel:h,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=M.billedModel||e.model||a.def.model,oe=e.context?.channel,Ve=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,J,oe,Ve),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${U()}`)}return M}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let m=nt(p.message);return ge={content:"",error:st(m),errorKind:m.kind},ge}finally{An.stop(),O(ge)}}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=K(process.cwd(),$e,this.safe(e.agentId),t);Z(n)||Ua(n,{recursive:!0});let r=K(n,`${this.safe(e.id)}.json`);Wa(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 o=new Array(t).fill(0),i=n-t*36e5,a=K(process.cwd(),$e,this.safe(e));if(!Z(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;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=K(a,u);if(Z(g))try{for(let f of se(g)){if(!f.endsWith(".json"))continue;let y=f.split("-")[0],T=parseInt(y,10);if(!Number.isFinite(T)||T<i||T>n)continue;let b=Math.floor((n-T)/36e5),v=t-1-b;v>=0&&v<t&&o[v]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),$e);if(!Z(e))return 0;let t=0;for(let n of se(e)){let r=K(e,n),o;try{o=se(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=se(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(We(K(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=Ja){let t=K(process.cwd(),$e);if(!Z(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of se(t)){let i=K(t,o),a;try{a=se(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Ba(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=K(process.cwd(),$e,this.safe(e));if(!Z(n))return[];let r=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(n,i),c;try{c=se(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(We(K(a,d),"utf-8")),{transcript:u,responseText:g,...f}=l;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let n=K(process.cwd(),$e,this.safe(e));if(!Z(n))return null;let r=this.safe(t),o=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(n,i,`${r}.json`);if(Z(a))try{return JSON.parse(We(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ls();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||tt(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,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(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}: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 o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.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 o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,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(i,a,c),f=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),f=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:f,edited:u,pending:g}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let 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:o.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=>{tt(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 ec(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{xs as a,cc as b,ks as c,Eo as d,Is as e,Cs as f,xc as g,Sc as h,vc as i,Xo as j,Ks as k,ti as l,ni as m,si as n,Js as o,dt as p,ut as q,ed as r,Jt as s,V as t,pr as u,Li as v,Ui as w,fr as x,yd as y,yr as z,Be as A,va as B,Ca as C,Aa as D,$a as E,Ma as F,Zt as G,Yu as H,Vu as I,Qa as J,za as K,Xa as L,on as M,Xr as N,Yr as O,Va as P,Vr as Q,Zr as R,ec as S};
|
|
152
|
+
//# sourceMappingURL=chunk-PNTFOROF.js.map
|