agentix-cli 0.104.1 → 0.105.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-A7WZMOGA.js → App-2SSUXHUJ.js} +2 -2
- package/dist/{ChatApp-EWNT36ZE.js → ChatApp-RLOFB5CO.js} +2 -2
- package/dist/{agent-NPE76XHC.js → agent-PP6UH3O2.js} +2 -2
- package/dist/{board-dashboard-5EPKRDEW.js → board-dashboard-O3AYVTTF.js} +4 -4
- package/dist/{chunk-CUS7WGZT.js → chunk-2XLOIA52.js} +2 -2
- package/dist/{chunk-IA3BC7M3.js → chunk-3MMSS5JF.js} +2 -2
- package/dist/{chunk-IA3BC7M3.js.map → chunk-3MMSS5JF.js.map} +1 -1
- package/dist/{chunk-MVLNVMWI.js → chunk-4FSU5XTD.js} +2 -2
- package/dist/{chunk-BUAVQUHR.js → chunk-AK4HS2PQ.js} +2 -2
- package/dist/{chunk-N4IWNCH3.js → chunk-BBKFCHJV.js} +2 -2
- package/dist/{chunk-HE4PDESB.js → chunk-BTHH5ENX.js} +2 -2
- package/dist/{chunk-OLUAEBHJ.js → chunk-D6EX6VA5.js} +2 -2
- package/dist/{chunk-DEMIKEFB.js → chunk-DXOTH6MF.js} +30 -30
- package/dist/chunk-DXOTH6MF.js.map +1 -0
- package/dist/{chunk-76KJXOEV.js → chunk-E4RQHTNB.js} +2 -2
- package/dist/{chunk-MZQQVT3G.js → chunk-EB3B2FRY.js} +2 -2
- package/dist/{chunk-IO74N5DB.js → chunk-HFZTZVQW.js} +85 -85
- package/dist/chunk-HFZTZVQW.js.map +1 -0
- package/dist/{chunk-FZ7VHFL5.js → chunk-IM7SSJ67.js} +2 -2
- package/dist/{chunk-XHUOWYNY.js → chunk-J5LOMJ2Y.js} +2 -2
- package/dist/{chunk-ZBKKOUNJ.js → chunk-KPAGMXSL.js} +2 -2
- package/dist/{chunk-IOPAWHKW.js → chunk-KU3XT5S2.js} +2 -2
- package/dist/{chunk-NWNVHL57.js → chunk-N7YQ4IAR.js} +2 -2
- package/dist/{chunk-WTFNEPJ7.js → chunk-OREGWHKS.js} +2 -2
- package/dist/{chunk-32BPHJ4I.js → chunk-QFIIZIYX.js} +2 -2
- package/dist/{chunk-BEFKOHRC.js → chunk-UGM56ULD.js} +2 -2
- package/dist/{chunk-25RQQ55U.js → chunk-UGNXKP6Q.js} +2 -2
- package/dist/{chunk-Q57GZPDA.js → chunk-ZE7P7L2L.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-ZX7AY7H3.js → client-LK2BLOBZ.js} +2 -2
- package/dist/{config-BXOS2PLC.js → config-OQKZUWUT.js} +2 -2
- package/dist/config-mutator-S3FP3A7K.js +2 -0
- package/dist/{doctor-P3QQP33C.js → doctor-ON2EECFT.js} +2 -2
- package/dist/index.d.ts +12 -1
- package/dist/index.js +1 -1
- package/dist/{program-SAEPPSSW.js → program-G4IWH53Z.js} +14 -14
- package/dist/{promote-FHX4Q62Z.js → promote-KKLC2ENK.js} +2 -2
- package/dist/{query-WBK3YEPV.js → query-JEOWXBWZ.js} +2 -2
- package/dist/{registry-T5HSN66G.js → registry-6DGUQ5YT.js} +2 -2
- package/dist/{request-planner-3LA5RAKG.js → request-planner-SXR7HCE7.js} +2 -2
- package/dist/{review-candidates-QV66TOCL.js → review-candidates-OBAXZ6IM.js} +2 -2
- package/dist/{routing-HF4XVD4Y.js → routing-GW7LSHRJ.js} +2 -2
- package/dist/schedule-tool-TX7EPMQZ.js +2 -0
- package/dist/scheduler-4SD7YBW3.js +2 -0
- package/dist/{seat-NQTZUIKH.js → seat-4KA3YZEN.js} +2 -2
- package/dist/{select-3GVC5RDA.js → select-WLYRCSSM.js} +2 -2
- package/dist/{set-enabled-SXCE2MZX.js → set-enabled-DHSDYIIA.js} +2 -2
- package/dist/{tool-23GOQNUW.js → tool-OBS4P2BP.js} +2 -2
- package/dist/{tool-E6JBENAN.js → tool-YKBDZ7K7.js} +2 -2
- package/dist/wiki-237HZZNR.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-DEMIKEFB.js.map +0 -1
- package/dist/chunk-IO74N5DB.js.map +0 -1
- package/dist/config-mutator-KRAUD3CA.js +0 -2
- package/dist/schedule-tool-V66FX5XL.js +0 -2
- package/dist/scheduler-XVMWASQR.js +0 -2
- package/dist/wiki-VM2RTHVF.js +0 -2
- /package/dist/{App-A7WZMOGA.js.map → App-2SSUXHUJ.js.map} +0 -0
- /package/dist/{ChatApp-EWNT36ZE.js.map → ChatApp-RLOFB5CO.js.map} +0 -0
- /package/dist/{agent-NPE76XHC.js.map → agent-PP6UH3O2.js.map} +0 -0
- /package/dist/{board-dashboard-5EPKRDEW.js.map → board-dashboard-O3AYVTTF.js.map} +0 -0
- /package/dist/{chunk-CUS7WGZT.js.map → chunk-2XLOIA52.js.map} +0 -0
- /package/dist/{chunk-MVLNVMWI.js.map → chunk-4FSU5XTD.js.map} +0 -0
- /package/dist/{chunk-BUAVQUHR.js.map → chunk-AK4HS2PQ.js.map} +0 -0
- /package/dist/{chunk-N4IWNCH3.js.map → chunk-BBKFCHJV.js.map} +0 -0
- /package/dist/{chunk-HE4PDESB.js.map → chunk-BTHH5ENX.js.map} +0 -0
- /package/dist/{chunk-OLUAEBHJ.js.map → chunk-D6EX6VA5.js.map} +0 -0
- /package/dist/{chunk-76KJXOEV.js.map → chunk-E4RQHTNB.js.map} +0 -0
- /package/dist/{chunk-MZQQVT3G.js.map → chunk-EB3B2FRY.js.map} +0 -0
- /package/dist/{chunk-FZ7VHFL5.js.map → chunk-IM7SSJ67.js.map} +0 -0
- /package/dist/{chunk-XHUOWYNY.js.map → chunk-J5LOMJ2Y.js.map} +0 -0
- /package/dist/{chunk-ZBKKOUNJ.js.map → chunk-KPAGMXSL.js.map} +0 -0
- /package/dist/{chunk-IOPAWHKW.js.map → chunk-KU3XT5S2.js.map} +0 -0
- /package/dist/{chunk-NWNVHL57.js.map → chunk-N7YQ4IAR.js.map} +0 -0
- /package/dist/{chunk-WTFNEPJ7.js.map → chunk-OREGWHKS.js.map} +0 -0
- /package/dist/{chunk-32BPHJ4I.js.map → chunk-QFIIZIYX.js.map} +0 -0
- /package/dist/{chunk-BEFKOHRC.js.map → chunk-UGM56ULD.js.map} +0 -0
- /package/dist/{chunk-25RQQ55U.js.map → chunk-UGNXKP6Q.js.map} +0 -0
- /package/dist/{chunk-Q57GZPDA.js.map → chunk-ZE7P7L2L.js.map} +0 -0
- /package/dist/{client-ZX7AY7H3.js.map → client-LK2BLOBZ.js.map} +0 -0
- /package/dist/{config-BXOS2PLC.js.map → config-OQKZUWUT.js.map} +0 -0
- /package/dist/{config-mutator-KRAUD3CA.js.map → config-mutator-S3FP3A7K.js.map} +0 -0
- /package/dist/{doctor-P3QQP33C.js.map → doctor-ON2EECFT.js.map} +0 -0
- /package/dist/{program-SAEPPSSW.js.map → program-G4IWH53Z.js.map} +0 -0
- /package/dist/{promote-FHX4Q62Z.js.map → promote-KKLC2ENK.js.map} +0 -0
- /package/dist/{query-WBK3YEPV.js.map → query-JEOWXBWZ.js.map} +0 -0
- /package/dist/{registry-T5HSN66G.js.map → registry-6DGUQ5YT.js.map} +0 -0
- /package/dist/{request-planner-3LA5RAKG.js.map → request-planner-SXR7HCE7.js.map} +0 -0
- /package/dist/{review-candidates-QV66TOCL.js.map → review-candidates-OBAXZ6IM.js.map} +0 -0
- /package/dist/{routing-HF4XVD4Y.js.map → routing-GW7LSHRJ.js.map} +0 -0
- /package/dist/{schedule-tool-V66FX5XL.js.map → schedule-tool-TX7EPMQZ.js.map} +0 -0
- /package/dist/{scheduler-XVMWASQR.js.map → scheduler-4SD7YBW3.js.map} +0 -0
- /package/dist/{seat-NQTZUIKH.js.map → seat-4KA3YZEN.js.map} +0 -0
- /package/dist/{select-3GVC5RDA.js.map → select-WLYRCSSM.js.map} +0 -0
- /package/dist/{set-enabled-SXCE2MZX.js.map → set-enabled-DHSDYIIA.js.map} +0 -0
- /package/dist/{tool-23GOQNUW.js.map → tool-OBS4P2BP.js.map} +0 -0
- /package/dist/{tool-E6JBENAN.js.map → tool-YKBDZ7K7.js.map} +0 -0
- /package/dist/{wiki-VM2RTHVF.js.map → wiki-237HZZNR.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-
|
|
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()}},Kt=class{constructor(e=li,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([y],[b])=>y.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("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 y=[...this.entries].find(([,b])=>!b.connection.busy);if(!y)throw new de("Codex warm process capacity reached");y[1].connection.close(),this.entries.delete(y[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("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,d="",c,l,u,p=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let m=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 y={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",{...y,...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 I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(y){if(i.close(),!a&&!e.signal?.aborted)throw new de(y.message);return{content:d,codexSessionId:l,usage:u,error:y.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(m),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())}}},Us=new Kt;import{execFile as _i}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(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 c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[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),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function id(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(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"}},Ws=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=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(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=He(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=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(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=He(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(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{randomUUID as mi}from"crypto";import{existsSync as hi,readFileSync as fi}from"fs";import{resolve as yi}from"path";function bi(s){let e=yi(s,"CLAUDE.md");if(!hi(e))return null;try{let t=fi(e,"utf8");return us(t)}catch{return null}}var wi=20*60*1e3,xi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Ti(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 qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=this.log=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(Ti({...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:bi(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 d=this.waiters.splice(0);for(let c of d)c(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;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(f=>{t=f}),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=mi(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
|
-
`);let d=e.deadlineMs??wi,c=o+d,l=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new je(d)),u=!1,p=null;try{for(;;){let f=c-Date.now();if(f<=0)throw l();let m=await this.nextEvent(f);if(m===null&&this.killReason)throw new Ue(this.killReason);if(m===null&&!this.exited)throw l();if(m===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!u){if(m.type==="user"&&m.uuid===i)u=!0,p&&(yield{type:p.type,raw:p});else if(m.type==="system"&&m.subtype==="init")p=m;else if(m.type==="result"){p=null;let
|
|
1
|
+
import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-IM7SSJ67.js";import{a as fs}from"./chunk-GLQLCBJS.js";import{b as ws}from"./chunk-DP7RTNDM.js";import{a as Ps}from"./chunk-W4YR2RO2.js";import{b as ks,c as Bt,d as Ss,e as vs,h as Cs}from"./chunk-4FSU5XTD.js";import{a as hs}from"./chunk-J5LOMJ2Y.js";import{a as jt,b as Ts}from"./chunk-J3SOEFRE.js";import{a as Ut,b as Is}from"./chunk-SIU6STB2.js";import{e as As,i as $s,j as Ms,k as Rs}from"./chunk-X5C5W3E4.js";import{a as ss}from"./chunk-OREGWHKS.js";import{a as rs,c as os}from"./chunk-MYVHVJWZ.js";import{a as is,b as as,c as cs,d as ds,f as us}from"./chunk-DWADWDMU.js";import{a as ls,b as gs}from"./chunk-23A5K5UW.js";import{g as ps,h as ms}from"./chunk-ZE7P7L2L.js";import{a as at,c as Le}from"./chunk-2GIDVZ4H.js";import{q as es,t as ts,v as xe,w as ns}from"./chunk-BTHH5ENX.js";import{a as Ne,b as it,f as Ht}from"./chunk-72SZI2UW.js";import{a as we,b as Dt}from"./chunk-FCPTN6NF.js";import{c as Bn,d as Wn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{B as Ft,D as oi,F as Qn,J as ii,P as zn,Q as Xn,R as Oe,S as Yn,T as Vn,V as Zn,ha as ai,z as Jn}from"./chunk-3MMSS5JF.js";import{a as Lt,i as ri}from"./chunk-RJ7DASOU.js";import{g as Nt,h as si}from"./chunk-BRK6M6LA.js";import{a as qn,b as oe,c as Kn,d as Gn,e as Ot}from"./chunk-2QNT5JDS.js";ns();Ht();var Ls="session-continuity",Fs={continues:Ne("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:Ne("Does the new request refer to something stated earlier in the conversation?")};function Hs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Wt(s.message,1200),previousRequest:s.previousMessage?Wt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Wt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function js(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 Wt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ht}from"execa";import{spawn as ci}from"node:child_process";import{createHash as di}from"node:crypto";import{createInterface as ui}from"node:readline";var de=class extends Error{},li=s=>ci("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),qt=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(),ui({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()}},Kt=class{constructor(e=li,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[I])=>b.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("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(([,I])=>!I.connection.busy);if(!b)throw new de("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("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,d="",c,l,u,p,f=!1,m=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let k=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),y=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(y),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let E=new Promise((D,$)=>{i.failTurn=$,i.notify=(O,L)=>{if(L?.threadId!==l)return;let P=L.item,F={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...L,type:O.replace("/","."),...P?{item:{...P,type:F[P.type]||P.type}}:{}}),O==="item/completed"&&P?.type==="agentMessage"&&P.phase==="final_answer"&&(c=P.text),O==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=L.delta,e.onDelta?.(L.delta,d)),O==="thread/tokenUsage/updated"){let H=L.tokenUsage.last;p=H.inputTokens;let j=H.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-j),outputTokens:(u?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+j,cacheCreateTokens:(u?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}O==="turn/completed"&&(L.turn.status==="completed"?D():$(new Error(L.turn.error?.message||`Codex turn ${L.turn.status}`)))}});return E.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await E,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,contextTokens:p,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new de(b.message);return{content:d,codexSessionId:l,usage:u,contextTokens:p,error:b.message,duration:Date.now()-t}}finally{clearTimeout(y),clearTimeout(k),e.signal?.removeEventListener("abort",m),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())}}},Us=new Kt;import{execFile as _i}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(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 c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[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),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function id(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(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"}},Ws=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=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(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=He(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=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(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=He(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(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{randomUUID as mi}from"crypto";import{existsSync as hi,readFileSync as fi}from"fs";import{resolve as yi}from"path";function bi(s){let e=yi(s,"CLAUDE.md");if(!hi(e))return null;try{let t=fi(e,"utf8");return us(t)}catch{return null}}var wi=20*60*1e3,xi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Ti(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 qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=this.log=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(Ti({...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:bi(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 d=this.waiters.splice(0);for(let c of d)c(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;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(f=>{t=f}),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=mi(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
|
+
`);let d=e.deadlineMs??wi,c=o+d,l=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new je(d)),u=!1,p=null;try{for(;;){let f=c-Date.now();if(f<=0)throw l();let m=await this.nextEvent(f);if(m===null&&this.killReason)throw new Ue(this.killReason);if(m===null&&!this.exited)throw l();if(m===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!u){if(m.type==="user"&&m.uuid===i)u=!0,p&&(yield{type:p.type,raw:p});else if(m.type==="system"&&m.subtype==="init")p=m;else if(m.type==="result"){p=null;let k=typeof m.result=="string"?m.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${k.length} chars): ${k.slice(0,120)}`)}continue}if(yield{type:m.type,raw:m},m.type==="result"){this.onResultEvent(m);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},xi);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let 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"}}};Ot();ri();Dt();import{resolve as Ks,join as Gs}from"path";var ki=4e3;function lt(s){try{let e=Gs(Ks(s.root),".agentx","db.sqlite"),t=Lt({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,ki):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)
|
|
@@ -15,29 +15,29 @@ ${e.trim()}
|
|
|
15
15
|
[User]
|
|
16
16
|
${s}`}function Di(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(Qt(e,n)),o}function Oi(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 sr(s){return JSON.stringify(s)}function lr(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${sr(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(sr).join(",")}]`]}function gr(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...lr()),i||a.push("--color","never");let d=n||s.model;return d&&a.push("--model",d),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(Qt(e,r)),a}function ft(s,e){let t=at(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(":"),zt(t,e)}function zt(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 yt(s={}){return{channel:s.channel||"api",chatId:s.chatId||s.group||s.sender||"default"}}function Ni(s,e){let t=ft(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 Li(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 ue(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Xt(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:ue(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ue(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ue(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ue(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Xt(n,e+1);if(r)return r}}function pr(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 Yt(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=Yt(t,e+1);if(n)return n}}}function Fi(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
|
|
17
17
|
`))if(i.trim())try{let a=JSON.parse(i);t=Xt(a)||t,n=pr(a)||n,r=Yt(a)||r,o=mr(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function mr(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return rr(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return rr(e)}}}function rr(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 Hi(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 Vt(s,e,t,n,r){let o=Hi(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 ji(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 Ui(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 hr(s,e,t,n,r){let o=Date.now(),i=le(s,e,t),a=yr(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=ur(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Vt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:p,exitCode:f,killed:m}=await new Promise(b=>{let I=Le(zt(at(s.workspace),e),s.billing),E=!1,
|
|
19
|
-
`);
|
|
18
|
+
`)}function ji(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 Ui(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 hr(s,e,t,n,r){let o=Date.now(),i=le(s,e,t),a=yr(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=ur(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Vt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:p,exitCode:f,killed:m}=await new Promise(b=>{let I=Le(zt(at(s.workspace),e),s.billing),E=!1,D=_i("claude",d,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...I,HOME:I.HOME||"/home/"+(I.USER||"user")}},($,O,L)=>{b({stdout:O||"",stderr:L||"",exitCode:$?$.code??1:0,killed:E})});if(D.stdin?.end(),r){let $=()=>{E=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.killed||D.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?$():r.addEventListener("abort",$,{once:!0})}});if(m)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&f!==0){let b,I=Date.now()-o;return f===143&&I<l-Ei?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(I/1e3)}s, before its ${Math.round(l/6e4)}m time limit`,errorKind:"interrupted",duration:I}:(f===143?b=`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(p||"")?b=dr():b=p?.trim()||`Claude Code exited with code ${f}`,{content:"",...Q(b),duration:Date.now()-o})}let k=ji(u);if(k)return{content:"",...Q(k),duration:Date.now()-o};let y=Ui(u);return{content:y.text,duration:Date.now()-o,claudeSessionId:y.sessionId,usage:y.usage,numTurns:y.numTurns,billedModel:y.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function fr(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 d=le(s,e,n),c=yr(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let l=ur(s,d,!0,r,e.model,e.systemPromptAppend,c.args);Vt(e.agentId,s,e.model,r,"stream");let u="",p,f,m,k,y,b;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),E=Le(zt(at(s.workspace),e),s.billing),D=ht("claude",l,{cwd:s.workspace,timeout:I,reject:!1,env:E,extendEnv:!1,buffer:!1,stdin:"ignore"}),$=()=>{},O=new Promise(C=>{$=C}),L=!1,P;if(i){let C=()=>{L=!0,P=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?C():i.addEventListener("abort",C,{once:!0})}let F="",H=new We("utf8");D.stdout&&D.stdout.on("data",C=>{F+=H.write(C);let v=F.split(`
|
|
19
|
+
`);F=v.pop()||"";for(let w of v)if(w.trim())try{let x=JSON.parse(w);if(o)try{o(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let N=x.message.usage,M=(N.input_tokens||0)+(N.cache_read_input_tokens||0)+(N.cache_creation_input_tokens||0);M>0&&(k=M)}if(x.type==="assistant"&&x.message?.content){for(let N of x.message.content)if(N.type==="text"&&N.text){let M=N.text.slice(u.length);M&&(u=N.text,t(M,u))}}if(x.type==="content_block_delta"&&x.delta?.text&&(u+=x.delta.text,t(x.delta.text,u)),x.type==="result"&&$(),x.type==="result"&&x.result){if(x.is_error&&typeof x.result=="string")b=x.result;else{let N=(typeof x.result=="string",x.result);if(typeof N=="string"&&N.length>u.length){let M=N.slice(u.length);u=N,M&&t(M,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"&&(p=x.model),typeof x.session_id=="string"&&(m=x.session_id),typeof x.num_turns=="number"&&(y=x.num_turns)}x.type==="system"&&x.subtype==="init"&&(typeof x.model=="string"&&(p=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 j=await Qi(
|
|
23
|
-
`);I=w.pop()||"";for(let x of w)if(x.trim())try{let N=JSON.parse(x);if(o)try{o(N)}catch{}p=Xt(N)||p,f=pr(N)||f,m=Yt(N)||m,
|
|
22
|
+
`,u))}});let j=await Qi(D,O),K=H.end();if(K&&(F+=K),L)return{content:"",error:P||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&j.stdout&&(u=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!u){let C=typeof j.stderr=="string"?j.stderr:"",v=j,w;return v.timedOut?w=`Claude Code timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:v.signal?w=C.trim()||`Claude Code killed by signal ${v.signal}`:v.code==="ENOENT"||/ENOENT|spawn claude/i.test((v.shortMessage||"")+" "+C)?w=dr():w=C.trim()||`Claude Code exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-a}}return b?{content:"",...Q(b),duration:Date.now()-a,usage:f,contextTokens:k,numTurns:y,billedModel:p,claudeSessionId:m}:{content:u,duration:Date.now()-a,usage:f,contextTokens:k,numTurns:y,billedModel:p,claudeSessionId:m}}catch(I){return{content:u||"",...Q(I.message),duration:Date.now()-a,usage:f,contextTokens:k,numTurns:y,billedModel:p,claudeSessionId:m}}}async function Bi(s,e,t,n){let r=Date.now(),o=le(s,e,t),i=or(pt(cr(),"agentx-codex-")),a=pt(i,"last-message.txt"),d=gr(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let c=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await ht("codex",d,{cwd:s.workspace,timeout:c,reject:!1,env:ft(s,e),extendEnv:!1,stdin:"ignore"}),u=Fi(l.stdout);if(l.exitCode!==0||u.apiError){let f=l,m;return f.timedOut?m=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?m=u.apiError:f.signal?m=l.stderr.trim()||`Codex CLI killed by signal ${f.signal}`:f.code==="ENOENT"||/ENOENT|spawn codex/i.test((f.shortMessage||"")+" "+l.stderr)?m=mt():m=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${f.exitCode??"unknown"}`,{content:"",...Q(m),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let p="";try{p=ir(a,"utf8").trim()}catch{}return p||(p=l.stdout.trim()),{content:p,duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}catch(c){let l=/ENOENT|spawn codex/i.test(c?.message||"")?mt():c?.message;return{content:"",...Q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{ar(i,{recursive:!0,force:!0})}}async function Wi(s,e,t,n,r,o){let i=Date.now(),a=le(s,e,n),d=or(pt(cr(),"agentx-codex-")),c=pt(d,"last-message.txt"),l=gr(s,a,!0,e.model,e.systemPromptAppend,c,r),u="",p,f,m,k;try{let y=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),b=ht("codex",l,{cwd:s.workspace,timeout:y,reject:!1,env:ft(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let I="",E="",D=!1,$=new We("utf8"),O=new We("utf8"),L=Math.min(y,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),P,F=()=>{P&&clearTimeout(P),P=setTimeout(()=>{D=!0,b.kill("SIGTERM",{forceKillAfterTimeout:5e3})},L)};F(),b.stderr?.on("data",v=>{F(),E+=O.write(v),E.length>16e3&&(E=E.slice(-16e3))}),b.stdout?.on("data",v=>{F(),I+=$.write(v);let w=I.split(`
|
|
23
|
+
`);I=w.pop()||"";for(let x of w)if(x.trim())try{let N=JSON.parse(x);if(o)try{o(N)}catch{}p=Xt(N)||p,f=pr(N)||f,m=Yt(N)||m,k=mr(N)||k;let M=Li(N);if(M&&M!==u){let V=M.startsWith(u)?M.slice(u.length):M;u=M.startsWith(u)?M:u+M,V&&t(V,u)}}catch{u+=x+`
|
|
24
24
|
`,t(x+`
|
|
25
|
-
`,u)}});let H=await b;
|
|
25
|
+
`,u)}});let H=await b;P&&clearTimeout(P);let j=$.end();j&&(I+=j);let K=O.end();if(K&&(E+=K),H.exitCode!==0&&!u||k){let v=E||(typeof H.stderr=="string"?H.stderr:""),w=H,x;return D?x=`Codex CLI produced no output for ${Math.round(L/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:w.timedOut?x=`Codex CLI timed out after ${Math.round(y/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:k?x=k:w.signal?x=v.trim()||`Codex CLI killed by signal ${w.signal}`:w.code==="ENOENT"||/ENOENT|spawn codex/i.test((w.shortMessage||"")+" "+v)?x=mt():x=v.trim()||`Codex CLI exited with code ${w.exitCode??"unknown"}`,{content:"",...Q(x),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}let C="";try{C=ir(c,"utf8").trim()}catch{}if(C&&C!==u){let v=C.startsWith(u)?C.slice(u.length):C;u=C,v&&t(v,u)}return{content:u,duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}catch(y){let b=/ENOENT|spawn codex/i.test(y?.message||"")?mt():y?.message;return{content:u,...Q(b||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}finally{ar(d,{recursive:!0,force:!0})}}async function qi(s,e,t,n,r,o,i,a){let d=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let c=le(s,e,n),l=Di(s,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",p,f=e.freshSession?void 0:r,m,k,y=!0,b;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),E=Ni(s,e);if(s.persistentProcess)try{k=await os.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:E,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",k.url),E=k.env,o?.({type:"opencode.ready",reused:k.reused,startupMs:Date.now()-d})}catch(v){if(!(v instanceof rs))throw v;v.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:v.message})}if(i?.aborted)throw new Error("task cancelled by operator");let D=ht("opencode",l,{cwd:s.workspace,timeout:I,reject:!1,env:E,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let $=!1,O,L=()=>{k?.invalidate(),$=!0,O=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{D.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",L,{once:!0}),b=()=>i?.removeEventListener("abort",L),i?.aborted&&L();let P="",F="",H=new We("utf8"),j=new We("utf8"),K=v=>{if(v.trim())try{let w=JSON.parse(v);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()-d,reused:k?.reused??!1}),u+=x,t?.(x,u));let N=w.type==="reasoning"&&typeof w.part?.text=="string"?w.part.text:void 0;N&&a?.(N);let M=w.type==="step_finish"?w.part?.tokens:void 0;M&&(p={inputTokens:ue(M.input),outputTokens:ue(M.output),cacheReadTokens:ue(M.cache?.read),cacheCreateTokens:ue(M.cache?.write)}),m=Oi(w)||m}catch{u+=v+`
|
|
26
26
|
`,t?.(v+`
|
|
27
|
-
`,u)}};
|
|
28
|
-
`);
|
|
27
|
+
`,u)}};D.stdout?.on("data",v=>{P+=H.write(v);let w=P.split(`
|
|
28
|
+
`);P=w.pop()||"";for(let x of w)K(x)}),D.stderr?.on("data",v=>{F+=j.write(v)});let C=await D;if(i&&i.removeEventListener("abort",L),P+=H.end(),P.trim()&&K(P),F+=j.end(),$)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:f};if(C.exitCode!==0||m){let v=C,w;return v.timedOut?w=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:m?w=m:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+F)?w=nr():w=F.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-d,usage:p,opencodeSessionId:f}}return y=!1,{content:u.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||s.model,opencodeSessionId:f}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?nr():I?.message;return{content:u,...Q(E||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:f}}finally{b?.(),k?.release(y)}}async function Ki(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=le(s,e,n),d="",c=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of c)l.type==="result"&&l.subtype==="success"&&(d=l.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Gi(s,e,t,n,r,o,i,a,d){let c=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,f=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(y))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let m=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);m.unref?.();let k=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let y=s.provider||"claude-code",b=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),D=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,$=ds(s),O=Object.keys($).length>0,L={task:b,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:D,providerOpts:o,abortSignal:u.signal,mcpServers:O?$:void 0};if(r){let{generateStream:K}=await import("./agent-PP6UH3O2.js"),C="",v,w,x,N;for await(let M of K(L)){if(d)try{d(M)}catch{}if(M.type==="text_delta")C+=M.text,r(M.text,C);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==C){let V=M.result.content.slice(C.length);V?(C=M.result.content,r(V,C)):C=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==C){let V=M.result.content.slice(C.length);V?(C=M.result.content,r(V,C)):C=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!C?p?k():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:C||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:P}=await import("./agent-PP6UH3O2.js"),F=await P(L),H=F.inputTokens,j=F.outputTokens;if((H===void 0||j===void 0)&&F.tokensUsed){let K=F.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:F.content||"Done.",tokensUsed:F.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?k():y?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(m),a&&a.removeEventListener("abort",f)}}var Ji=1e3;async function Qi(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"}),Ji),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 zi(s,e,t,n,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=yt(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,f=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,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>C}catch(C){return C instanceof Te,null}f&&Vt(e.agentId,s,e.model,n,"persistent");let m=le(s,e,t),k="",y,b,I,E,D,$,O,L="",P="",F=C=>{if(!i||!C)return;let v;if(P&&C.startsWith(P)?v=C.slice(P.length):v=L&&!L.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
|
-
${
|
|
33
|
+
${C}`:C,P=C,!!v){L+=v;try{i(v,L)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:m,taskId:e.taskId??"unknown",deadlineMs:C})){if(K=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let w=v.raw.message?.content??[];for(let N of w)N.type==="text"&&typeof N.text=="string"?(k=N.text,F(N.text)):N.type==="tool_use"&&(P="");let x=v.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(E=N)}}if(v.type==="result"){let w=v.raw;if(w.is_error){let x=Q(typeof w.result=="string"?w.result:"claude error");y=x.error,b=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(k=w.result,L||F(w.result));typeof w.session_id=="string"&&(O=w.session_id),w.usage&&(I={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"&&(D=w.num_turns),typeof w.message?.model=="string"?$=w.message.model:typeof w.model=="string"&&($=w.model)}}}catch(C){if(H)y="task cancelled by operator",b="cancelled";else if(K)if(C instanceof Ue)y=`Claude Code was stopped mid-turn (${C.reason}), before its time limit`,b="interrupted";else if(C instanceof je){let v=Q(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);y=v.error,b=v.errorKind}else{let v=Q(`persistent claude process error: ${C?.message||String(C)}`);y=v.error,b=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!y&&(y="task cancelled by operator",b="cancelled"),{content:H?"":k,error:y,errorKind:b,duration:Date.now()-d,usage:I,contextTokens:E,numTurns:D,billedModel:$,claudeSessionId:O}}function yr(s){let e=oe(s.autonomy);if(!e&&!s.personLimits)return{args:[]};if(!s.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?zs(s.autonomy,s.agentId,s.taskId):{args:[]};return"error"in t||!s.personLimits?t:er(t.args,s.taskId,s.agentId)}function Xi(s){return oe(s.autonomy)||!!s.personLimits}async function Yi(s,e,t,n,r,o,i){let a=oe(e.autonomy)?e.autonomy:void 0,d=a&&Xs(a,s.tier)||e.personLimits&&tr(s.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:c,message:a?`${Gn(a)}
|
|
34
34
|
|
|
35
35
|
${e.message}`:e.message},u=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${u} task=${c} via=spawn (persistent process bypassed)
|
|
36
|
-
`),e.personLimits&&Vs(c,e.personLimits);try{let p=t?await fr(s,l,t,n,r,o,i):await hr(s,l,n,r,i);if(!a)return p;let f=Ys(c);return{...p,autonomy:a,...f.length?{autonomyBlocks:f}:{}}}finally{e.personLimits&&Zs(c)}}async function br(s,e,t,n,r,o,i,a,d){if(Xi(e))return Yi(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let c=await zi(s,e,r,o,i,a,n);if(c!==null)return c}return n?fr(s,e,n,r,o,i,a):hr(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let c=await Us.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ft(s,e),args:lr(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Qt(le(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{...c,...c.error?Q(c.error):{}}}catch(c){if(!(c instanceof de))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Wi(s,e,n,r,o,i):Bi(s,e,r,o);case"opencode":return qi(s,e,n,r,o,i,a,d);case"sdk":{let c=s.provider||"claude",l=t[c]?.apiKey;return l?Ki(s,e,l,r):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=s.provider||"claude-code",l=t[c],u=l?.apiKey;return Gi(s,e,u,r,n,{thinking:l?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as Ie,writeFileSync as wr,mkdirSync as Vi,existsSync as Zt,readdirSync as en}from"fs";import{resolve as Se}from"path";var tn=12e3,qe=30,Zi=720,ea=40,ta=18e4,na="[Compacted conversation summary",sa=7*864e5,ra=[/\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 oa(s){return s?ra.some(e=>e.test(s)):!1}var ia=[{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 Tr(s){if(!s)return null;let e=0;for(let t of ia)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function xr(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 kr(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 Ir(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 aa(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 bt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Se(e,".agentx/sessions"),Zt(this.sessionsDir)||Vi(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zi),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ea),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ta)}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 d=this.adapterResolver(t);if(!d?.seedHistory)return;let c=(async()=>{try{let l=await d.seedHistory(n,{maxMessages:qe,maxChars:tn});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,c);try{await c}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(Zt(o))try{let c=JSON.parse(Ie(o,"utf-8"));return this.cache.set(r,c),c}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),d={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,d),this.save(d),d}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(!Zt(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);xr(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);xr(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??qe),a=Math.max(200,r.maxChars??tn),d=[],c=0;for(let p=o.messages.length-1;p>=0&&d.length<i;p--){let f=o.messages[p];if(c+=f.content.length,d.push(f),c>=a)break}d.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of d){let f=aa(p.timestamp);f!==u&&(l.push(`\u2014 ${f} \u2014`),u=f);let m=p.name||(p.role==="user"?"User":"Agent");l.push(`${m}: ${p.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,"_"),d;try{d=en(this.sessionsDir).filter(
|
|
36
|
+
`),e.personLimits&&Vs(c,e.personLimits);try{let p=t?await fr(s,l,t,n,r,o,i):await hr(s,l,n,r,i);if(!a)return p;let f=Ys(c);return{...p,autonomy:a,...f.length?{autonomyBlocks:f}:{}}}finally{e.personLimits&&Zs(c)}}async function br(s,e,t,n,r,o,i,a,d){if(Xi(e))return Yi(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let c=await zi(s,e,r,o,i,a,n);if(c!==null)return c}return n?fr(s,e,n,r,o,i,a):hr(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let c=await Us.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ft(s,e),args:lr(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Qt(le(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{...c,...c.error?Q(c.error):{}}}catch(c){if(!(c instanceof de))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Wi(s,e,n,r,o,i):Bi(s,e,r,o);case"opencode":return qi(s,e,n,r,o,i,a,d);case"sdk":{let c=s.provider||"claude",l=t[c]?.apiKey;return l?Ki(s,e,l,r):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=s.provider||"claude-code",l=t[c],u=l?.apiKey;return Gi(s,e,u,r,n,{thinking:l?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as Ie,writeFileSync as wr,mkdirSync as Vi,existsSync as Zt,readdirSync as en}from"fs";import{resolve as Se}from"path";var tn=12e3,qe=30,Zi=720,ea=40,ta=18e4,na="[Compacted conversation summary",sa=7*864e5,ra=[/\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 oa(s){return s?ra.some(e=>e.test(s)):!1}var ia=[{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 Tr(s){if(!s)return null;let e=0;for(let t of ia)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function xr(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 kr(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 Ir(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 aa(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 bt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Se(e,".agentx/sessions"),Zt(this.sessionsDir)||Vi(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zi),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ea),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ta),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([n,r])=>[n,Math.max(5e4,r)]))}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 d=this.adapterResolver(t);if(!d?.seedHistory)return;let c=(async()=>{try{let l=await d.seedHistory(n,{maxMessages:qe,maxChars:tn});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,c);try{await c}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(Zt(o))try{let c=JSON.parse(Ie(o,"utf-8"));return this.cache.set(r,c),c}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),d={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,d),this.save(d),d}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(!Zt(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);xr(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);xr(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??qe),a=Math.max(200,r.maxChars??tn),d=[],c=0;for(let p=o.messages.length-1;p>=0&&d.length<i;p--){let f=o.messages[p];if(c+=f.content.length,d.push(f),c>=a)break}d.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of d){let f=aa(p.timestamp);f!==u&&(l.push(`\u2014 ${f} \u2014`),u=f);let m=p.name||(p.role==="user"?"User":"Agent");l.push(`${m}: ${p.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,"_"),d;try{d=en(this.sessionsDir).filter(D=>D.startsWith(`${a}:`)&&D.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let c=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,p=d.filter(D=>{let $=D.match(u);if(!$)return!1;let O=$[1];return O>=c&&O<=l}),f=[],m=0,k=e.query?.toLowerCase(),y=e.participants?.length?new Set(e.participants):void 0;for(let D of p){let $;try{$=JSON.parse(Ie(Se(this.sessionsDir,D),"utf-8"))}catch{continue}if($.agentId===e.agentId&&!(e.channel&&$.channel!==e.channel)&&!(e.chatId&&$.chatId!==e.chatId))for(let O of $.messages)m++,!(!O.timestamp||O.timestamp<o||O.timestamp>=i)&&(y&&O.role==="user"&&!y.has(O.name??"")||k&&!O.content.toLowerCase().includes(k)||f.push({ts:O.timestamp,role:O.role,senderName:O.name??"",content:O.content,channel:$.channel,chatId:$.chatId,day:$.day,sessionFile:D}))}f.sort((D,$)=>$.ts.localeCompare(D.ts));let b=f.slice(0,t),I=b.length>0?b[b.length-1].ts:null,E=f.length>t;return{turns:b,oldestTs:I,hasMore:E,totalScanned:m}}recentByChatId(e){let t=Math.min(Math.max(e.limit??qe,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=en(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 p=u.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),d=[];for(let u of a){let p;try{p=JSON.parse(Ie(Se(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let f of p.messages)!f.timestamp||f.timestamp<n||d.push({ts:f.timestamp,role:f.role,senderName:f.name??"",content:f.content,agentId:p.agentId,sessionFile:u})}let c=new Set,l=[];for(let u of d){let p=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;c.has(p)||(c.add(p),l.push(u))}return l.sort((u,p)=>u.ts.localeCompare(p.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!==""&&!oa(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=en(this.sessionsDir).filter(c=>c.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&c.includes(o)&&c.endsWith(".json")),d=[];for(let c of a)try{let l=JSON.parse(Ie(Se(this.sessionsDir,c),"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,m=u.map(k=>` [${k.timestamp.slice(11,16)}] ${k.name||k.role}: ${k.content.slice(0,200)}`);d.push(`From ${f} (${l.channel}):
|
|
38
38
|
${m.join(`
|
|
39
39
|
`)}`)}catch{}return d.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...d,"[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:d}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:n});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(na)}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()},wr(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>sa?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>qe&&(e.messages=e.messages.slice(-qe));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>tn&&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);wr(t,JSON.stringify(e,null,2))}catch{}}};var wt=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(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}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(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}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 Ke,writeFileSync as Sr,appendFileSync as ca,existsSync as ve,mkdirSync as da}from"fs";import{resolve as Ce}from"path";var Cr={"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}},Ar=2e5,ua=1.5;function la(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 $r(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Ar?{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 vr=500,ga=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,da(this.dir,{recursive:!0}),this.pricing=pa()}getPricing(){return this.pricing}static calculateCost(e,t,n=Cr){let r=la(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,d=e.tier2CacheReadTokens||0,c=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+d/1e6*o.cacheRead+c/1e6*o.cacheCreate;return l+u*ua}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,d,c){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 p=0,f=0,m=0,T=0,y=0,b=0,I=0,E=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Ar?(y=n.inputTokens,b=n.outputTokens,I=n.cacheReadTokens,E=n.cacheCreateTokens):(p=n.inputTokens,f=n.outputTokens,m=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),f=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=f,u.cacheReadTokens+=m,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+y,u.tier2OutputTokens=(u.tier2OutputTokens||0)+b,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+E,i&&u.errors++,u.byChannel||(u.byChannel={});let _=(d||"other").toLowerCase(),C=u.byChannel[_]||{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+=p,C.outputTokens+=f,C.cacheReadTokens+=m,C.cacheCreateTokens+=T,C.tier2InputTokens+=y,C.tier2OutputTokens+=b,C.tier2CacheReadTokens+=I,C.tier2CacheCreateTokens+=E,i&&C.errors++,u.byChannel[_]=C,c&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(c)||(u.sessionKeys.push(c),u.sessionKeys.length>vr&&u.sessionKeys.splice(0,u.sessionKeys.length-vr))),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(Ke(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(Ke(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,d=0,c=0,l="",u=0,p={},f={},m={};for(let[T,y]of Object.entries(n.agents)){let b=this.cost(y);p[T]=b,r+=y.tasks,o+=(y.inputTokens||0)+(y.tier2InputTokens||0),i+=(y.outputTokens||0)+(y.tier2OutputTokens||0),a+=(y.cacheReadTokens||0)+(y.tier2CacheReadTokens||0),d+=(y.cacheCreateTokens||0)+(y.tier2CacheCreateTokens||0),c+=b,b>u&&(u=b,l=T);let I=y.sessionKeys?.length||0;f[T]={sessions:I,avgTasksPerSession:I>0?y.tasks/I:y.tasks};for(let[E,_]of Object.entries(y.byChannel||{})){let C=this.cost(_,y.model);m[E]=(m[E]||0)+C}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:d,totalCost:c,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:f,byChannel:m}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=c=>c<.01?c.toFixed(4):c.toFixed(2),o=c=>c>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}K`:String(c),i=Object.entries(e.agentCosts).sort(([,c],[,l])=>l-c).map(([c,l])=>{let u=e.agentSessionStats[c],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${c}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,c],[,l])=>l-c).map(([c,l])=>`${c}: $${r(l)}`).join(", "),d=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;ve(n)?ca(n,d+`
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:d}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:n});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(na)}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.getTierTwoThresholdTokens(t)}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()},wr(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>sa?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(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>qe&&(e.messages=e.messages.slice(-qe));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>tn&&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);wr(t,JSON.stringify(e,null,2))}catch{}}};var wt=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(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}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(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}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 Ke,writeFileSync as Sr,appendFileSync as ca,existsSync as ve,mkdirSync as da}from"fs";import{resolve as Ce}from"path";var Cr={"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}},Ar=2e5,ua=1.5;function la(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 $r(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Ar?{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 vr=500,ga=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,da(this.dir,{recursive:!0}),this.pricing=pa()}getPricing(){return this.pricing}static calculateCost(e,t,n=Cr){let r=la(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,d=e.tier2CacheReadTokens||0,c=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+d/1e6*o.cacheRead+c/1e6*o.cacheCreate;return l+u*ua}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,d,c){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 p=0,f=0,m=0,k=0,y=0,b=0,I=0,E=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Ar?(y=n.inputTokens,b=n.outputTokens,I=n.cacheReadTokens,E=n.cacheCreateTokens):(p=n.inputTokens,f=n.outputTokens,m=n.cacheReadTokens,k=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),f=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=f,u.cacheReadTokens+=m,u.cacheCreateTokens+=k,u.tier2InputTokens=(u.tier2InputTokens||0)+y,u.tier2OutputTokens=(u.tier2OutputTokens||0)+b,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+E,i&&u.errors++,u.byChannel||(u.byChannel={});let D=(d||"other").toLowerCase(),$=u.byChannel[D]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};$.tasks++,$.totalDuration+=t,$.inputTokens+=p,$.outputTokens+=f,$.cacheReadTokens+=m,$.cacheCreateTokens+=k,$.tier2InputTokens+=y,$.tier2OutputTokens+=b,$.tier2CacheReadTokens+=I,$.tier2CacheCreateTokens+=E,i&&$.errors++,u.byChannel[D]=$,c&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(c)||(u.sessionKeys.push(c),u.sessionKeys.length>vr&&u.sessionKeys.splice(0,u.sessionKeys.length-vr))),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(Ke(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(Ke(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,d=0,c=0,l="",u=0,p={},f={},m={};for(let[k,y]of Object.entries(n.agents)){let b=this.cost(y);p[k]=b,r+=y.tasks,o+=(y.inputTokens||0)+(y.tier2InputTokens||0),i+=(y.outputTokens||0)+(y.tier2OutputTokens||0),a+=(y.cacheReadTokens||0)+(y.tier2CacheReadTokens||0),d+=(y.cacheCreateTokens||0)+(y.tier2CacheCreateTokens||0),c+=b,b>u&&(u=b,l=k);let I=y.sessionKeys?.length||0;f[k]={sessions:I,avgTasksPerSession:I>0?y.tasks/I:y.tasks};for(let[E,D]of Object.entries(y.byChannel||{})){let $=this.cost(D,y.model);m[E]=(m[E]||0)+$}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:d,totalCost:c,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:f,byChannel:m}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=c=>c<.01?c.toFixed(4):c.toFixed(2),o=c=>c>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}K`:String(c),i=Object.entries(e.agentCosts).sort(([,c],[,l])=>l-c).map(([c,l])=>{let u=e.agentSessionStats[c],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${c}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,c],[,l])=>l-c).map(([c,l])=>`${c}: $${r(l)}`).join(", "),d=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;ve(n)?ca(n,d+`
|
|
41
41
|
`):Sr(n,`# Token Costs
|
|
42
42
|
|
|
43
43
|
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
@@ -46,7 +46,7 @@ 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
|
`+d+`
|
|
49
|
-
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=Ke(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=Ke(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 d=0;d<n;d++){let c=a.toISOString().slice(0,10);if(o&&c<=o)break;i.push(c),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let d of i){if(this.hasTokenCostsEntry(d,t.filePath))continue;let c=this.generateDailyReport(d);!c||c.totalTasks===0||(this.appendToTokenCosts(c,t.filePath),r.push(d))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,d=0,c={},l={};for(let m=0;m<e;m++){let
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=Ke(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=Ke(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 d=0;d<n;d++){let c=a.toISOString().slice(0,10);if(o&&c<=o)break;i.push(c),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let d of i){if(this.hasTokenCostsEntry(d,t.filePath))continue;let c=this.generateDailyReport(d);!c||c.totalTasks===0||(this.appendToTokenCosts(c,t.filePath),r.push(d))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,d=0,c={},l={};for(let m=0;m<e;m++){let k=new Date(Date.now()-m*864e5).toISOString().slice(0,10),y=this.getDate(k);if(y)for(let[b,I]of Object.entries(y.agents)){let E=this.cost(I);t+=I.tasks;let D=(I.inputTokens||0)+(I.tier2InputTokens||0),$=(I.outputTokens||0)+(I.tier2OutputTokens||0),O=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),L=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=D,r+=$,o+=O,i+=L,a+=I.errors,d+=E;let P=c[b]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};P.tasks+=I.tasks,P.input+=D,P.output+=$,P.cacheRead+=O,P.cacheCreate+=L,P.total=P.input+P.output+P.cacheRead+P.cacheCreate,P.totalDuration+=I.totalDuration,P.avgDuration=P.totalDuration/P.tasks,P.cost+=E,P.sessions+=I.sessionKeys?.length||0,I.model&&(P.model=I.model),c[b]=P;for(let[F,H]of Object.entries(I.byChannel||{})){let j=this.cost(H,I.model),K=l[F]||{tasks:0,cost:0};K.tasks+=H.tasks,K.cost+=j,l[F]=K}}}let u=n+r+o+i,p=o+i>0?o/(o+i):0,f={};for(let[m,k]of Object.entries(c))f[m]={sessions:k.sessions,avgTasksPerSession:k.sessions>0?k.tasks/k.sessions:k.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:d,byAgent:c,byChannel:l,sessionStats:f}}filePath(e){return Ce(this.dir,`${e}.json`)}save(e){try{Sr(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function pa(){let s=JSON.parse(JSON.stringify(Cr));try{let e=Ce(process.cwd(),ga);if(!ve(e))return s;let t=JSON.parse(Ke(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 ma={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}},Mr=4;function Rr(s,e=ma){let t=ha(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Mr;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Mr,d=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+d.length>o){let c=o-r;c>100&&n.push(d.slice(0,c)+"...");break}n.push(d),r+=d.length}return n.join(`
|
|
50
50
|
|
|
51
51
|
`)}function ha(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(fa(s,t("channel",200))),n.push(ya(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],d=s.intent.axes?.[a];if(d&&Object.keys(d).length){let c=Object.entries(d).map(([l,u])=>` ${l}: ${u}`).join(`
|
|
@@ -103,7 +103,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:Sa,maxTokens:512})).content.trim().match(/\[[
|
|
|
103
103
|
`)})].join(`
|
|
104
104
|
|
|
105
105
|
`)}ns();Ht();var hn="turn-progress",uo={progress:it({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.")},mn=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function lo(s){return{agent:s.agent,request:mn(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:mn(e.input,300),...e.result!==void 0?{result:mn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Ht();var go="turn-handoff",po="approval-binding",mo={nextStep:it({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.")},ho={approves:Ne("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."})},Ac=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,fo=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,$c=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function fn(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:$c.test(e.split(`
|
|
106
|
-
`).slice(-3).join(" ")):!1}var Mc=/^\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 yo(s){return s.trim().length<=160&&Mc.test(s)}function bo(s){return s.trim().length<=160}function wo(s){return{agent:s.agent,channel:s.channel,request:Ac(s.request,1500),agentReplyEnding:fo(s.reply,1200)}}function xo(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:fo(s.previousReply,1200)}}var Rc=5*6e4,Pc=3,_c=12,Ec=24*60*6e4,To=new Set(["cron","heartbeat","bench","a2a","business"]),Dc={observe(){},stop(){}};function ko(s){if(ts(hn)==="off")return Dc;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let p;for(let[f,m]of o)m>1&&(!p||m>p.times)&&(p={call:f,times:m});return p},l=p=>{if(d)return;d=!0,a=n.length;let f=lo({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-_c),repeated:c(),trigger:p});xe(hn,f,uo,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{d=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Rc);return u.unref?.(),{observe(p){let f=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let m of f){if(m?.type!=="tool_use")continue;let
|
|
106
|
+
`).slice(-3).join(" ")):!1}var Mc=/^\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 yo(s){return s.trim().length<=160&&Mc.test(s)}function bo(s){return s.trim().length<=160}function wo(s){return{agent:s.agent,channel:s.channel,request:Ac(s.request,1500),agentReplyEnding:fo(s.reply,1200)}}function xo(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:fo(s.previousReply,1200)}}var Rc=5*6e4,Pc=3,_c=12,Ec=24*60*6e4,To=new Set(["cron","heartbeat","bench","a2a","business"]),Dc={observe(){},stop(){}};function ko(s){if(ts(hn)==="off")return Dc;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let p;for(let[f,m]of o)m>1&&(!p||m>p.times)&&(p={call:f,times:m});return p},l=p=>{if(d)return;d=!0,a=n.length;let f=lo({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-_c),repeated:c(),trigger:p});xe(hn,f,uo,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{d=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Rc);return u.unref?.(),{observe(p){let f=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let m of f){if(m?.type!=="tool_use")continue;let k=m.input?JSON.stringify(m.input):"",y={tool:m.name||"tool",input:k};n.push(y),typeof m.id=="string"&&r.set(m.id,y);let b=`${y.tool}(${k})`,I=(o.get(b)??0)+1;o.set(b,I),I>=Pc&&!i.has(b)&&(i.add(b),l("repetition"))}else if(p?.type==="user")for(let m of f){if(m?.type!=="tool_result")continue;let k=r.get(m.tool_use_id);k&&(k.result=Array.isArray(m.content)?m.content.map(y=>typeof y?.text=="string"?y.text:"").join(""):typeof m.content=="string"?m.content:"",m.is_error&&(k.error=!0))}},stop(){clearInterval(u)}}}var yn=new Map,Io=(s,e,t)=>`${s}\0${e}\0${t}`;function So(s){if(To.has(s.channel)||!fn(s.reply))return;let e=Io(s.agent,s.channel,s.chatId);xe(go,wo(s),mo,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&yn.set(e,{callId:t.callId,at:Date.now()})})}function vo(s){if(To.has(s.channel))return;let e=Io(s.agent,s.channel,s.chatId),t=yn.get(e);if(t){yn.delete(e);let n=es().store;if(n&&Date.now()-t.at<Ec)try{n.label(t.callId,"userReply",yo(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!bo(s.message)||!fn(s.previousReply)||xe(po,xo({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),ho,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}si();oi();ii();Vn();function Co(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(ze(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(d=>{a(),n(d)},d=>{a(),r(d)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function ze(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Re=class extends Error{constructor(t,n){super(`step "${t}" exceeded its ${Math.round(n/1e3)}s budget`);this.step=t;this.budgetMs=n;this.name="StepBudgetExceeded"}};function Ao(s,e,t){return e>0?new Promise((n,r)=>{let o=setTimeout(()=>r(new Re(t,e)),e);o.unref?.(),s.then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),r(i)})}):s}var Nc=250,Lc=5e3,Uc={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3};function $o(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Do;function dg(s){Do=s}function ug(){return Do}var Mo=64*1024,Bc=5*60*1e3,Wc=3e4,qc=300,Pe=".agentx/task-history",Kc=30;function Ye(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Gc(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 Jc(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=$s(s,e,X().recent());return Rs(t,n)}function Qc(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",p=r.get(u)||[];p.push(l.meta.title),r.set(u,p)}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
|
`),d=process.argv[1]||"dist/cli.js",c=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 ${d} wiki query "the question" --dir ${c} --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 ${d} wiki facts list --dir ${c}\`. 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
109
|
`)}var bn=8*1024;function zc(s,e){if(s)try{Ns(s)}catch{}return e}function Ro(s){if(s.length<=bn)return s;let e=s.length-bn;return s.slice(0,bn)+`\u2026[+${e}]`}function Po(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 Xc(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 _o(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=X();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?Ro(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(d=>typeof d?.text=="string"?d.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?Ro(a):null,at:r})}return}}function Yc(){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
|
|
@@ -127,26 +127,26 @@ Agent: ${t.slice(0,1e3)}`}],{model:Sa,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(d=>typeof d?.text=="string"?d.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Ye(i,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
|
-
`:""}}var Eo=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new ws;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new ys;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 bt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new hs(void 0,void 0,"unified"),this.memoryStore=new bs,this.patternStore=new Tt,this.rateLimiter=new wt,this.tokenTracker=new Ae,this.messageQueue=new xt,Gr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ps({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new ms({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}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let n=Xn(this.config.people,e,t);return n?(this.log(`[${e}] refused: ${n.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:n.person.id,event:"agent-refused",detail:e}),n.note):null}logToolRefusal(e,t,n){this.log(`[${t??"?"}] blocked for ${e}: ${n} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:n})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Ds(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;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 d of a.def.mentions){if(t.atMentionsOnly&&!d.startsWith("@"))continue;let c=d.toLowerCase();n.includes(c)&&c.length>o&&(r=i,o=c.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,d=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=kr(p.messages,e.message??""),d=Ir(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let c={message:e.message??"",previousMessage:i,recentRequests:d,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(Ls,Hs(c),Fs,{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"||!js(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),X().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"),d=await a(t,n);if(!d.memo){this.log(`[${e}] rotation memo skipped (${i}, ${d.reason}, ${d.durationMs}ms)`);return}let{storeRotationMemo:c}=await import("./rotation-memo-store-A4YW6FSK.js"),l=c(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:d.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${d.durationMs}ms, ${d.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;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().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=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().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(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:g.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=yt(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),h=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(
|
|
132
|
-
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let m={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};c.runningTasks.push(m),e.runningTaskId=m.id;let
|
|
130
|
+
`:""}}var Eo=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new ws;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new ys;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 bt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new hs(void 0,void 0,"unified"),this.memoryStore=new bs,this.patternStore=new Tt,this.rateLimiter=new wt,this.tokenTracker=new Ae,this.messageQueue=new xt,Gr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ps({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new ms({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}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let n=Xn(this.config.people,e,t);return n?(this.log(`[${e}] refused: ${n.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:n.person.id,event:"agent-refused",detail:e}),n.note):null}logToolRefusal(e,t,n){this.log(`[${t??"?"}] blocked for ${e}: ${n} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:n})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Ds(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;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 d of a.def.mentions){if(t.atMentionsOnly&&!d.startsWith("@"))continue;let c=d.toLowerCase();n.includes(c)&&c.length>o&&(r=i,o=c.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,d=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=kr(p.messages,e.message??""),d=Ir(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let c={message:e.message??"",previousMessage:i,recentRequests:d,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(Ls,Hs(c),Fs,{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"||!js(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),X().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"),d=await a(t,n);if(!d.memo){this.log(`[${e}] rotation memo skipped (${i}, ${d.reason}, ${d.durationMs}ms)`);return}let{storeRotationMemo:c}=await import("./rotation-memo-store-A4YW6FSK.js"),l=c(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:d.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${d.durationMs}ms, ${d.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;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().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=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().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(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:g.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=yt(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),h=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(_=>setTimeout(_,S))}}else if(l==="voice"){let g=Date.now(),h=25*6e4,S=`${e.agentId}\0${u}`;for(;this.messageQueue.isBusy(e.agentId,l,u)||this.voiceClaims.has(S);){if(Date.now()-g>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(h/6e4)}m`};await new Promise(_=>setTimeout(_,500))}p=S,this.voiceClaims.add(S)}else{let g=c.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,l,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:l,chatId:u,originalContext:e.context,queuedAt:e.queuedAt});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let S=this.messageQueue.pendingCount(e.agentId,l,u);return X().emit("task:queued",{agentId:e.agentId,channel:l,chatId:u,at:new Date().toISOString(),sender:Ft(e.context),humanRoot:Nt(e.context)}),this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${S}) behind=${c.runningTasks.map(_=>_.id).join(",")||"-"} chat=${l}:${u} at=${new Date().toISOString()}`),{content:"",error:xs(h,S)}}}let f=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,h)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!f.ok)return this.log(`[${e.agentId}] ${f.reason}`),{content:"",error:f.reason};if(e.queuedAt!==void 0){let g=Er(e.queuedAt);g&&(e.message=`${g}
|
|
132
|
+
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let m={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};c.runningTasks.push(m),e.runningTaskId=m.id;let k=zn(this.config.people,e.context);if(e.context&&(k?e.context.person=k.id:delete e.context.person),this.runningContexts.set(m.id,e.context??{}),e.onStart)try{e.onStart(m.id)}catch{}let y=new AbortController;this.taskAborts.set(m.id,{agentId:e.agentId,channel:m.channel,chatId:typeof m.chatId=="string"?m.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(m.id,b);let I=g=>{if(g){b.buffer+=g,b.buffer.length>Mo&&(b.buffer=b.buffer.slice(b.buffer.length-Mo));for(let h of b.subscribers)try{h(g)}catch{}}},E=we();e.taskId=E;let D=new Map,$=(g,h,S)=>{try{X().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-h,at:new Date().toISOString()})}catch{}},O=0,L=!1,P=()=>{L||(L=!0,O&&$("first-event",O,"ok"))},F;if(t){let g=Yc();F=h=>{P();let S=g(h);if(S&&I(S),_o(E,e.agentId,h),Po(D,h),cn(h,void 0,e.model||c.def.model),r)try{r(h)}catch{}}}else F=g=>{if(P(),_o(E,e.agentId,g),Po(D,g),cn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,j=H?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;j?.unref?.();let K=(c.def.preSpawnTimeoutSec??qc)*1e3,C=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(K/1e3)}s in step "${m.step??"start"}"`))},K);C.unref?.();let v=()=>{C&&clearTimeout(C),C=void 0},w=()=>`task=${m.id} chat=${l}:${u} at=${new Date().toISOString()}`,x;y.signal.addEventListener("abort",()=>{let g=ze(y.signal).message;/^timed out/.test(g)&&(x=m.step??"start"),this.log(`[${e.agentId}] task ${m.id} aborted in step "${m.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let N=g=>{m.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},M=(g,h,S=0)=>{if(y.signal.aborted)return Promise.reject(ze(y.signal));N(g),(g==="agent"||g==="workflow-auto-run")&&(v(),O=Date.now());let _=Date.now(),W=Ao(h(),Uc[g]??0,g);return Co(W,y.signal,S).then(B=>($(g,_,"ok"),B),B=>{throw $(g,_,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},V=async(g,h,S,_=0)=>{try{return await M(g,h,_)}catch(W){if(W instanceof Re)return S();throw W}},wn=!1,xn=g=>{if(wn)return;wn=!0,this.runReleases.delete(m.id),j&&clearTimeout(j),v(),c.activeTasks--;let h=c.runningTasks.findIndex(S=>S.id===m.id);h!==-1&&c.runningTasks.splice(h,1),this.runningContexts.delete(m.id),this.taskAborts.delete(m.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(m.id),Bc).unref?.();try{let S=b.endedAt,
|
|
135
|
-
`).length}L`,B=`[${e.agentId}] ${
|
|
136
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&
|
|
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=Vc(c.def.richMessages,
|
|
134
|
+
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(m.id),Bc).unref?.();try{let S=b.endedAt,_={id:m.id,agentId:e.agentId,channel:m.channel,chatId:m.chatId,sender:m.sender,message:e.message||"",startedAt:m.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-m.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(_);let W=(_.responseText||_.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:_.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${m.id} chat=${l}:${u} at=${new Date().toISOString()}`);let _=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:_,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then(A=>(Fe(A.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,A)),A=>{throw W(),A}).catch(A=>{this.log(`[${e.agentId}] queued message failed: ${A.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(m.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-SXR7HCE7.js"),pe=await V("request-gate",()=>Oo(e.message,e.agentId,T),()=>({active:!1,preprocess:!1}));pe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let R=u,vt=e.context?.sender||"User",ne=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,T,R),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${T}:${R}`),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()})),e.freshSession||await V("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,T,R,e.seedHistory),()=>{});let Lo=[...this.sessions.getSession(e.agentId,T,R).messages].reverse().find(g=>g.role==="agent")?.content;vo({agent:e.agentId,channel:T,chatId:R,message:e.message,previousReply:Lo,taskId:E}),this.sessions.addUserMessage(e.agentId,T,R,vt,e.message);let Tn=Date.now();X().emit("task:started",{agentId:e.agentId,channel:T,chatId:R,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Tn).toISOString(),taskId:E,resumeOrigin:Pr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Ft(e.context),...k?{person:k}:{},humanRoot:Nt(e.context),pickup:Jn(e.context),operator:Qn(e.context)});let Y,Ct,kn=this.classifier;if(kn&&T!=="a2a"&&!ne){N("classify");let g=Date.now();Ct=kn.classify({text:e.message,channel:T,sender:e.context?.sender,chatId:R,agentId:e.agentId}).then(h=>{Y=h||void 0,Y?.path?.length&&(m.intentPath=Y.path.slice()),$("classify",g,"ok")},h=>{this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`),$("classify",g,"error")})}let In=async g=>{if(!Ct)return;let h;await Promise.race([Ct,new Promise(S=>{h=setTimeout(S,g),h.unref?.()})]),h&&clearTimeout(h)};await In(Nc);let _e=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let g=new _s({baseDir:G(process.cwd(),this.config.workflows.dir)}),h=Es({agentId:e.agentId,channel:T,message:e.message,intentPath:Y?.path},g.list());h&&h.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${_e.mode} reasons=${h.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&h.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Fo=this.wikiHub.getAgentWiki(e.agentId),Sn=this.memoryStore.findRelevant(e.message,e.agentId,ne?3:8),vn=this.memoryStore.buildContext(Sn),Cn=this.memoryStore.contextFacts(Sn),Ho=this.patternStore.findRelevant(e.message,e.agentId,5),jo=this.patternStore.buildContext(Ho),An="";if(!ne)try{let{loadLocalSkills:g,getAutoInjectSkills:h}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),_=e.personLimits?.skills??[],W=_.length?S.filter(B=>!_.some(ee=>Oe(ee,B.frontmatter.name))):S;An=h(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,T,R):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,T,R):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,T,R):void 0;if(U&&this.sessions.isSessionStale(e.agentId,T,R)&&(this.log(`[${e.agentId}] session stale for ${T}:${R}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"stale"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,T,R)){let g=this.sessions.getLastTurnContextTokens(e.agentId,T,R);this.log(`[${e.agentId}] tier-2 rotation for ${T}:${R} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(T)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,T,R)){let g=this.sessions.getTurnCount(e.agentId,T,R);this.log(`[${e.agentId}] max-turns rotation for ${T}:${R} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await V("rotate",()=>this.maybeRotateForContinuity(e,c,T,R,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,T,R,this.memoryStore));if(g.compacted){let h=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${T}:${R} (quality: ${h}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let _=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${_.overallScore} (lexicon=${_.lexiconDecay}, tools=${_.toolShift}, semantic=${_.semanticDrift})`),_.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${_.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Uo=process.env.AGENTX_CONTEXT_SURGERY==="1",Bo=ne?{maxMessages:8,maxChars:2400}:Uo&&$o(T,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Wo=!U&&!ne?Qc(Fo,e.agentId):void 0,Ve=U?void 0:this.sessions.buildHistoryContext(e.agentId,T,R,Bo),qo=U?void 0:this.sessions.getRotationMemo(e.agentId,T,R)??void 0,$n,Mn=[];if(this.config.procedures?.injection?.enabled&&!U&&!ne)try{let g=new Qe({baseDir:G(process.cwd(),this.config.procedures.dir)}),h=gn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){$n=pn(h),Mn=h.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of h)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(me&&me.cat)try{let h=this.sessions.getSession(e.agentId,T,R).messages,S=h[0],_=h[h.length-1],W=Ve===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ve.length}c/${Ve.split(`
|
|
135
|
+
`).length}L`,B=`[${e.agentId}] ${T}:${R} ${W} | session.messages=${h.length}`+(h.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${_.timestamp.slice(11,19)}(${_.role}:${(_.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",B)}catch(g){me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Rn;if(c.def.contextReferences&&!U)try{let g=c.def.workspace,h=this.referencesCache.get(g);if(!h){let[_,W]=await M("references",()=>Promise.all([jt(c.def.workspace),Ut(c.def.workspace)]));if(_.byId.size===0&&W.recipes.length===0){let[B,ee]=await M("references",()=>Promise.all([jt(process.cwd()),Ut(process.cwd())]));h={refs:B,recipes:ee}}else h={refs:_,recipes:W};this.referencesCache.set(g,h)}let S=Is({agentId:e.agentId,intentTags:Y?.path,message:e.message},h.recipes,h.refs);S.cards.length>0&&(Rn=Ts(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Pn=this.sessions.getCrossSessionSummary(e.agentId,T,R,e.message),_n,Ze=Tr(e.message);if(Ze)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:T,chatId:R,lookbackDays:Ze.lookbackDays,limit:12});if(g.turns.length>0){let h=[`[Long-memory recall \u2014 last ${Ze.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((_,W)=>_.ts.localeCompare(W.ts));for(let _ of S){let W=_.ts.slice(11,16)+" "+_.day,B=_.role==="user"?_.senderName||"User":_.senderName||"Agent";h.push(`${W} ${B}: ${_.content}`)}g.hasMore&&h.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),_n=h.join(`
|
|
136
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&T!=="voice"&&T!=="desktop"){try{let{planContext:g}=await import("./context-planner-JU7CNXCB.js"),h=await M("plan-context",()=>g({agentId:e.agentId,channel:T,chatId:R,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));h?(On=!0,En=h.sessionHistory,vn=h.memoryContext,Cn=h.memoryFacts,Pn=h.crossChatContext,Dn=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}On&&U&&(this.sessions.clearClaudeSessionId(e.agentId,T,R),U=void 0)}let At=`${e.agentId}:${T}:${R}`,et=cs(e.message);et&&(et==="default"?(this.activeSouls.delete(At),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(At,et),this.log(`[${e.agentId}] Soul switched to: ${et}`)));let Go=this.activeSouls.get(At),Jo=is(c.def.workspace,Go),Qo=as(Jo),zo=this.agentMemory.indexMarkdown(e.agentId),Xo=c.def.tier==="claude-code"||c.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=Vc(c.def.richMessages,T),Nn="";if(c.def.workspace){let g=G(c.def.workspace,"CLAUDE.md");if(te(g))try{let h=Xe(g,"utf-8");Nn=`[Project CLAUDE.md]
|
|
138
138
|
${h.length>4e3?h.slice(0,4e3)+`
|
|
139
139
|
|
|
140
|
-
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let tt=e.context?.runbookPath,$t=[];if(tt&&te(tt)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,S=4e3,
|
|
140
|
+
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let tt=e.context?.runbookPath,$t=[];if(tt&&te(tt)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,S=4e3,_=16e3;for(let W of g){if(h>=_)break;let B=G(tt,W);if(te(B))try{let ee=Xe(B,"utf-8"),A=ee.length>S?ee.slice(0,S)+`
|
|
141
141
|
|
|
142
142
|
[${W} truncated to ${S} bytes]`:ee;$t.push(`[Project Runbook \u2014 ${W} from ${tt}]
|
|
143
|
-
${
|
|
143
|
+
${A}`),h+=A.length}catch{}}}let Vo=$t.length>0?$t.join(`
|
|
144
144
|
|
|
145
145
|
`):"",Mt=[c.def.systemPrompt||"",Xo,Yo,Nn,Vo,Qo||"",zo||""].filter(g=>g.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,Rt={channel:
|
|
148
|
-
`),
|
|
147
|
+
`)||void 0,Rt={channel:T,chatId:R,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(T,c.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:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,T,R),rotationMemo:qo,eventDigest:U?void 0:Jc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(T,!U,c.def.richMessages);return g?zc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{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),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,T,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-GW7LSHRJ.js"),h=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:T,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,T,R),cheapModel:Hn}));h.downgraded&&(_t=h.model,this.log(`[${e.agentId}] ${h.reason}`))}catch{}let ei={...e,systemPromptAppend:Mt,..._t?{model:_t}:{}},se,jn=!1,Un=ko({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),ti=F;F=g=>{Un.observe(g),ti?.(g)};try{let g=this.workflowAutoRunner;if(be&&g){let q=be;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:T,chatId:R,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:T,chatId:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?ut():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:T,chatId:R}),ce=!!U||z,re=[Wr(ce),no(ce,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(re){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${re.reason}`);let De={content:"",error:re.message,duration:0};if(!t){b.buffer=`[error] ${re.message}`;for(let ni of b.subscribers)try{ni(b.buffer)}catch{}}return se=De,De}Qr();let Ee=so();Ee&&this.log(`[${e.agentId}] ${Ee}`)}let h=c.def.tier==="claude-code",S=h?t:(q,z)=>{q&&I(q),t&&t(q,z)},_=!1,W=h?n:q=>{q&&(_?I(q):(I(`\u{1F4AD} ${q}`),_=!0)),n&&n(q)},B=()=>{_&&(I(`
|
|
148
|
+
`),_=!1)},ee=h?S:S?(q,z)=>{B(),S(q,z)}:void 0,A=await M("agent",()=>br(c.def,ei,this.providers,ee,st,U,F,y.signal,W),Wc);if(!A.error){let q=Xc(c.def.toolUseRequired,D);if(q){let z=Array.from(D.entries()).map(([ce,ot])=>`${ce}=${ot}`).join(", ")||"none";A.error=`tool_required_not_called: ${q} (invoked: ${z})`,A.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let Et=this.interruptedRuns.get(m.id);Et&&(A.content="",A.error=Et,A.errorKind="interrupted"),se=A;let ae=A.usage?$r(A.usage):void 0;if(jn=!0,X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:T,chatId:R,durationMs:Date.now()-Tn,error:A.error||void 0,errorKind:A.error?A.errorKind:void 0,interrupted:Et?!0:void 0,inputTokens:ae?.inputTokens,outputTokens:ae?.outputTokens,cacheReadTokens:ae?.cacheReadTokens,cacheCreateTokens:ae?.cacheCreateTokens,tier2InputTokens:ae?.tier2InputTokens,tier2OutputTokens:ae?.tier2OutputTokens,tier2CacheReadTokens:ae?.tier2CacheReadTokens,tier2CacheCreateTokens:ae?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:pe.arm,numTurns:A.numTurns,injectedContext:Zo,finalResponse:A.content||void 0,billedModel:A.billedModel||c.def.model||void 0,at:new Date().toISOString()}),!t&&(A.content||A.error)){let q=A.error?`[error] ${A.error}`:A.content;b.buffer=q;for(let z of b.subscribers)try{z(q)}catch{}}if(A.error)c.errors++,this.log(`[${e.agentId}] error: ${A.error}`);else{if(this.sessions.addAgentMessage(e.agentId,T,R,A.content),So({agent:e.agentId,channel:T,chatId:R,request:e.message,reply:A.content,taskId:E}),A.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,T,R,A.claudeSessionId),A.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,T,R,A.codexSessionId),A.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,T,R,A.opencodeSessionId),(A.claudeSessionId||A.codexSessionId||A.opencodeSessionId)&&A.usage&&this.sessions.recordTurnUsage(e.agentId,T,R,A.usage,A.contextTokens),A.usage){let re=A.contextTokens,Ee=(A.usage.inputTokens||0)+(A.usage.cacheReadTokens||0)+(A.usage.cacheCreateTokens||0);(re??Ee)>=this.sessions.getTierTwoThresholdTokens(T)&&this.log(`[${e.agentId}] TIER-2 HIT on ${T}:${R}: context=${re??"n/a"} tokens (cumulative turn total=${Ee}) \u2014 next turn will rotate`)}if(ls({channel:T,content:`User: ${e.message}`,responseLength:A.content.length}).capture){await In(Lc);try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:T,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
|
-
Agent: ${
|
|
150
|
+
Agent: ${A.content}`,meta:Gc(Y,e.context)})}catch{}gs(e.agentId,e.message,A.content,{channel:T,chatId:R,sender:vt},this.memoryStore).catch(()=>{}),Lr(e.agentId,e.message,A.content,{channel:T,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=A.billedModel||e.model||c.def.model,ce=e.context?.channel,ot=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,A.duration||0,A.usage,e.message.length,A.content.length,!1,z,ce,ot),this.log(`[${e.agentId}] completed in ${A.duration}ms`+(A.tokensUsed?` (${A.tokensUsed} tokens)`:"")+` ${w()}`)}return A}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let h=ct(g.message);return se={content:"",error:dt(h),errorKind:h.kind},se}finally{if(Un.stop(),!jn)try{X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:l,chatId:u,durationMs:Date.now()-m.startedAt.getTime(),error:se?.error||(y.signal.aborted?ze(y.signal).message:"run ended before completion"),errorKind:se?.errorKind,interrupted:this.interruptedRuns.has(m.id)?!0:void 0,at:new Date().toISOString()})}catch{}xn(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=G(process.cwd(),Pe,this.safe(e.agentId),t);te(n)||Fc(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);jc(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=G(process.cwd(),Pe,this.safe(e));if(!te(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let d=new Date(n).toISOString().slice(0,10),c=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[c,d]){let p=G(a,u);if(te(p))try{for(let f of ie(p)){if(!f.endsWith(".json"))continue;let m=f.split("-")[0],k=parseInt(m,10);if(!Number.isFinite(k)||k<i||k>n)continue;let y=Math.floor((n-k)/36e5),b=t-1-y;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Pe);if(!te(e))return 0;let t=0;for(let n of ie(e)){let r=G(e,n),o;try{o=ie(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ie(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let l=JSON.parse(Xe(G(a,c),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Kc){let t=G(process.cwd(),Pe);if(!te(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ie(t)){let i=G(t,o),a;try{a=ie(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=n))try{Hc(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return[];let r=ie(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=G(n,i),d;try{d=ie(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let l=JSON.parse(Xe(G(a,c),"utf-8")),{transcript:u,responseText:p,...f}=l;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return null;let r=this.safe(t),o=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(te(a))try{return JSON.parse(Xe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Ps();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||Fe(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(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}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=>{let d=yt(a);return d.channel===t.channel&&d.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:d,originalMessage:c}=o,l=o.controller.signal.aborted,u=!1;l&&c&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,d,c)),this.messageQueue.enqueue(i,a,d,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:n}});let p=this.messageQueue.pendingCount(i,a,d),f=!1;if(r.replace){let m=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(m))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${m}`),f=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:f,edited:u,pending:p}}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,d=i.chatId;return new Promise(c=>{let l=!1,u=p=>{l||(l=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Fe(p.error)?u({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}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 Vc(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
151
|
`)}export{Us as a,id as b,Ws as c,bi as d,qs as e,lt as f,wd as g,Id as h,Sd as i,Md as j,yt as k,Hi as l,hr as m,qi as n,Ki as o,Gi as p,br as q,bt as r,wt as s,wa as t,ou as u,iu as v,rn as w,X as x,Fr as y,Ma as z,Ea as A,Ur as B,Iu as C,Br as D,Gr as E,Vr as F,Lu as G,Zr as H,Qe as I,kc as J,Ic as K,Sc as L,vc as M,Cc as N,gn as O,dg as P,ug as Q,Gc as R,Jc as S,Qc as T,bn as U,Ro as V,Po as W,Xc as X,_o as Y,Eo as Z,Vc as _};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-DXOTH6MF.js.map
|