agentix-cli 0.64.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/{agent-3M5EI4S6.js → agent-HUKCS3AK.js} +2 -2
  2. package/dist/{board-dashboard-JBRO26JC.js → board-dashboard-S4V4WR2N.js} +225 -170
  3. package/dist/{board-dashboard-JBRO26JC.js.map → board-dashboard-S4V4WR2N.js.map} +1 -1
  4. package/dist/{chunk-KZDG26LI.js → chunk-AVDWFQZ5.js} +2 -2
  5. package/dist/{chunk-NNXHRO7H.js → chunk-ECBKTFTL.js} +17 -17
  6. package/dist/chunk-ECBKTFTL.js.map +1 -0
  7. package/dist/{chunk-S2VETB7B.js → chunk-EOKOGQZG.js} +26 -26
  8. package/dist/chunk-EOKOGQZG.js.map +1 -0
  9. package/dist/{chunk-HYKILAEJ.js → chunk-HSJRI3NW.js} +183 -183
  10. package/dist/chunk-HSJRI3NW.js.map +1 -0
  11. package/dist/{chunk-VVQDKHF5.js → chunk-LEFRNHZF.js} +4 -4
  12. package/dist/{chunk-VUB6XYWD.js → chunk-OTTAKMGC.js} +54 -54
  13. package/dist/chunk-OTTAKMGC.js.map +1 -0
  14. package/dist/cli.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/{program-FSRL275V.js → program-DZCKFNHD.js} +2 -2
  17. package/dist/registry-P7IAAFCX.js +2 -0
  18. package/package.json +1 -1
  19. package/dist/chunk-HYKILAEJ.js.map +0 -1
  20. package/dist/chunk-NNXHRO7H.js.map +0 -1
  21. package/dist/chunk-S2VETB7B.js.map +0 -1
  22. package/dist/chunk-VUB6XYWD.js.map +0 -1
  23. package/dist/registry-T4R7LVFZ.js +0 -2
  24. /package/dist/{agent-3M5EI4S6.js.map → agent-HUKCS3AK.js.map} +0 -0
  25. /package/dist/{chunk-KZDG26LI.js.map → chunk-AVDWFQZ5.js.map} +0 -0
  26. /package/dist/{chunk-VVQDKHF5.js.map → chunk-LEFRNHZF.js.map} +0 -0
  27. /package/dist/{program-FSRL275V.js.map → program-DZCKFNHD.js.map} +0 -0
  28. /package/dist/{registry-T4R7LVFZ.js.map → registry-P7IAAFCX.js.map} +0 -0
@@ -1,44 +1,44 @@
1
- import{a as Wn,b as Kn,h as ss,n as rs,s as os}from"./chunk-NNXHRO7H.js";import{a as Bn}from"./chunk-WP6KLXTP.js";import{a as kt}from"./chunk-N6EWZGIX.js";import{b as qn}from"./chunk-DP7RTNDM.js";import{b as Jn,c as vt,d as Qn,e as Xn,h as Yn}from"./chunk-BHE5TJSN.js";import{a as It,b as Gn}from"./chunk-J3SOEFRE.js";import{a as St,b as zn}from"./chunk-SIU6STB2.js";import{e as Vn,i as Zn,j as es,k as ts}from"./chunk-X5C5W3E4.js";import{a as ns}from"./chunk-W4YR2RO2.js";import{a as Rn}from"./chunk-LQ5J6COO.js";import{a as _n,b as En,c as Dn,d as On,f as Nn}from"./chunk-DWADWDMU.js";import{a as Ln,b as Fn}from"./chunk-NO2HOK4B.js";import{a as Un}from"./chunk-AZBOYKQA.js";import{b as Hn,c as jn}from"./chunk-WGWNVLVW.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as $n,t as Mn,v as we,w as Pn}from"./chunk-PTB2TPOC.js";import{a as Re,b as Ye,f as Tt}from"./chunk-72SZI2UW.js";import{a as be,b as wt}from"./chunk-FCPTN6NF.js";import{c as kn,d as In}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as Sn,e as oe,f as vn,g as Cn,h as xt,s as An,z as lo}from"./chunk-OVF37EXJ.js";Pn();Tt();var is="session-continuity",as={continues:Re("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:Re("Does the new request refer to something stated earlier in the conversation?")};function cs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Ct(s.message,1200),previousRequest:s.previousMessage?Ct(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Ct(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ds(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 Ct(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as go,execFile as po}from"node:child_process";import{createHash as ho,randomBytes as mo}from"node:crypto";import{createInterface as fo}from"node:readline";import{promisify as yo}from"node:util";var bo=yo(po),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},At=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=bo("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=ho("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:mo(32).toString("hex")},l=go("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=fo({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(d=!1)=>{c||(c=!0,a.busy=!1,d||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},us=new At;import{execa as rt}from"execa";import{spawn as wo}from"node:child_process";import{createHash as xo}from"node:crypto";import{createInterface as To}from"node:readline";var ae=class extends Error{},ko=s=>wo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),$t=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(),To({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()}},Mt=class{constructor(e=ko,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=xo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new $t(e,this.launchProcess)}}catch{throw new ae("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={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",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,P)=>{if(P?.threadId!==l)return;let N=P.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...P,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=P.delta,e.onDelta?.(P.delta,c)),v==="thread/tokenUsage/updated"){let O=P.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(P.turn.status==="completed"?_():A(new Error(P.turn.error?.message||`Codex turn ${P.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),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())}}},ls=new Mt;import{execFile as No}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as vs,readFileSync as Cs,rmSync as As}from"fs";import{join as nt}from"path";import{tmpdir as $s}from"os";function Ze(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function et(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var gs=null;function tt(){return gs}function Va(s){gs=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},ps=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=Ee(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 xe(`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 xe(`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=Ee(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=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(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=Ee(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Io}from"child_process";import{existsSync as So,readFileSync as vo}from"fs";import{resolve as Co}from"path";function Ao(s){let e=Co(s,"CLAUDE.md");if(!So(e))return null;try{let t=vo(e,"utf8");return Nn(t)}catch{return null}}var $o=20*60*1e3,Mo=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},hs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Pt(e,t,this.opts)}},Pt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Io(r,o,{cwd:t.workspace,env:_e({...process.env},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:Ao(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
3
- `);let a=e.deadlineMs??$o,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Mo);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
- `))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};xt();import{resolve as ms,join as fs}from"path";wt();var Po=4e3;function ys(s){try{let e=fs(ms(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,Po):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
1
+ import{a as Wn,b as Kn,h as ss,n as rs,t as os,v as is}from"./chunk-ECBKTFTL.js";import{a as Bn}from"./chunk-WP6KLXTP.js";import{a as kt}from"./chunk-N6EWZGIX.js";import{b as qn}from"./chunk-DP7RTNDM.js";import{b as Jn,c as vt,d as Qn,e as Xn,h as Yn}from"./chunk-BHE5TJSN.js";import{a as It,b as Gn}from"./chunk-J3SOEFRE.js";import{a as St,b as zn}from"./chunk-SIU6STB2.js";import{e as Vn,i as Zn,j as es,k as ts}from"./chunk-X5C5W3E4.js";import{a as ns}from"./chunk-W4YR2RO2.js";import{a as Pn}from"./chunk-LQ5J6COO.js";import{a as _n,b as En,c as Dn,d as On,f as Nn}from"./chunk-DWADWDMU.js";import{a as Ln,b as Fn}from"./chunk-NO2HOK4B.js";import{a as Un}from"./chunk-AZBOYKQA.js";import{b as Hn,c as jn}from"./chunk-WGWNVLVW.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as $n,t as Mn,v as we,w as Rn}from"./chunk-PTB2TPOC.js";import{a as Pe,b as Ye,f as Tt}from"./chunk-72SZI2UW.js";import{a as be,b as wt}from"./chunk-FCPTN6NF.js";import{c as kn,d as In}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as Sn,e as oe,f as vn,g as Cn,h as xt,s as An,z as go}from"./chunk-OVF37EXJ.js";Rn();Tt();var as="session-continuity",cs={continues:Pe("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:Pe("Does the new request refer to something stated earlier in the conversation?")};function ds(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Ct(s.message,1200),previousRequest:s.previousMessage?Ct(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Ct(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function us(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 Ct(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as po,execFile as ho}from"node:child_process";import{createHash as mo,randomBytes as fo}from"node:crypto";import{createInterface as yo}from"node:readline";import{promisify as bo}from"node:util";var wo=bo(ho),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},At=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=wo("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=mo("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:fo(32).toString("hex")},l=po("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=yo({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(d=!1)=>{c||(c=!0,a.busy=!1,d||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},ls=new At;import{execa as rt}from"execa";import{spawn as xo}from"node:child_process";import{createHash as To}from"node:crypto";import{createInterface as ko}from"node:readline";var ae=class extends Error{},Io=s=>xo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),$t=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(),ko({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()}},Mt=class{constructor(e=Io,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=To("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new $t(e,this.launchProcess)}}catch{throw new ae("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={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",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,R)=>{if(R?.threadId!==l)return;let N=R.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),v==="thread/tokenUsage/updated"){let O=R.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(R.turn.status==="completed"?_():A(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),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())}}},gs=new Mt;import{execFile as Lo}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as Cs,readFileSync as As,rmSync as $s}from"fs";import{join as nt}from"path";import{tmpdir as Ms}from"os";function Ze(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function et(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ps=null;function tt(){return ps}function tc(s){ps=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},hs=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=Ee(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 xe(`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 xe(`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=Ee(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=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(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=Ee(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as So}from"child_process";import{existsSync as vo,readFileSync as Co}from"fs";import{resolve as Ao}from"path";function $o(s){let e=Ao(s,"CLAUDE.md");if(!vo(e))return null;try{let t=Co(e,"utf8");return Nn(t)}catch{return null}}var Mo=20*60*1e3,Ro=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},ms=class{constructor(e={}){this.opts=e}spawn(e,t){return new Rt(e,t,this.opts)}},Rt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=So(r,o,{cwd:t.workspace,env:_e({...process.env},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:$o(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
3
+ `);let a=e.deadlineMs??Mo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ro);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
+ `))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};xt();import{resolve as fs,join as ys}from"path";wt();var Po=4e3;function bs(s){try{let e=ys(fs(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,Po):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
5
5
  (id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
6
6
  verdict, effective_action, mode, severity, approver, ms)
7
7
  VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
8
8
  @verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:n,ts:Date.now(),agent_id:s.input.agentId??null,task_id:s.taskId??null,tool:s.input.tool,command:r,resolved_target:s.verdict.resolvedTarget,matched_rule:s.verdict.ruleId,verdict:s.verdict.action,effective_action:s.verdict.effectiveAction,mode:s.mode,severity:s.verdict.severity,approver:s.approver??null,ms:s.ms??null}),n}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
9
- `),null}}function uc(s){let e=fs(ms(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}xt();var Ro=50,_o=6*60*60*1e3,Rt=null,Te=new Map;function hc(s){Rt=s===null?null:String(s)}function Eo(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function ws(s,e,t){if(!oe(s))return{args:[]};if(!Rt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Eo(Rt,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function xs(s,e){return!oe(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Do(s){for(let[e,t]of Te)s-t.at>_o&&Te.delete(e)}function Oo(s,e){let t=Date.now();Do(t);let n=Te.get(s)??{at:t,blocks:[]};n.blocks.length<Ro&&n.blocks.push(e),n.at=t,Te.set(s,n)}function Ts(s){if(!s)return[];let e=Te.get(s);return Te.delete(s),e?.blocks??[]}function bs(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function mc(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let o=Sn.safeParse(e.level),i=o.success?vn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:c,reason:d},u={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return ys({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:u,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Oo(e.taskId,l),{stdout:bs(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(o){return{stdout:bs(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}function q(s){let e=Ze(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
- `)}return{error:et(e),errorKind:e.kind}}function Ms(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function st(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function ks(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function de(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",l=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
9
+ `),null}}function pc(s){let e=ys(fs(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}xt();var _o=50,Eo=6*60*60*1e3,Pt=null,Te=new Map;function yc(s){Pt=s===null?null:String(s)}function Do(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function xs(s,e,t){if(!oe(s))return{args:[]};if(!Pt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Do(Pt,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function Ts(s,e){return!oe(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Oo(s){for(let[e,t]of Te)s-t.at>Eo&&Te.delete(e)}function No(s,e){let t=Date.now();Oo(t);let n=Te.get(s)??{at:t,blocks:[]};n.blocks.length<_o&&n.blocks.push(e),n.at=t,Te.set(s,n)}function ks(s){if(!s)return[];let e=Te.get(s);return Te.delete(s),e?.blocks??[]}function ws(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function bc(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let o=Sn.safeParse(e.level),i=o.success?vn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:c,reason:d},u={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return bs({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:u,mode:"enforce",taskId:e.taskId??null}),e.taskId&&No(e.taskId,l),{stdout:ws(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(o){return{stdout:ws(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}function q(s){let e=Ze(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
+ `)}return{error:et(e),errorKind:e.kind}}function Rs(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function st(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function Is(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function de(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",l=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
11
11
  `))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
12
12
  `)}function Ps(s,e,t,n,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let c=r||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function _t(s,e){return!e||e.trim().length===0?s:`[System]
13
13
  ${e.trim()}
14
14
 
15
15
  [User]
16
- ${s}`}function Lo(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(_t(e,n)),o}function Fo(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 Is(s){return JSON.stringify(s)}function Rs(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Is(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(Is).join(",")}]`]}function _s(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Rs()),i||a.push("--color","never");let c=n||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(_t(e,r)),a}function ot(s,e){let t=Ve(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(":"),Et(t,e)}function Et(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 Ho(s,e){let t=ot(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 jo(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function ce(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Dt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ce(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ce(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ce(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ce(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Dt(n,e+1);if(r)return r}}function Es(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 Ot(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=Ot(t,e+1);if(n)return n}}}function Uo(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
17
- `))if(i.trim())try{let a=JSON.parse(i);t=Dt(a)||t,n=Es(a)||n,r=Ot(a)||r,o=Ds(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function Ds(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return Ss(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return Ss(e)}}}function Ss(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 Bo(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 Nt(s,e,t,n,r){let o=Bo(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 Wo(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 Ko(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 Os(s,e,t,n,r){let o=Date.now(),i=de(s,e,t),a=Ls(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=Ps(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Nt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:p,exitCode:y,killed:b}=await new Promise(I=>{let k=_e(Et(Ve(s.workspace),e),s.billing),_=!1,A=No("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...k,HOME:k.HOME||"/home/"+(k.USER||"user")}},(v,P,N)=>{I({stdout:P||"",stderr:N||"",exitCode:v?v.code??1:0,killed:_})});if(A.stdin?.end(),r){let v=()=>{_=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.killed||A.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?v():r.addEventListener("abort",v,{once:!0})}});if(b)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&y!==0){let I;return y===143?I=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:y==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?I=Ms():I=p?.trim()||`Claude Code exited with code ${y}`,{content:"",...q(I),duration:Date.now()-o}}let x=Wo(u);if(x)return{content:"",...q(x),duration:Date.now()-o};let w=Ko(u);return{content:w.text,duration:Date.now()-o,claudeSessionId:w.sessionId,usage:w.usage,numTurns:w.numTurns,billedModel:w.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function Ns(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=de(s,e,n),d=Ls(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let l=Ps(s,c,!0,r,e.model,e.systemPromptAppend,d.args);Nt(e.agentId,s,e.model,r,"stream");let u="",p,y,b,x,w,I;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=_e(Et(Ve(s.workspace),e),s.billing),A=rt("claude",l,{cwd:s.workspace,timeout:k,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"}),v=!1,P;if(i){let D=()=>{v=!0,P=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?D():i.addEventListener("abort",D,{once:!0})}let N="",M=new Oe("utf8");A.stdout&&A.stdout.on("data",D=>{N+=M.write(D);let H=N.split(`
16
+ ${s}`}function Fo(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(_t(e,n)),o}function Ho(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 Ss(s){return JSON.stringify(s)}function _s(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Ss(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(Ss).join(",")}]`]}function Es(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",..._s()),i||a.push("--color","never");let c=n||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(_t(e,r)),a}function ot(s,e){let t=Ve(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(":"),Et(t,e)}function Et(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(s.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function jo(s,e){let t=ot(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 Uo(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function ce(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Dt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ce(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ce(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ce(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ce(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Dt(n,e+1);if(r)return r}}function Ds(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 Ot(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=Ot(t,e+1);if(n)return n}}}function Bo(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
17
+ `))if(i.trim())try{let a=JSON.parse(i);t=Dt(a)||t,n=Ds(a)||n,r=Ot(a)||r,o=Os(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function Os(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return vs(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return vs(e)}}}function vs(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 Wo(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 Nt(s,e,t,n,r){let o=Wo(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 Ko(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 qo(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 Ns(s,e,t,n,r){let o=Date.now(),i=de(s,e,t),a=Fs(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=Ps(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Nt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:p,exitCode:y,killed:b}=await new Promise(I=>{let k=_e(Et(Ve(s.workspace),e),s.billing),_=!1,A=Lo("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...k,HOME:k.HOME||"/home/"+(k.USER||"user")}},(v,R,N)=>{I({stdout:R||"",stderr:N||"",exitCode:v?v.code??1:0,killed:_})});if(A.stdin?.end(),r){let v=()=>{_=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.killed||A.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?v():r.addEventListener("abort",v,{once:!0})}});if(b)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&y!==0){let I;return y===143?I=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:y==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?I=Rs():I=p?.trim()||`Claude Code exited with code ${y}`,{content:"",...q(I),duration:Date.now()-o}}let x=Ko(u);if(x)return{content:"",...q(x),duration:Date.now()-o};let w=qo(u);return{content:w.text,duration:Date.now()-o,claudeSessionId:w.sessionId,usage:w.usage,numTurns:w.numTurns,billedModel:w.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function Ls(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=de(s,e,n),d=Fs(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let l=Ps(s,c,!0,r,e.model,e.systemPromptAppend,d.args);Nt(e.agentId,s,e.model,r,"stream");let u="",p,y,b,x,w,I;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=_e(Et(Ve(s.workspace),e),s.billing),A=rt("claude",l,{cwd:s.workspace,timeout:k,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"}),v=!1,R;if(i){let D=()=>{v=!0,R=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?D():i.addEventListener("abort",D,{once:!0})}let N="",M=new Oe("utf8");A.stdout&&A.stdout.on("data",D=>{N+=M.write(D);let H=N.split(`
19
19
  `);N=H.pop()||"";for(let C of H)if(C.trim())try{let g=JSON.parse(C);if(o)try{o(g)}catch{}if(g.type==="assistant"&&g.message?.usage){let T=g.message.usage,E=(T.input_tokens||0)+(T.cache_read_input_tokens||0)+(T.cache_creation_input_tokens||0);E>0&&(x=E)}if(g.type==="assistant"&&g.message?.content){for(let T of g.message.content)if(T.type==="text"&&T.text){let E=T.text.slice(u.length);E&&(u=T.text,t(E,u))}}if(g.type==="content_block_delta"&&g.delta?.text&&(u+=g.delta.text,t(g.delta.text,u)),g.type==="result"&&g.result){if(g.is_error&&typeof g.result=="string")I=g.result;else{let T=(typeof g.result=="string",g.result);if(typeof T=="string"&&T.length>u.length){let E=T.slice(u.length);u=T,E&&t(E,u)}}g.usage&&(y={inputTokens:g.usage.input_tokens||0,outputTokens:g.usage.output_tokens||0,cacheReadTokens:g.usage.cache_read_input_tokens||0,cacheCreateTokens:g.usage.cache_creation_input_tokens||0}),typeof g.model=="string"&&(p=g.model),typeof g.session_id=="string"&&(b=g.session_id),typeof g.num_turns=="number"&&(w=g.num_turns)}g.type==="system"&&g.subtype==="init"&&(typeof g.model=="string"&&(p=g.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${g.apiKeySource} version=${g.claude_code_version} model=${g.model} permMode=${g.permissionMode}
20
20
  `))}catch{C.trim()&&!C.startsWith("{")&&(u+=C+`
21
21
  `,t(C+`
22
- `,u))}});let O=await A,F=M.end();if(F&&(N+=F),v)return{content:"",error:P||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&O.stdout&&(u=typeof O.stdout=="string"?O.stdout:""),O.exitCode!==0&&!u){let D=typeof O.stderr=="string"?O.stderr:"",H=O,C;return H.timedOut?C=`Claude Code timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:H.signal?C=D.trim()||`Claude Code killed by signal ${H.signal}`:H.code==="ENOENT"||/ENOENT|spawn claude/i.test((H.shortMessage||"")+" "+D)?C=Ms():C=D.trim()||`Claude Code exited with code ${H.exitCode??"unknown"}`,{content:"",...q(C),duration:Date.now()-a}}return I?{content:"",...q(I),duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}:{content:u,duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}}catch(k){return{content:u||"",...q(k.message),duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}}}async function qo(s,e,t,n){let r=Date.now(),o=de(s,e,t),i=vs(nt($s(),"agentx-codex-")),a=nt(i,"last-message.txt"),c=_s(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await rt("codex",c,{cwd:s.workspace,timeout:d,reject:!1,env:ot(s,e),extendEnv:!1,stdin:"ignore"}),u=Uo(l.stdout);if(l.exitCode!==0||u.apiError){let y=l,b;return y.timedOut?b=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?b=u.apiError:y.signal?b=l.stderr.trim()||`Codex CLI killed by signal ${y.signal}`:y.code==="ENOENT"||/ENOENT|spawn codex/i.test((y.shortMessage||"")+" "+l.stderr)?b=st():b=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${y.exitCode??"unknown"}`,{content:"",...q(b),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let p="";try{p=Cs(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(d){let l=/ENOENT|spawn codex/i.test(d?.message||"")?st():d?.message;return{content:"",...q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{As(i,{recursive:!0,force:!0})}}async function Go(s,e,t,n,r,o){let i=Date.now(),a=de(s,e,n),c=vs(nt($s(),"agentx-codex-")),d=nt(c,"last-message.txt"),l=_s(s,a,!0,e.model,e.systemPromptAppend,d,r),u="",p,y,b,x;try{let w=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),I=rt("codex",l,{cwd:s.workspace,timeout:w,reject:!1,env:ot(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let k="",_="",A=!1,v=new Oe("utf8"),P=new Oe("utf8"),N=Math.min(w,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),M,O=()=>{M&&clearTimeout(M),M=setTimeout(()=>{A=!0,I.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};O(),I.stderr?.on("data",g=>{O(),_+=P.write(g),_.length>16e3&&(_=_.slice(-16e3))}),I.stdout?.on("data",g=>{O(),k+=v.write(g);let T=k.split(`
23
- `);k=T.pop()||"";for(let E of T)if(E.trim())try{let L=JSON.parse(E);if(o)try{o(L)}catch{}p=Dt(L)||p,y=Es(L)||y,b=Ot(L)||b,x=Ds(L)||x;let m=jo(L);if(m&&m!==u){let X=m.startsWith(u)?m.slice(u.length):m;u=m.startsWith(u)?m:u+m,X&&t(X,u)}}catch{u+=E+`
22
+ `,u))}});let O=await A,F=M.end();if(F&&(N+=F),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&O.stdout&&(u=typeof O.stdout=="string"?O.stdout:""),O.exitCode!==0&&!u){let D=typeof O.stderr=="string"?O.stderr:"",H=O,C;return H.timedOut?C=`Claude Code timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:H.signal?C=D.trim()||`Claude Code killed by signal ${H.signal}`:H.code==="ENOENT"||/ENOENT|spawn claude/i.test((H.shortMessage||"")+" "+D)?C=Rs():C=D.trim()||`Claude Code exited with code ${H.exitCode??"unknown"}`,{content:"",...q(C),duration:Date.now()-a}}return I?{content:"",...q(I),duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}:{content:u,duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}}catch(k){return{content:u||"",...q(k.message),duration:Date.now()-a,usage:y,contextTokens:x,numTurns:w,billedModel:p,claudeSessionId:b}}}async function Go(s,e,t,n){let r=Date.now(),o=de(s,e,t),i=Cs(nt(Ms(),"agentx-codex-")),a=nt(i,"last-message.txt"),c=Es(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await rt("codex",c,{cwd:s.workspace,timeout:d,reject:!1,env:ot(s,e),extendEnv:!1,stdin:"ignore"}),u=Bo(l.stdout);if(l.exitCode!==0||u.apiError){let y=l,b;return y.timedOut?b=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?b=u.apiError:y.signal?b=l.stderr.trim()||`Codex CLI killed by signal ${y.signal}`:y.code==="ENOENT"||/ENOENT|spawn codex/i.test((y.shortMessage||"")+" "+l.stderr)?b=st():b=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${y.exitCode??"unknown"}`,{content:"",...q(b),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let p="";try{p=As(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(d){let l=/ENOENT|spawn codex/i.test(d?.message||"")?st():d?.message;return{content:"",...q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{$s(i,{recursive:!0,force:!0})}}async function Jo(s,e,t,n,r,o){let i=Date.now(),a=de(s,e,n),c=Cs(nt(Ms(),"agentx-codex-")),d=nt(c,"last-message.txt"),l=Es(s,a,!0,e.model,e.systemPromptAppend,d,r),u="",p,y,b,x;try{let w=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),I=rt("codex",l,{cwd:s.workspace,timeout:w,reject:!1,env:ot(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let k="",_="",A=!1,v=new Oe("utf8"),R=new Oe("utf8"),N=Math.min(w,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),M,O=()=>{M&&clearTimeout(M),M=setTimeout(()=>{A=!0,I.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};O(),I.stderr?.on("data",g=>{O(),_+=R.write(g),_.length>16e3&&(_=_.slice(-16e3))}),I.stdout?.on("data",g=>{O(),k+=v.write(g);let T=k.split(`
23
+ `);k=T.pop()||"";for(let E of T)if(E.trim())try{let L=JSON.parse(E);if(o)try{o(L)}catch{}p=Dt(L)||p,y=Ds(L)||y,b=Ot(L)||b,x=Os(L)||x;let m=Uo(L);if(m&&m!==u){let X=m.startsWith(u)?m.slice(u.length):m;u=m.startsWith(u)?m:u+m,X&&t(X,u)}}catch{u+=E+`
24
24
  `,t(E+`
25
- `,u)}});let F=await I;M&&clearTimeout(M);let D=v.end();D&&(k+=D);let H=P.end();if(H&&(_+=H),F.exitCode!==0&&!u||x){let g=_||(typeof F.stderr=="string"?F.stderr:""),T=F,E;return A?E=`Codex CLI produced no output for ${Math.round(N/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:T.timedOut?E=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:x?E=x:T.signal?E=g.trim()||`Codex CLI killed by signal ${T.signal}`:T.code==="ENOENT"||/ENOENT|spawn codex/i.test((T.shortMessage||"")+" "+g)?E=st():E=g.trim()||`Codex CLI exited with code ${T.exitCode??"unknown"}`,{content:"",...q(E),duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}let C="";try{C=Cs(d,"utf8").trim()}catch{}if(C&&C!==u){let g=C.startsWith(u)?C.slice(u.length):C;u=C,g&&t(g,u)}return{content:u,duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}catch(w){let I=/ENOENT|spawn codex/i.test(w?.message||"")?st():w?.message;return{content:u,...q(I||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}finally{As(c,{recursive:!0,force:!0})}}async function Jo(s,e,t,n,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=de(s,e,n),l=Lo(s,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",p,y=e.freshSession?void 0:r,b,x,w=!0,I;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=Ho(s,e);if(s.persistentProcess)try{x=await us.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:_,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",x.url),_=x.env,o?.({type:"opencode.ready",reused:x.reused,startupMs:Date.now()-c})}catch(g){if(!(g instanceof ie))throw g;g.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:g.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=rt("opencode",l,{cwd:s.workspace,timeout:k,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let v=!1,P,N=()=>{x?.invalidate(),v=!0,P=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),I=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let M="",O="",F=new Oe("utf8"),D=new Oe("utf8"),H=g=>{if(g.trim())try{let T=JSON.parse(g);try{o?.(T)}catch{}typeof T.sessionID=="string"&&(y=T.sessionID);let E=T.type==="text"&&typeof T.part?.text=="string"?T.part.text:void 0;E&&(u||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:x?.reused??!1}),u+=E,t?.(E,u));let L=T.type==="reasoning"&&typeof T.part?.text=="string"?T.part.text:void 0;L&&a?.(L);let m=T.type==="step_finish"?T.part?.tokens:void 0;m&&(p={inputTokens:ce(m.input),outputTokens:ce(m.output),cacheReadTokens:ce(m.cache?.read),cacheCreateTokens:ce(m.cache?.write)}),b=Fo(T)||b}catch{u+=g+`
25
+ `,u)}});let F=await I;M&&clearTimeout(M);let D=v.end();D&&(k+=D);let H=R.end();if(H&&(_+=H),F.exitCode!==0&&!u||x){let g=_||(typeof F.stderr=="string"?F.stderr:""),T=F,E;return A?E=`Codex CLI produced no output for ${Math.round(N/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:T.timedOut?E=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:x?E=x:T.signal?E=g.trim()||`Codex CLI killed by signal ${T.signal}`:T.code==="ENOENT"||/ENOENT|spawn codex/i.test((T.shortMessage||"")+" "+g)?E=st():E=g.trim()||`Codex CLI exited with code ${T.exitCode??"unknown"}`,{content:"",...q(E),duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}let C="";try{C=As(d,"utf8").trim()}catch{}if(C&&C!==u){let g=C.startsWith(u)?C.slice(u.length):C;u=C,g&&t(g,u)}return{content:u,duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}catch(w){let I=/ENOENT|spawn codex/i.test(w?.message||"")?st():w?.message;return{content:u,...q(I||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:y,codexSessionId:b||r}}finally{$s(c,{recursive:!0,force:!0})}}async function zo(s,e,t,n,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=de(s,e,n),l=Fo(s,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",p,y=e.freshSession?void 0:r,b,x,w=!0,I;try{let k=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=jo(s,e);if(s.persistentProcess)try{x=await ls.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:_,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",x.url),_=x.env,o?.({type:"opencode.ready",reused:x.reused,startupMs:Date.now()-c})}catch(g){if(!(g instanceof ie))throw g;g.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:g.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=rt("opencode",l,{cwd:s.workspace,timeout:k,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let v=!1,R,N=()=>{x?.invalidate(),v=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),I=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let M="",O="",F=new Oe("utf8"),D=new Oe("utf8"),H=g=>{if(g.trim())try{let T=JSON.parse(g);try{o?.(T)}catch{}typeof T.sessionID=="string"&&(y=T.sessionID);let E=T.type==="text"&&typeof T.part?.text=="string"?T.part.text:void 0;E&&(u||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:x?.reused??!1}),u+=E,t?.(E,u));let L=T.type==="reasoning"&&typeof T.part?.text=="string"?T.part.text:void 0;L&&a?.(L);let m=T.type==="step_finish"?T.part?.tokens:void 0;m&&(p={inputTokens:ce(m.input),outputTokens:ce(m.output),cacheReadTokens:ce(m.cache?.read),cacheCreateTokens:ce(m.cache?.write)}),b=Ho(T)||b}catch{u+=g+`
26
26
  `,t?.(g+`
27
27
  `,u)}};A.stdout?.on("data",g=>{M+=F.write(g);let T=M.split(`
28
- `);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:P||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=ks():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...q(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?ks():k?.message;return{content:u,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function zo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Qo(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=s.provider||"claude-code",I=n?`${n}
28
+ `);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=Is():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...q(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?Is():k?.message;return{content:u,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function Qo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Xo(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=s.provider||"claude-code",I=n?`${n}
29
29
 
30
- ${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),P=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:P?v:void 0};if(r){let{generateStream:H}=await import("./agent-3M5EI4S6.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(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 X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-3M5EI4S6.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function Xo(s,e,t,n,r,o,i){let a=tt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Nt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,P,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
30
+ ${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-HUKCS3AK.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(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 X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-HUKCS3AK.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function Yo(s,e,t,n,r,o,i){let a=tt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Nt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
31
31
  `)?`
32
32
 
33
- ${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=q(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(P=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=q(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=q(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.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",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:P}}function Ls(s){return oe(s.autonomy)?s.taskId?ws(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Yo(s,e,t,n,r,o,i){let a=e.autonomy,c=xs(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Cn(a)}
33
+ ${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=q(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(R=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=q(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=q(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.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",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:R}}function Fs(s){return oe(s.autonomy)?s.taskId?xs(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Vo(s,e,t,n,r,o,i){let a=e.autonomy,c=Ts(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Cn(a)}
34
34
 
35
35
  ${e.message}`};process.stderr.write(`[claude-autonomy] agent=${e.agentId} level=${a} task=${d} via=spawn (persistent process bypassed)
36
- `);let u=t?await Ns(s,l,t,n,r,o,i):await Os(s,l,n,r,i),p=Ts(d);return{...u,autonomy:a,...p.length?{autonomyBlocks:p}:{}}}async function Fs(s,e,t,n,r,o,i,a,c){if(oe(e.autonomy))return Yo(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let d=await Xo(s,e,r,o,i,a,n);if(d!==null)return d}return n?Ns(s,e,n,r,o,i,a):Os(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let d=await ls.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ot(s,e),args:Rs(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:_t(de(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...d,...d.error?q(d.error):{}}}catch(d){if(!(d instanceof ae))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Go(s,e,n,r,o,i):qo(s,e,r,o);case"opencode":return Jo(s,e,n,r,o,i,a,c);case"sdk":{let d=s.provider||"claude",l=t[d]?.apiKey;return l?zo(s,e,l,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=s.provider||"claude-code",l=t[d],u=l?.apiKey;return Qo(s,e,u,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as ke,writeFileSync as Hs,mkdirSync as Vo,existsSync as Lt,readdirSync as Ft}from"fs";import{resolve as Ie}from"path";var Ht=12e3,Ne=30,Zo=720,ei=40,ti=18e4,ni="[Compacted conversation summary",si=7*864e5,ri=[/\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 oi(s){return s?ri.some(e=>e.test(s)):!1}var ii=[{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 Us(s){if(!s)return null;let e=0;for(let t of ii)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function js(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 Bs(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 Ws(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 ai(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 it=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ie(e,".agentx/sessions"),Lt(this.sessionsDir)||Vo(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zo),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ei),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ti)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let l=await c.seedHistory(n,{maxMessages:Ne,maxChars:Ht});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ie(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(Lt(o))try{let d=JSON.parse(ke(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!Lt(i))return null;try{return JSON.parse(ke(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);js(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);js(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??Ne),a=Math.max(200,r.maxChars??Ht),c=[],d=0;for(let p=o.messages.length-1;p>=0&&c.length<i;p--){let y=o.messages[p];if(d+=y.content.length,c.push(y),d>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of c){let y=ai(p.timestamp);y!==u&&(l.push(`\u2014 ${y} \u2014`),u=y);let b=p.name||(p.role==="user"?"User":"Agent");l.push(`${b}: ${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,"_"),c;try{c=Ft(this.sessionsDir).filter(A=>A.startsWith(`${a}:`)&&A.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,p=c.filter(A=>{let v=A.match(u);if(!v)return!1;let P=v[1];return P>=d&&P<=l}),y=[],b=0,x=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let A of p){let v;try{v=JSON.parse(ke(Ie(this.sessionsDir,A),"utf-8"))}catch{continue}if(v.agentId===e.agentId&&!(e.channel&&v.channel!==e.channel)&&!(e.chatId&&v.chatId!==e.chatId))for(let P of v.messages)b++,!(!P.timestamp||P.timestamp<o||P.timestamp>=i)&&(w&&P.role==="user"&&!w.has(P.name??"")||x&&!P.content.toLowerCase().includes(x)||y.push({ts:P.timestamp,role:P.role,senderName:P.name??"",content:P.content,channel:v.channel,chatId:v.chatId,day:v.day,sessionFile:A}))}y.sort((A,v)=>v.ts.localeCompare(A.ts));let I=y.slice(0,t),k=I.length>0?I[I.length-1].ts:null,_=y.length>t;return{turns:I,oldestTs:k,hasMore:_,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ne,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=Ft(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}),c=[];for(let u of a){let p;try{p=JSON.parse(ke(Ie(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let y of p.messages)!y.timestamp||y.timestamp<n||c.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.content,agentId:p.agentId,sessionFile:u})}let d=new Set,l=[];for(let u of c){let p=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;d.has(p)||(d.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!==""&&!oi(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Ft(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let l=JSON.parse(ke(Ie(this.sessionsDir,d),"utf-8"));if(l.id===i||l.messages.length===0)continue;let u=l.messages.slice(-4),y=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,b=u.map(x=>` [${x.timestamp.slice(11,16)}] ${x.name||x.role}: ${x.content.slice(0,200)}`);c.push(`From ${y} (${l.channel}):
36
+ `);let u=t?await Ls(s,l,t,n,r,o,i):await Ns(s,l,n,r,i),p=ks(d);return{...u,autonomy:a,...p.length?{autonomyBlocks:p}:{}}}async function Hs(s,e,t,n,r,o,i,a,c){if(oe(e.autonomy))return Vo(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let d=await Yo(s,e,r,o,i,a,n);if(d!==null)return d}return n?Ls(s,e,n,r,o,i,a):Ns(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let d=await gs.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ot(s,e),args:_s(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:_t(de(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...d,...d.error?q(d.error):{}}}catch(d){if(!(d instanceof ae))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Jo(s,e,n,r,o,i):Go(s,e,r,o);case"opencode":return zo(s,e,n,r,o,i,a,c);case"sdk":{let d=s.provider||"claude",l=t[d]?.apiKey;return l?Qo(s,e,l,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=s.provider||"claude-code",l=t[d],u=l?.apiKey;return Xo(s,e,u,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as ke,writeFileSync as js,mkdirSync as Zo,existsSync as Lt,readdirSync as Ft}from"fs";import{resolve as Ie}from"path";var Ht=12e3,Ne=30,ei=720,ti=40,ni=18e4,si="[Compacted conversation summary",ri=7*864e5,oi=[/\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 ii(s){return s?oi.some(e=>e.test(s)):!1}var ai=[{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 Bs(s){if(!s)return null;let e=0;for(let t of ai)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Us(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 Ws(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 Ks(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 ci(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 it=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ie(e,".agentx/sessions"),Lt(this.sessionsDir)||Zo(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??ei),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ti),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ni)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let l=await c.seedHistory(n,{maxMessages:Ne,maxChars:Ht});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ie(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(Lt(o))try{let d=JSON.parse(ke(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!Lt(i))return null;try{return JSON.parse(ke(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);Us(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);Us(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??Ne),a=Math.max(200,r.maxChars??Ht),c=[],d=0;for(let p=o.messages.length-1;p>=0&&c.length<i;p--){let y=o.messages[p];if(d+=y.content.length,c.push(y),d>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of c){let y=ci(p.timestamp);y!==u&&(l.push(`\u2014 ${y} \u2014`),u=y);let b=p.name||(p.role==="user"?"User":"Agent");l.push(`${b}: ${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,"_"),c;try{c=Ft(this.sessionsDir).filter(A=>A.startsWith(`${a}:`)&&A.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,p=c.filter(A=>{let v=A.match(u);if(!v)return!1;let R=v[1];return R>=d&&R<=l}),y=[],b=0,x=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let A of p){let v;try{v=JSON.parse(ke(Ie(this.sessionsDir,A),"utf-8"))}catch{continue}if(v.agentId===e.agentId&&!(e.channel&&v.channel!==e.channel)&&!(e.chatId&&v.chatId!==e.chatId))for(let R of v.messages)b++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(w&&R.role==="user"&&!w.has(R.name??"")||x&&!R.content.toLowerCase().includes(x)||y.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:v.channel,chatId:v.chatId,day:v.day,sessionFile:A}))}y.sort((A,v)=>v.ts.localeCompare(A.ts));let I=y.slice(0,t),k=I.length>0?I[I.length-1].ts:null,_=y.length>t;return{turns:I,oldestTs:k,hasMore:_,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ne,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=Ft(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}),c=[];for(let u of a){let p;try{p=JSON.parse(ke(Ie(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let y of p.messages)!y.timestamp||y.timestamp<n||c.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.content,agentId:p.agentId,sessionFile:u})}let d=new Set,l=[];for(let u of c){let p=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;d.has(p)||(d.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!==""&&!ii(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Ft(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let l=JSON.parse(ke(Ie(this.sessionsDir,d),"utf-8"));if(l.id===i||l.messages.length===0)continue;let u=l.messages.slice(-4),y=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,b=u.map(x=>` [${x.timestamp.slice(11,16)}] ${x.name||x.role}: ${x.content.slice(0,200)}`);c.push(`From ${y} (${l.channel}):
38
38
  ${b.join(`
39
39
  `)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
40
- `)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-H5U32UU6.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(ni)}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 Ie(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Hs(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>si?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>Ne&&(e.messages=e.messages.slice(-Ne));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Ht&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&pe.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);Hs(t,JSON.stringify(e,null,2))}catch{}}};var at=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as Le,writeFileSync as Ks,appendFileSync as ci,existsSync as Se,mkdirSync as di}from"fs";import{resolve as ve}from"path";var Gs={"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}},Js=2e5,ui=1.5;function li(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 zs(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Js?{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 qs=500,gi=".agentx/pricing/custom.json",Ce=class{dir;cache=null;pricing;constructor(e=ve(process.cwd(),".agentx/usage")){this.dir=e,di(this.dir,{recursive:!0}),this.pricing=pi()}getPricing(){return this.pricing}static calculateCost(e,t,n=Gs){let r=li(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,u=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return l+u*ui}cost(e,t){return Ce.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,c,d){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let p=0,y=0,b=0,x=0,w=0,I=0,k=0,_=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Js?(w=n.inputTokens,I=n.outputTokens,k=n.cacheReadTokens,_=n.cacheCreateTokens):(p=n.inputTokens,y=n.outputTokens,b=n.cacheReadTokens,x=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),y=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=y,u.cacheReadTokens+=b,u.cacheCreateTokens+=x,u.tier2InputTokens=(u.tier2InputTokens||0)+w,u.tier2OutputTokens=(u.tier2OutputTokens||0)+I,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+k,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+_,i&&u.errors++,u.byChannel||(u.byChannel={});let A=(c||"other").toLowerCase(),v=u.byChannel[A]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};v.tasks++,v.totalDuration+=t,v.inputTokens+=p,v.outputTokens+=y,v.cacheReadTokens+=b,v.cacheCreateTokens+=x,v.tier2InputTokens+=w,v.tier2OutputTokens+=I,v.tier2CacheReadTokens+=k,v.tier2CacheCreateTokens+=_,i&&v.errors++,u.byChannel[A]=v,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>qs&&u.sessionKeys.splice(0,u.sessionKeys.length-qs))),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(Se(t))try{return this.cache=JSON.parse(Le(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Se(t))return null;try{return JSON.parse(Le(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,c=0,d=0,l="",u=0,p={},y={},b={};for(let[x,w]of Object.entries(n.agents)){let I=this.cost(w);p[x]=I,r+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),d+=I,I>u&&(u=I,l=x);let k=w.sessionKeys?.length||0;y[x]={sessions:k,avgTasksPerSession:k>0?w.tasks/k:w.tasks};for(let[_,A]of Object.entries(w.byChannel||{})){let v=this.cost(A,w.model);b[_]=(b[_]||0)+v}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:y,byChannel:b}}appendToTokenCosts(e,t){let n=t||ve(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=Object.entries(e.agentCosts).sort(([,d],[,l])=>l-d).map(([d,l])=>{let u=e.agentSessionStats[d],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,l])=>l-d).map(([d,l])=>`${d}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;Se(n)?ci(n,c+`
41
- `):Ks(n,`# Token Costs
40
+ `)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-H5U32UU6.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:n});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(si)}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 Ie(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},js(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>ri?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>Ne&&(e.messages=e.messages.slice(-Ne));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Ht&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&pe.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);js(t,JSON.stringify(e,null,2))}catch{}}};var at=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as Le,writeFileSync as qs,appendFileSync as di,existsSync as Se,mkdirSync as ui}from"fs";import{resolve as ve}from"path";var Js={"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}},zs=2e5,li=1.5;function gi(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 Qs(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>zs?{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 Gs=500,pi=".agentx/pricing/custom.json",Ce=class{dir;cache=null;pricing;constructor(e=ve(process.cwd(),".agentx/usage")){this.dir=e,ui(this.dir,{recursive:!0}),this.pricing=hi()}getPricing(){return this.pricing}static calculateCost(e,t,n=Js){let r=gi(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,u=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return l+u*li}cost(e,t){return Ce.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,c,d){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let p=0,y=0,b=0,x=0,w=0,I=0,k=0,_=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>zs?(w=n.inputTokens,I=n.outputTokens,k=n.cacheReadTokens,_=n.cacheCreateTokens):(p=n.inputTokens,y=n.outputTokens,b=n.cacheReadTokens,x=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),y=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=y,u.cacheReadTokens+=b,u.cacheCreateTokens+=x,u.tier2InputTokens=(u.tier2InputTokens||0)+w,u.tier2OutputTokens=(u.tier2OutputTokens||0)+I,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+k,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+_,i&&u.errors++,u.byChannel||(u.byChannel={});let A=(c||"other").toLowerCase(),v=u.byChannel[A]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};v.tasks++,v.totalDuration+=t,v.inputTokens+=p,v.outputTokens+=y,v.cacheReadTokens+=b,v.cacheCreateTokens+=x,v.tier2InputTokens+=w,v.tier2OutputTokens+=I,v.tier2CacheReadTokens+=k,v.tier2CacheCreateTokens+=_,i&&v.errors++,u.byChannel[A]=v,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>Gs&&u.sessionKeys.splice(0,u.sessionKeys.length-Gs))),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(Se(t))try{return this.cache=JSON.parse(Le(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Se(t))return null;try{return JSON.parse(Le(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,c=0,d=0,l="",u=0,p={},y={},b={};for(let[x,w]of Object.entries(n.agents)){let I=this.cost(w);p[x]=I,r+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),d+=I,I>u&&(u=I,l=x);let k=w.sessionKeys?.length||0;y[x]={sessions:k,avgTasksPerSession:k>0?w.tasks/k:w.tasks};for(let[_,A]of Object.entries(w.byChannel||{})){let v=this.cost(A,w.model);b[_]=(b[_]||0)+v}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:y,byChannel:b}}appendToTokenCosts(e,t){let n=t||ve(process.cwd(),".agentx/TOKEN_COSTS.md"),r=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=Object.entries(e.agentCosts).sort(([,d],[,l])=>l-d).map(([d,l])=>{let u=e.agentSessionStats[d],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,l])=>l-d).map(([d,l])=>`${d}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;Se(n)?di(n,c+`
41
+ `):qs(n,`# Token Costs
42
42
 
43
43
  Daily token cost tracking. Auto-appended at midnight, host time.
44
44
  Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
@@ -46,18 +46,18 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
46
46
  | Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
47
47
  |------|-------|-------|--------|---------|---------|------|-----------|-------------|
48
48
  `+c+`
49
- `)}hasTokenCostsEntry(e,t){let n=t||ve(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Se(n))return!1;try{let r=Le(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||ve(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Se(t))return null;try{let r=Le(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,c=0,d={},l={};for(let b=0;b<e;b++){let x=new Date(Date.now()-b*864e5).toISOString().slice(0,10),w=this.getDate(x);if(w)for(let[I,k]of Object.entries(w.agents)){let _=this.cost(k);t+=k.tasks;let A=(k.inputTokens||0)+(k.tier2InputTokens||0),v=(k.outputTokens||0)+(k.tier2OutputTokens||0),P=(k.cacheReadTokens||0)+(k.tier2CacheReadTokens||0),N=(k.cacheCreateTokens||0)+(k.tier2CacheCreateTokens||0);n+=A,r+=v,o+=P,i+=N,a+=k.errors,c+=_;let M=d[I]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};M.tasks+=k.tasks,M.input+=A,M.output+=v,M.cacheRead+=P,M.cacheCreate+=N,M.total=M.input+M.output+M.cacheRead+M.cacheCreate,M.totalDuration+=k.totalDuration,M.avgDuration=M.totalDuration/M.tasks,M.cost+=_,M.sessions+=k.sessionKeys?.length||0,k.model&&(M.model=k.model),d[I]=M;for(let[O,F]of Object.entries(k.byChannel||{})){let D=this.cost(F,k.model),H=l[O]||{tasks:0,cost:0};H.tasks+=F.tasks,H.cost+=D,l[O]=H}}}let u=n+r+o+i,p=o+i>0?o/(o+i):0,y={};for(let[b,x]of Object.entries(d))y[b]={sessions:x.sessions,avgTasksPerSession:x.sessions>0?x.tasks/x.sessions:x.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:y}}filePath(e){return ve(this.dir,`${e}.json`)}save(e){try{Ks(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function pi(){let s=JSON.parse(JSON.stringify(Gs));try{let e=ve(process.cwd(),gi);if(!Se(e))return s;let t=JSON.parse(Le(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 hi={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}},Qs=4;function Xs(s,e=hi){let t=mi(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Qs;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Qs,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let d=o-r;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),r+=c.length}return n.join(`
49
+ `)}hasTokenCostsEntry(e,t){let n=t||ve(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Se(n))return!1;try{let r=Le(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||ve(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Se(t))return null;try{let r=Le(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,c=0,d={},l={};for(let b=0;b<e;b++){let x=new Date(Date.now()-b*864e5).toISOString().slice(0,10),w=this.getDate(x);if(w)for(let[I,k]of Object.entries(w.agents)){let _=this.cost(k);t+=k.tasks;let A=(k.inputTokens||0)+(k.tier2InputTokens||0),v=(k.outputTokens||0)+(k.tier2OutputTokens||0),R=(k.cacheReadTokens||0)+(k.tier2CacheReadTokens||0),N=(k.cacheCreateTokens||0)+(k.tier2CacheCreateTokens||0);n+=A,r+=v,o+=R,i+=N,a+=k.errors,c+=_;let M=d[I]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};M.tasks+=k.tasks,M.input+=A,M.output+=v,M.cacheRead+=R,M.cacheCreate+=N,M.total=M.input+M.output+M.cacheRead+M.cacheCreate,M.totalDuration+=k.totalDuration,M.avgDuration=M.totalDuration/M.tasks,M.cost+=_,M.sessions+=k.sessionKeys?.length||0,k.model&&(M.model=k.model),d[I]=M;for(let[O,F]of Object.entries(k.byChannel||{})){let D=this.cost(F,k.model),H=l[O]||{tasks:0,cost:0};H.tasks+=F.tasks,H.cost+=D,l[O]=H}}}let u=n+r+o+i,p=o+i>0?o/(o+i):0,y={};for(let[b,x]of Object.entries(d))y[b]={sessions:x.sessions,avgTasksPerSession:x.sessions>0?x.tasks/x.sessions:x.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:y}}filePath(e){return ve(this.dir,`${e}.json`)}save(e){try{qs(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function hi(){let s=JSON.parse(JSON.stringify(Js));try{let e=ve(process.cwd(),pi);if(!Se(e))return s;let t=JSON.parse(Le(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 mi={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}},Xs=4;function Ys(s,e=mi){let t=fi(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Xs;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Xs,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let d=o-r;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),r+=c.length}return n.join(`
50
50
 
51
- `)}function mi(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(fi(s,t("channel",200))),n.push(yi(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(`
51
+ `)}function fi(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(yi(s,t("channel",200))),n.push(bi(s,t("scope",200))),s.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:s.landscape,tags:["landscape","world-model"]}),s.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:s.systemPrompt.split(`
52
52
  `)[0],tags:["identity",s.agentId]}),s.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:s.bootstrapContext,tags:["bootstrap","identity","personality"]}),s.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:s.references,tags:["references","verified","deterministic"]}),s.intent&&s.intent.path.length>0){let i=[`[Intent path: ${s.intent.pathLabel}${s.intent.status==="pending"?" (pending approval)":""}]`],a=s.intent.path[s.intent.path.length-1],c=s.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([l,u])=>` ${l}: ${u}`).join(`
53
53
  `);i.push(d)}s.intent.leaf?.input&&i.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
54
- `),tags:["intent",...s.intent.path]})}else{let i=bi(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
54
+ `),tags:["intent",...s.intent.path]})}else{let i=wi(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
55
55
  `),tags:["artifacts",...s.mediaType?["media"]:[]]}),s.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:s.skillInjection,tags:["skills","auto-inject"]}),s.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:s.patternContext,tags:["patterns","behavioral","self-improving"]}),s.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:s.procedureContext,tags:["procedures","sop"]}),s.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:s.memoryContext,tags:["memory","persistent"]});let o=s.groupHistory||s.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),s.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:s.crossChatContext,tags:["history","cross-chat"]}),s.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:s.longMemoryRecall,tags:["history","long-memory"]}),s.handoverNote){let i=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&i.push(`Operator summary: ${s.handoverNote.summary}`),i.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
56
56
  `),tags:["handover",s.handoverNote.fromAgent]})}return s.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${s.rotationMemo.reason}, ${s.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,s.rotationMemo.memo].join(`
57
- `),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function fi(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
58
- `),tags:r,rules:n}}function yi(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
59
- `),tags:n}}function bi(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}function Ys(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=32e3?e:null}catch{return null}}function Kc(s){if(!s)return null;try{let e=JSON.parse(s);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="direct")return e}catch{}return null}var ct=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
60
- `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as wi,writeFileSync as Vs,appendFileSync as xi,mkdirSync as Ti,existsSync as Zs}from"fs";import{resolve as jt}from"path";var er=50,ki="claude-haiku-4-20250514",Ii=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
57
+ `),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function yi(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
58
+ `),tags:r,rules:n}}function bi(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
59
+ `),tags:n}}function wi(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}function Vs(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=32e3?e:null}catch{return null}}function Jc(s){if(!s)return null;try{let e=JSON.parse(s);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="direct")return e}catch{}return null}var ct=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
60
+ `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as xi,writeFileSync as Zs,appendFileSync as Ti,mkdirSync as ki,existsSync as er}from"fs";import{resolve as jt}from"path";var tr=50,Ii="claude-haiku-4-20250514",Si=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
61
61
 
62
62
  Extract patterns like:
63
63
  - "When asked about X, the approach that works is Y"
@@ -73,20 +73,20 @@ SKIP:
73
73
  Output a JSON array:
74
74
  [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
75
75
 
76
- If nothing worth extracting, output: []`,dt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=jt(e,".agentx/patterns"),Zs(this.patternsDir)||Ti(this.patternsDir,{recursive:!0})}filePath(e){return jt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Zs(t))return[];try{return wi(t,"utf-8").split(`
77
- `).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};xi(this.filePath(e),JSON.stringify(n)+`
76
+ If nothing worth extracting, output: []`,dt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=jt(e,".agentx/patterns"),er(this.patternsDir)||ki(this.patternsDir,{recursive:!0})}filePath(e){return jt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!er(t))return[];try{return xi(t,"utf-8").split(`
77
+ `).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Ti(this.filePath(e),JSON.stringify(n)+`
78
78
  `)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=jt(this.patternsDir,`${t}_bm25_cache.json`),a=In(o,i),d=kn(e,a).slice(0,n).map(l=>r[l.docIndex]).filter(l=>l.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(l=>l.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
79
- `)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Vs(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
79
+ `)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Zs(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
80
80
  `)+`
81
- `)}prune(e){let t=this.getAll(e);t.length<=er||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,er),Vs(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
81
+ `)}prune(e){let t=this.getAll(e);t.length<=tr||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,tr),Zs(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
82
82
  `)+`
83
- `))}};async function tr(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-NRPX2FHP.js"),c=(await o("claude").generate([{role:"system",content:Ii},{role:"user",content:`User: ${e.slice(0,500)}
83
+ `))}};async function nr(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-NRPX2FHP.js"),c=(await o("claude").generate([{role:"system",content:Si},{role:"user",content:`User: ${e.slice(0,500)}
84
84
 
85
- Agent: ${t.slice(0,1e3)}`}],{model:ki,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let l of d)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as Si}from"events";var vi=2e4,Bt=class{inner=new Si;envelopeListeners=new Set;ring=new Yn;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let n=this.inner.emit(e,t);try{this.publish(Ci(e,t))}catch{}return n}publish(e){let t=Xn(),n=e.id??Qn(),r={id:n,rootId:e.rootId??t?.rootId??n,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:vt(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>vi&&this.seen.delete(this.seen.keys().next().value);let n={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:vt(e.summary??"")};e.parentId&&(n.parentId=e.parentId),e.agentId&&(n.agentId=e.agentId),e.ref&&(n.ref=e.ref),this.ring.push(n);for(let r of this.envelopeListeners)try{r(n)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function Ci(s,e){let t=e,n={type:s,at:t.at,agentId:t.agentId,ref:t.taskId};switch(s){case"message:matched":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:started":return{...n,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...n,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...n,kind:"agent",summary:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...n,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...n,kind:"agent",summary:String(s)}}}var Ut;function ee(){return Ut||(Ut=new Bt),Ut}wt();wt();var nr=["manual","notify","auto"];function Ai(s){return typeof s=="string"&&nr.includes(s)}var Wt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var $i=7*24*60*6e4,Fe=class{constructor(e={},t){this.store=t;this.opts={...Wt,...e};let n={};try{n=t?.load()??{}}catch{n={}}let r=Date.now()-$i;for(let[o,i]of Object.entries(n))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,n),i}touch(e,t=Date.now()){let n=this.sessions.get(e);return n?(n.lastSeenAt=t,n):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r.watch=void 0,this.remember(r),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],t||(n.watch=void 0),this.remember(n),n}watch(e,t,n=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,n,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:n},this.remember(r,n),r}advanceWatch(e,t){let n=this.sessions.get(e);n?.watch&&(n.watch.cursor.id===t.id&&n.watch.cursor.at===t.at||(n.watch.cursor=t,this.remember(n)))}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,this.remember(n),n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),n={}){this.sessions.delete(e),n.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,n){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,n)}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:be(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:Mi(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let n={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(n.watch={...e.watch}),this.saved.set(e.sessionId,n)}for(let[n,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(n);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Mi(s,e){return s.length<=e?s:`${s.slice(0,e)}
86
- \u2026[truncated ${s.length-e} chars]`}lo();import{z as Pi}from"zod";var rr=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Ri(s){if(s==null)return{ok:!0,subscriptions:rr};let e=Pi.array(An).min(1).safeParse(s);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var _i=15,Ei=1500,sr=200;function or(s,e=Date.now()){let t=s[s.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Di(s,e){if(e.id){let n=s.findIndex(r=>r.id===e.id);if(n>=0)return s.slice(n+1)}let t=Date.parse(e.at);return Number.isNaN(t)?s:e.id?s.filter(n=>Date.parse(n.at)>t):s.filter(n=>Date.parse(n.at)>=t)}function ad(s,e,t={}){let n=Di(e,s.cursor),r=n.length?or(n):s.cursor,o=n.filter(d=>s.subscriptions.some(l=>Vn(l,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=s.cursor.id??s.cursor.at,{text:a,shown:c}=Oi(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function Oi(s,e,t={}){let n=Math.max(3,t.maxLines??_i),r=Math.max(200,t.maxChars??Ei),o=s.map(a=>Ni(`- ${es(a)}`)),i=o.length;for(let a=Math.min(i,n-1);a>=0;a--){let c=i-a,l=[c?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];c&&l.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let u=l.join(`
87
- `);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Ni(s){return s.length<=sr?s:`${s.slice(0,sr-1)}\u2026`}import{existsSync as Li,mkdirSync as Fi,readFileSync as Hi,renameSync as ji,writeFileSync as Ui}from"node:fs";import{homedir as Bi}from"node:os";import{dirname as Wi,join as Ki}from"node:path";function qi(s){return{load:()=>Li(s)?JSON.parse(Hi(s,"utf-8")):{},save:e=>{Fi(Wi(s),{recursive:!0});let t=`${s}.tmp`;Ui(t,JSON.stringify(e,null,2),{mode:384}),ji(t,s)}}}function Gi(){if(!process.env.VITEST)return qi(process.env.AGENTX_ATTACH_BINDINGS_FILE??Ki(Bi(),".agentx","attach-bindings.json"))}var Kt;function ir(){return Kt||(Kt=new Fe({},Gi())),Kt}xt();import{readFileSync as Ji}from"fs";import{homedir as zi}from"os";import{join as Qi}from"path";var He=null,Xi=6e4;function Yi(){try{let s=Qi(zi(),".claude.json"),e=Ji(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function Vi(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Zi(s=!1){let e=Date.now();return!s&&He&&e-He.checkedAt<Xi||(He=Vi(Yi(),e)),He}function ar(s){let e=Zi();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var cr={warnRatio:.8},z={...cr},ea=5*60*60*1e3,ta=60*60*1e3,he=[];function dr(s){z={...cr,...s||{}}}function ur(s){let e=s-ea,t=0;for(;t<he.length&&he[t]<e;)t++;t>0&&he.splice(0,t)}function lr(s=Date.now()){ur(s),he.push(s)}function gr(s=Date.now()){ur(s);let e=s-ta,t=0;for(let o=he.length-1;o>=0&&he[o]>=e;o--)t++;let n=he.length,r={lastHour:t,last5h:n,maxPerHour:z.maxPerHour,maxPer5h:z.maxPer5h};return z.maxPerHour&&z.maxPerHour>0&&(r.hourlyRatio=t/z.maxPerHour),z.maxPer5h&&z.maxPer5h>0&&(r.fiveHourRatio=n/z.maxPer5h),r}function pr(s,e=Date.now()){let t=gr(e);return s?null:z.maxPerHour&&t.lastHour>=z.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${z.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:z.maxPer5h&&t.last5h>=z.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${z.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function hr(s=Date.now()){let e=gr(s),t=z.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var qt=new Map;function mr(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function fr(s,e,t,n=Date.now()){let r=qt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},qt.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function yr(s){let e=qt.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as V,mkdirSync as $a,readdirSync as ne,readFileSync as Ue,rmSync as Ma,writeFileSync as Pa}from"fs";import{resolve as B}from"path";import{existsSync as fe,mkdirSync as Gt,readFileSync as na,readdirSync as sa,renameSync as ra,unlinkSync as oa,writeFileSync as ut}from"fs";import{resolve as ue,relative as lt}from"path";import{z as K}from"zod";var me=K.object({id:K.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:K.string().min(1),trigger:K.string().min(1,"procedures must describe when they apply"),inputs:K.array(K.string()).default([]),expected:K.string().optional(),kpis:K.array(K.string()).default([]),owner:K.string().optional(),tags:K.array(K.string()).default([]),status:K.enum(["draft","active","deprecated"]).default("active"),source:K.string().optional(),evidence:K.array(K.string()).default([]),created:K.string().optional(),updated:K.string().optional(),related:K.array(K.string()).default([])});function ia(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
85
+ Agent: ${t.slice(0,1e3)}`}],{model:Ii,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let l of d)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as vi}from"events";var Ci=2e4,Bt=class{inner=new vi;envelopeListeners=new Set;ring=new Yn;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let n=this.inner.emit(e,t);try{this.publish(Ai(e,t))}catch{}return n}publish(e){let t=Xn(),n=e.id??Qn(),r={id:n,rootId:e.rootId??t?.rootId??n,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:vt(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>Ci&&this.seen.delete(this.seen.keys().next().value);let n={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:vt(e.summary??"")};e.parentId&&(n.parentId=e.parentId),e.agentId&&(n.agentId=e.agentId),e.ref&&(n.ref=e.ref),this.ring.push(n);for(let r of this.envelopeListeners)try{r(n)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function Ai(s,e){let t=e,n={type:s,at:t.at,agentId:t.agentId,ref:t.taskId};switch(s){case"message:matched":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:started":return{...n,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...n,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...n,kind:"agent",summary:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...n,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...n,kind:"agent",summary:String(s)}}}var Ut;function ee(){return Ut||(Ut=new Bt),Ut}wt();wt();var sr=["manual","notify","auto"];function $i(s){return typeof s=="string"&&sr.includes(s)}var Wt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Mi=7*24*60*6e4,Fe=class{constructor(e={},t){this.store=t;this.opts={...Wt,...e};let n={};try{n=t?.load()??{}}catch{n={}}let r=Date.now()-Mi;for(let[o,i]of Object.entries(n))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,n),i}touch(e,t=Date.now()){let n=this.sessions.get(e);return n?(n.lastSeenAt=t,n):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r.watch=void 0,this.remember(r),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],t||(n.watch=void 0),this.remember(n),n}watch(e,t,n=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,n,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:n},this.remember(r,n),r}advanceWatch(e,t){let n=this.sessions.get(e);n?.watch&&(n.watch.cursor.id===t.id&&n.watch.cursor.at===t.at||(n.watch.cursor=t,this.remember(n)))}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,this.remember(n),n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),n={}){this.sessions.delete(e),n.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,n){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,n)}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:be(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:Ri(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let n={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(n.watch={...e.watch}),this.saved.set(e.sessionId,n)}for(let[n,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(n);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Ri(s,e){return s.length<=e?s:`${s.slice(0,e)}
86
+ \u2026[truncated ${s.length-e} chars]`}go();import{z as Pi}from"zod";var or=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function _i(s){if(s==null)return{ok:!0,subscriptions:or};let e=Pi.array(An).min(1).safeParse(s);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var Ei=15,Di=1500,rr=200;function ir(s,e=Date.now()){let t=s[s.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Oi(s,e){if(e.id){let n=s.findIndex(r=>r.id===e.id);if(n>=0)return s.slice(n+1)}let t=Date.parse(e.at);return Number.isNaN(t)?s:e.id?s.filter(n=>Date.parse(n.at)>t):s.filter(n=>Date.parse(n.at)>=t)}function ud(s,e,t={}){let n=Oi(e,s.cursor),r=n.length?ir(n):s.cursor,o=n.filter(d=>s.subscriptions.some(l=>Vn(l,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=s.cursor.id??s.cursor.at,{text:a,shown:c}=Ni(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function Ni(s,e,t={}){let n=Math.max(3,t.maxLines??Ei),r=Math.max(200,t.maxChars??Di),o=s.map(a=>Li(`- ${es(a)}`)),i=o.length;for(let a=Math.min(i,n-1);a>=0;a--){let c=i-a,l=[c?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];c&&l.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let u=l.join(`
87
+ `);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Li(s){return s.length<=rr?s:`${s.slice(0,rr-1)}\u2026`}import{existsSync as Fi,mkdirSync as Hi,readFileSync as ji,renameSync as Ui,writeFileSync as Bi}from"node:fs";import{homedir as Wi}from"node:os";import{dirname as Ki,join as qi}from"node:path";function Gi(s){return{load:()=>Fi(s)?JSON.parse(ji(s,"utf-8")):{},save:e=>{Hi(Ki(s),{recursive:!0});let t=`${s}.tmp`;Bi(t,JSON.stringify(e,null,2),{mode:384}),Ui(t,s)}}}function Ji(){if(!process.env.VITEST)return Gi(process.env.AGENTX_ATTACH_BINDINGS_FILE??qi(Wi(),".agentx","attach-bindings.json"))}var Kt;function ar(){return Kt||(Kt=new Fe({},Ji())),Kt}xt();import{readFileSync as zi}from"fs";import{homedir as Qi}from"os";import{join as Xi}from"path";var He=null,Yi=6e4;function Vi(){try{let s=Xi(Qi(),".claude.json"),e=zi(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function Zi(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function ea(s=!1){let e=Date.now();return!s&&He&&e-He.checkedAt<Yi||(He=Zi(Vi(),e)),He}function cr(s){let e=ea();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var dr={warnRatio:.8},z={...dr},ta=5*60*60*1e3,na=60*60*1e3,he=[];function ur(s){z={...dr,...s||{}}}function lr(s){let e=s-ta,t=0;for(;t<he.length&&he[t]<e;)t++;t>0&&he.splice(0,t)}function gr(s=Date.now()){lr(s),he.push(s)}function pr(s=Date.now()){lr(s);let e=s-na,t=0;for(let o=he.length-1;o>=0&&he[o]>=e;o--)t++;let n=he.length,r={lastHour:t,last5h:n,maxPerHour:z.maxPerHour,maxPer5h:z.maxPer5h};return z.maxPerHour&&z.maxPerHour>0&&(r.hourlyRatio=t/z.maxPerHour),z.maxPer5h&&z.maxPer5h>0&&(r.fiveHourRatio=n/z.maxPer5h),r}function hr(s,e=Date.now()){let t=pr(e);return s?null:z.maxPerHour&&t.lastHour>=z.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${z.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:z.maxPer5h&&t.last5h>=z.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${z.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function mr(s=Date.now()){let e=pr(s),t=z.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var qt=new Map;function fr(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function yr(s,e,t,n=Date.now()){let r=qt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},qt.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function br(s){let e=qt.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as V,mkdirSync as Ma,readdirSync as ne,readFileSync as Ue,rmSync as Ra,writeFileSync as Pa}from"fs";import{resolve as B}from"path";import{existsSync as fe,mkdirSync as Gt,readFileSync as sa,readdirSync as ra,renameSync as oa,unlinkSync as ia,writeFileSync as ut}from"fs";import{resolve as ue,relative as lt}from"path";import{z as K}from"zod";var me=K.object({id:K.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:K.string().min(1),trigger:K.string().min(1,"procedures must describe when they apply"),inputs:K.array(K.string()).default([]),expected:K.string().optional(),kpis:K.array(K.string()).default([]),owner:K.string().optional(),tags:K.array(K.string()).default([]),status:K.enum(["draft","active","deprecated"]).default("active"),source:K.string().optional(),evidence:K.array(K.string()).default([]),created:K.string().optional(),updated:K.string().optional(),related:K.array(K.string()).default([])});function aa(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
88
88
  `)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function gt(s){let e=["---"];return e.push(`id: ${s.id}`),e.push(`title: "${s.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${s.trigger.replace(/"/g,'\\"')}"`),s.inputs?.length&&e.push(`inputs: ${JSON.stringify(s.inputs)}`),s.expected&&e.push(`expected: "${s.expected.replace(/"/g,'\\"')}"`),s.kpis?.length&&e.push(`kpis: ${JSON.stringify(s.kpis)}`),s.owner&&e.push(`owner: ${s.owner}`),s.tags?.length&&e.push(`tags: ${JSON.stringify(s.tags)}`),e.push(`status: ${s.status}`),s.source&&e.push(`source: "${s.source.replace(/"/g,'\\"')}"`),s.evidence?.length&&e.push(`evidence: ${JSON.stringify(s.evidence)}`),s.related?.length&&e.push(`related: ${JSON.stringify(s.related)}`),s.created&&e.push(`created: ${s.created}`),s.updated&&e.push(`updated: ${s.updated}`),e.push("---"),e.join(`
89
- `)}var je=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ue(process.cwd(),".agentx/procedures"),Gt(this.baseDir,{recursive:!0})}pathFor(e){return ue(this.baseDir,`${e}.md`)}get draftsDir(){return ue(this.baseDir,"_drafts")}draftPathFor(e){return ue(this.draftsDir,`${e}.md`)}parseFile(e){let t=na(e,"utf-8"),{meta:n,body:r}=ia(t),o=me.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:lt(this.baseDir,e)}:null}listDir(e){if(!fe(e))return[];let t=[];for(let n of sa(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(ue(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return fe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return fe(t)?this.parseFile(t):null}add(e,t){let n=me.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(fe(r))throw new Error(`Procedure already exists: ${n.id}`);return ut(r,gt(n)+`
89
+ `)}var je=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ue(process.cwd(),".agentx/procedures"),Gt(this.baseDir,{recursive:!0})}pathFor(e){return ue(this.baseDir,`${e}.md`)}get draftsDir(){return ue(this.baseDir,"_drafts")}draftPathFor(e){return ue(this.draftsDir,`${e}.md`)}parseFile(e){let t=sa(e,"utf-8"),{meta:n,body:r}=aa(t),o=me.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:lt(this.baseDir,e)}:null}listDir(e){if(!fe(e))return[];let t=[];for(let n of ra(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(ue(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return fe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return fe(t)?this.parseFile(t):null}add(e,t){let n=me.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(fe(r))throw new Error(`Procedure already exists: ${n.id}`);return ut(r,gt(n)+`
90
90
 
91
91
  `+t.trim()+`
92
92
  `),{meta:n,body:t.trim(),path:lt(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=me.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return ut(this.pathFor(e),gt(o)+`
@@ -98,15 +98,15 @@ Agent: ${t.slice(0,1e3)}`}],{model:ki,maxTokens:512})).content.trim().match(/\[[
98
98
  `),{meta:n,body:t.trim(),path:lt(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=me.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return ut(this.pathFor(e),gt(n)+`
99
99
 
100
100
  `+t.body+`
101
- `),oa(this.draftPathFor(e)),{meta:n,body:t.body,path:lt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!fe(t))throw new Error(`Draft not found: ${e}`);let n=ue(this.draftsDir,"_rejected");Gt(n,{recursive:!0}),ra(t,ue(n,`${e}.md`))}isRejected(e){return fe(ue(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as aa,mkdirSync as ca,readFileSync as da,writeFileSync as ua}from"fs";import{dirname as la,resolve as ga}from"path";import{z as Q}from"zod";var pa=Q.object({key:Q.string(),count:Q.number().int().min(0).default(0),firstSeen:Q.string(),lastSeen:Q.string(),taskIds:Q.array(Q.string()).default([]),sampleMessage:Q.string().default(""),status:Q.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:Q.string().optional()}),ha=Q.object({minedThrough:Q.string().optional(),candidates:Q.array(pa).default([])});function br(s){return ga(s,"_candidates.json")}function ma(s){let e=br(s);if(!aa(e))return{candidates:[]};try{let t=ha.safeParse(JSON.parse(da(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function fa(s,e){let t=br(s);ca(la(t),{recursive:!0}),ua(t,JSON.stringify(e,null,2)+`
102
- `)}function ya(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function ba(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function wa(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Jt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function wr(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function zt(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Jt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=wr(o,Jt(a.meta.trigger));d>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=wr(o,Jt(l));u>0&&c.push("title/tags");let p=Math.min(1,d*.7+u*.5);p>=r&&i.push({procedure:a,score:p,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Qt(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
101
+ `),ia(this.draftPathFor(e)),{meta:n,body:t.body,path:lt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!fe(t))throw new Error(`Draft not found: ${e}`);let n=ue(this.draftsDir,"_rejected");Gt(n,{recursive:!0}),oa(t,ue(n,`${e}.md`))}isRejected(e){return fe(ue(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as ca,mkdirSync as da,readFileSync as ua,writeFileSync as la}from"fs";import{dirname as ga,resolve as pa}from"path";import{z as Q}from"zod";var ha=Q.object({key:Q.string(),count:Q.number().int().min(0).default(0),firstSeen:Q.string(),lastSeen:Q.string(),taskIds:Q.array(Q.string()).default([]),sampleMessage:Q.string().default(""),status:Q.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:Q.string().optional()}),ma=Q.object({minedThrough:Q.string().optional(),candidates:Q.array(ha).default([])});function wr(s){return pa(s,"_candidates.json")}function fa(s){let e=wr(s);if(!ca(e))return{candidates:[]};try{let t=ma.safeParse(JSON.parse(ua(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function ya(s,e){let t=wr(s);da(ga(t),{recursive:!0}),la(t,JSON.stringify(e,null,2)+`
102
+ `)}function ba(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function wa(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function xa(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Jt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function xr(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function zt(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Jt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=xr(o,Jt(a.meta.trigger));d>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=xr(o,Jt(l));u>0&&c.push("title/tags");let p=Math.min(1,d*.7+u*.5);p>=r&&i.push({procedure:a,score:p,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Qt(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
103
103
  `)})].join(`
104
104
 
105
- `)}Pn();Tt();var Yt="turn-progress",xr={progress:Ye({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.")},Xt=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function Tr(s){return{agent:s.agent,request:Xt(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:Xt(e.input,300),...e.result!==void 0?{result:Xt(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Tt();var kr="turn-handoff",Ir="approval-binding",Sr={nextStep:Ye({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.")},vr={approves:Re("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."})},xa=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,Cr=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,Ta=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Vt(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Ta.test(e.split(`
106
- `).slice(-3).join(" ")):!1}var ka=/^\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 Ar(s){return s.trim().length<=160&&ka.test(s)}function $r(s){return s.trim().length<=160}function Mr(s){return{agent:s.agent,channel:s.channel,request:xa(s.request,1500),agentReplyEnding:Cr(s.reply,1200)}}function Pr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:Cr(s.previousReply,1200)}}var Ia=5*6e4,Sa=3,va=12,Ca=24*60*6e4,Rr=new Set(["cron","heartbeat","bench","a2a","business"]),Aa={observe(){},stop(){}};function _r(s){if(Mn(Yt)==="off")return Aa;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let p;for(let[y,b]of o)b>1&&(!p||b>p.times)&&(p={call:y,times:b});return p},l=p=>{if(c)return;c=!0,a=n.length;let y=Tr({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-va),repeated:d(),trigger:p});we(Yt,y,xr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{c=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Ia);return u.unref?.(),{observe(p){let y=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let b of y){if(b?.type!=="tool_use")continue;let x=b.input?JSON.stringify(b.input):"",w={tool:b.name||"tool",input:x};n.push(w),typeof b.id=="string"&&r.set(b.id,w);let I=`${w.tool}(${x})`,k=(o.get(I)??0)+1;o.set(I,k),k>=Sa&&!i.has(I)&&(i.add(I),l("repetition"))}else if(p?.type==="user")for(let b of y){if(b?.type!=="tool_result")continue;let x=r.get(b.tool_use_id);x&&(x.result=Array.isArray(b.content)?b.content.map(w=>typeof w?.text=="string"?w.text:"").join(""):typeof b.content=="string"?b.content:"",b.is_error&&(x.error=!0))}},stop(){clearInterval(u)}}}var Zt=new Map,Er=(s,e,t)=>`${s}\0${e}\0${t}`;function Dr(s){if(Rr.has(s.channel)||!Vt(s.reply))return;let e=Er(s.agent,s.channel,s.chatId);we(kr,Mr(s),Sr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&Zt.set(e,{callId:t.callId,at:Date.now()})})}function Or(s){if(Rr.has(s.channel))return;let e=Er(s.agent,s.channel,s.chatId),t=Zt.get(e);if(t){Zt.delete(e);let n=$n().store;if(n&&Date.now()-t.at<Ca)try{n.label(t.callId,"userReply",Ar(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!$r(s.message)||!Vt(s.previousReply)||we(Ir,Pr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),vr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function Nr(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(pt(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(c=>{a(),n(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function pt(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}function Lr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Wr;function Fu(s){Wr=s}function Hu(){return Wr}var Fr=64*1024,Ra=5*60*1e3,_a=3e4,Ea=300,Ae=".agentx/task-history",Da=30;function Be(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Oa(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 Na(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=Zn(s,e,ee().recent());return ts(t,n)}function La(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(`
105
+ `)}Rn();Tt();var Yt="turn-progress",Tr={progress:Ye({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.")},Xt=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function kr(s){return{agent:s.agent,request:Xt(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:Xt(e.input,300),...e.result!==void 0?{result:Xt(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Tt();var Ir="turn-handoff",Sr="approval-binding",vr={nextStep:Ye({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.")},Cr={approves:Pe("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."})},Ta=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,Ar=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,ka=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Vt(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:ka.test(e.split(`
106
+ `).slice(-3).join(" ")):!1}var Ia=/^\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 $r(s){return s.trim().length<=160&&Ia.test(s)}function Mr(s){return s.trim().length<=160}function Rr(s){return{agent:s.agent,channel:s.channel,request:Ta(s.request,1500),agentReplyEnding:Ar(s.reply,1200)}}function Pr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:Ar(s.previousReply,1200)}}var Sa=5*6e4,va=3,Ca=12,Aa=24*60*6e4,_r=new Set(["cron","heartbeat","bench","a2a","business"]),$a={observe(){},stop(){}};function Er(s){if(Mn(Yt)==="off")return $a;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let p;for(let[y,b]of o)b>1&&(!p||b>p.times)&&(p={call:y,times:b});return p},l=p=>{if(c)return;c=!0,a=n.length;let y=kr({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-Ca),repeated:d(),trigger:p});we(Yt,y,Tr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{c=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Sa);return u.unref?.(),{observe(p){let y=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let b of y){if(b?.type!=="tool_use")continue;let x=b.input?JSON.stringify(b.input):"",w={tool:b.name||"tool",input:x};n.push(w),typeof b.id=="string"&&r.set(b.id,w);let I=`${w.tool}(${x})`,k=(o.get(I)??0)+1;o.set(I,k),k>=va&&!i.has(I)&&(i.add(I),l("repetition"))}else if(p?.type==="user")for(let b of y){if(b?.type!=="tool_result")continue;let x=r.get(b.tool_use_id);x&&(x.result=Array.isArray(b.content)?b.content.map(w=>typeof w?.text=="string"?w.text:"").join(""):typeof b.content=="string"?b.content:"",b.is_error&&(x.error=!0))}},stop(){clearInterval(u)}}}var Zt=new Map,Dr=(s,e,t)=>`${s}\0${e}\0${t}`;function Or(s){if(_r.has(s.channel)||!Vt(s.reply))return;let e=Dr(s.agent,s.channel,s.chatId);we(Ir,Rr(s),vr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&Zt.set(e,{callId:t.callId,at:Date.now()})})}function Nr(s){if(_r.has(s.channel))return;let e=Dr(s.agent,s.channel,s.chatId),t=Zt.get(e);if(t){Zt.delete(e);let n=$n().store;if(n&&Date.now()-t.at<Aa)try{n.label(t.callId,"userReply",$r(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!Mr(s.message)||!Vt(s.previousReply)||we(Sr,Pr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),Cr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function Lr(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(pt(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(c=>{a(),n(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function pt(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}function Fr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Kr;function Bu(s){Kr=s}function Wu(){return Kr}var Hr=64*1024,_a=5*60*1e3,Ea=3e4,Da=300,Ae=".agentx/task-history",Oa=30;function Be(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Na(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 La(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=Zn(s,e,ee().recent());return ts(t,n)}function Fa(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
  `),c=process.argv[1]||"dist/cli.js",d=s.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
108
108
  node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","[End Institutional Wiki]"].join(`
109
- `)}var en=8*1024;function Hr(s){if(s.length<=en)return s;let e=s.length-en;return s.slice(0,en)+`\u2026[+${e}]`}function jr(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 Fa(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 Ur(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=ee();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?Hr(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Hr(a):null,at:r})}return}}function Ha(){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
109
+ `)}var en=8*1024;function Ha(s,e){if(s)try{is(s)}catch{}return e}function jr(s){if(s.length<=en)return s;let e=s.length-en;return s.slice(0,en)+`\u2026[+${e}]`}function Ur(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 ja(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 Br(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=ee();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?jr(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?jr(a):null,at:r})}return}}function Ua(){let s="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
110
110
  `;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
111
111
  `;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
112
112
  `;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
@@ -127,25 +127,25 @@ Agent: ${t.slice(0,1e3)}`}],{model:ki,maxTokens:512})).content.trim().match(/\[[
127
127
  \u2192 ${i}(${a})
128
128
  `}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Be(i,800)}
129
129
  `}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
130
- `:""}}var Br=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new qn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Wn;activeSouls=new Map;taskOutputs=new Map;taskAborts=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 it(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Un(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new dt,this.rateLimiter=new at,this.tokenTracker=new Ce,this.messageQueue=new ct,dr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Hn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new jn({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Bs(p.messages,e.message??""),c=Ws(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(is,cs(d),as,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!ds(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),ee().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-453FXKHQ.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let d=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",r,...d],source:{channel:r,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,r,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}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(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Jn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=oe(e.autonomy),i=o?null:ir().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let h=await i;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(S=>S.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="reminder"||c==="events"||o){let h=Date.now(),f=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(R=>setTimeout(R,S))}}else if(c==="voice"){let h=Date.now(),f=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(R=>setTimeout(R,500))}l=S,this.voiceClaims.add(S)}else{let h=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${S}) behind=${a.runningTasks.map(R=>R.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:`__queued__:${f}:${S}`}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(p),e.runningTaskId=p.id,e.onStart)try{e.onStart(p.id)}catch{}let y=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let x=h=>{if(h){b.buffer+=h,b.buffer.length>Fr&&(b.buffer=b.buffer.slice(b.buffer.length-Fr));for(let f of b.subscribers)try{f(h)}catch{}}},w=be();e.taskId=w;let I=new Map,k;if(t){let h=Ha();k=f=>{let S=h(f);if(S&&x(S),Ur(w,e.agentId,f),jr(I,f),r)try{r(f)}catch{}}}else k=h=>{if(Ur(w,e.agentId,h),jr(I,h),r)try{r(h)}catch{}};let _=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,A=_?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(_/1e3)}s`)),_):void 0;A?.unref?.();let v=(a.def.preSpawnTimeoutSec??Ea)*1e3,P=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(v/1e3)}s in step "${p.step??"start"}"`))},v);P.unref?.();let N=()=>{P&&clearTimeout(P),P=void 0},M=()=>`task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`,O;y.signal.addEventListener("abort",()=>{let h=pt(y.signal).message;/^timed out/.test(h)&&(O=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${h} ${M()}`)},{once:!0});let F=h=>{p.step=h,this.log(`[${e.agentId}] step ${h} ${M()}`)},D=(h,f,S=0)=>y.signal.aborted?Promise.reject(pt(y.signal)):(F(h),(h==="agent"||h==="workflow-auto-run")&&N(),Nr(f(),y.signal,S)),H=!1,C=h=>{if(H)return;H=!0,this.runReleases.delete(p.id),A&&clearTimeout(A),N(),a.activeTasks--;let f=a.runningTasks.findIndex(S=>S.id===p.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
130
+ `:""}}var Wr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new qn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Wn;activeSouls=new Map;taskOutputs=new Map;taskAborts=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 it(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Un(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new dt,this.rateLimiter=new at,this.tokenTracker=new Ce,this.messageQueue=new ct,ur({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Hn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new jn({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Ws(p.messages,e.message??""),c=Ks(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(as,ds(d),cs,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!us(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),ee().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-453FXKHQ.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let d=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",r,...d],source:{channel:r,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,r,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}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(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Jn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=oe(e.autonomy),i=o?null:ar().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let h=await i;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(S=>S.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="reminder"||c==="events"||o){let h=Date.now(),f=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let h=Date.now(),f=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let h=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:`__queued__:${f}:${S}`}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(p),e.runningTaskId=p.id,e.onStart)try{e.onStart(p.id)}catch{}let y=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let x=h=>{if(h){b.buffer+=h,b.buffer.length>Hr&&(b.buffer=b.buffer.slice(b.buffer.length-Hr));for(let f of b.subscribers)try{f(h)}catch{}}},w=be();e.taskId=w;let I=new Map,k;if(t){let h=Ua();k=f=>{let S=h(f);if(S&&x(S),Br(w,e.agentId,f),Ur(I,f),r)try{r(f)}catch{}}}else k=h=>{if(Br(w,e.agentId,h),Ur(I,h),r)try{r(h)}catch{}};let _=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,A=_?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(_/1e3)}s`)),_):void 0;A?.unref?.();let v=(a.def.preSpawnTimeoutSec??Da)*1e3,R=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(v/1e3)}s in step "${p.step??"start"}"`))},v);R.unref?.();let N=()=>{R&&clearTimeout(R),R=void 0},M=()=>`task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`,O;y.signal.addEventListener("abort",()=>{let h=pt(y.signal).message;/^timed out/.test(h)&&(O=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${h} ${M()}`)},{once:!0});let F=h=>{p.step=h,this.log(`[${e.agentId}] step ${h} ${M()}`)},D=(h,f,S=0)=>y.signal.aborted?Promise.reject(pt(y.signal)):(F(h),(h==="agent"||h==="workflow-auto-run")&&N(),Lr(f(),y.signal,S)),H=!1,C=h=>{if(H)return;H=!0,this.runReleases.delete(p.id),A&&clearTimeout(A),N(),a.activeTasks--;let f=a.runningTasks.findIndex(S=>S.id===p.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
132
132
  [task finished]
133
- `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),Ra).unref?.();try{let S=b.endedAt,R={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!h?.error,error:h?.error,...O?{status:"timeout",step:O}:{},responseText:h?.content||"",transcript:b.buffer};this.persistTaskRecord(R);let W=(R.responseText||R.error||"").trim();if(W){let J=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:J,at:S,ok:R.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let R of S){let W=R.originalContext||{channel:R.channel,sender:R.sender,chatId:R.chatId};this.execute({message:R.text,agentId:e.agentId,context:W}).then(J=>this.postQueuedResponseToChannel(e.agentId,W,J)).catch(J=>{this.log(`[${e.agentId}] queued message failed: ${J.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,C),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${M()}`);let g=e.context?.channel||"api",{evaluateRequest:T,selectRequestContext:E}=await import("./request-planner-PLBDCYKI.js"),L=await D("request-gate",()=>T(e.message,e.agentId,g));L.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let m=e.context?.chatId||e.context?.group||e.context?.sender||"default",X=e.context?.sender||"User",Z=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,m),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${m}`),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()})),e.freshSession||await D("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,g,m,e.seedHistory));let Kr=[...this.sessions.getSession(e.agentId,g,m).messages].reverse().find(h=>h.role==="agent")?.content;Or({agent:e.agentId,channel:g,chatId:m,message:e.message,previousReply:Kr,taskId:w}),this.sessions.addUserMessage(e.agentId,g,m,X,e.message);let tn=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:g,chatId:m,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(tn).toISOString(),taskId:w,resumeOrigin:Ys(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,nn=this.classifier;if(nn&&g!=="a2a"&&!Z)try{Y=await D("classify",()=>nn.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(h){this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`)}let $e=this.config.workflows?.matching,ye;if(this.config.workflows?.enabled&&$e?.enabled&&!o)try{let h=new ss({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=rs({agentId:e.agentId,channel:g,message:e.message,intentPath:Y?.path},h.list());f&&f.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${$e.mode} reasons=${f.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&f.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(h){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${h?.message||h}`)}let qr=this.wikiHub.getAgentWiki(e.agentId),sn=this.memoryStore.findRelevant(e.message,e.agentId,Z?3:8),rn=this.memoryStore.buildContext(sn),on=this.memoryStore.contextFacts(sn),Gr=this.patternStore.findRelevant(e.message,e.agentId,5),Jr=this.patternStore.buildContext(Gr),an="";if(!Z)try{let{loadLocalSkills:h,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),S=await D("skills",()=>h(a.def.workspace));an=f(S,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,m):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,m):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,m):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,m)&&(this.log(`[${e.agentId}] session stale for ${g}:${m}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,m)){let h=this.sessions.getLastTurnContextTokens(e.agentId,g,m);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${m} (last turn context: ${h} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"tier-2",lastTurnInputTokens:h,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,m)){let h=this.sessions.getTurnCount(e.agentId,g,m);this.log(`[${e.agentId}] max-turns rotation for ${g}:${m} (${h} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let h=j;await D("rotate",()=>this.maybeRotateForContinuity(e,a,g,m,h))&&(j=void 0)}try{let h=await D("compact",()=>this.sessions.compactIfNeeded(e.agentId,g,m,this.memoryStore));if(h.compacted){let f=h.qualityScore??"?",S=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${m} (quality: ${f}%, ${S} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let R=h.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${R.overallScore} (lexicon=${R.lexiconDecay}, tools=${R.toolShift}, semantic=${R.semanticDrift})`),R.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${R.lostWords.slice(0,5).join(", ")}`)}}}catch(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let zr=process.env.AGENTX_CONTEXT_SURGERY==="1",Qr=Z?{maxMessages:8,maxChars:2400}:zr&&Lr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Xr=!j&&!Z?La(qr,e.agentId):void 0,We=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,m,Qr),Yr=j?void 0:this.sessions.getRotationMemo(e.agentId,g,m)??void 0,cn,dn=[];if(this.config.procedures?.injection?.enabled&&!j&&!Z)try{let h=new je({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=zt(e.message,h.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){cn=Qt(f),dn=f.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of f)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(h){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${h?.message||h}`)}if(pe&&pe.cat)try{let f=this.sessions.getSession(e.agentId,g,m).messages,S=f[0],R=f[f.length-1],W=We===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${We.length}c/${We.split(`
134
- `).length}L`,J=`[${e.agentId}] ${g}:${m} ${W} | session.messages=${f.length}`+(f.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${R.timestamp.slice(11,19)}(${R.role}:${(R.content||"").slice(0,40).replace(/\n/g," ")})`:"");pe.cat("context",J)}catch(h){pe.cat("context",`[${e.agentId}] context-diag error: ${h?.message??h}`)}let un;if(a.def.contextReferences&&!j)try{let h=a.def.workspace,f=this.referencesCache.get(h);if(!f){let[R,W]=await D("references",()=>Promise.all([It(a.def.workspace),St(a.def.workspace)]));if(R.byId.size===0&&W.recipes.length===0){let[J,ge]=await D("references",()=>Promise.all([It(process.cwd()),St(process.cwd())]));f={refs:J,recipes:ge}}else f={refs:R,recipes:W};this.referencesCache.set(h,f)}let S=zn({agentId:e.agentId,intentTags:Y?.path,message:e.message},f.recipes,f.refs);S.cards.length>0&&(un=Gn(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(h){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${h?.message||h}`)}let ln=this.sessions.getCrossSessionSummary(e.agentId,g,m,e.message),gn,Ke=Us(e.message);if(Ke)try{let h=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:m,lookbackDays:Ke.lookbackDays,limit:12});if(h.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Ke.lookbackDays}d on this chat (cue-triggered)]`],S=[...h.turns].sort((R,W)=>R.ts.localeCompare(W.ts));for(let R of S){let W=R.ts.slice(11,16)+" "+R.day,J=R.role==="user"?R.senderName||"User":R.senderName||"Agent";f.push(`${W} ${J}: ${R.content}`)}h.hasMore&&f.push(`[\u2026${h.totalScanned-h.turns.length}+ older turns available \u2014 call /recall with before=${h.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),gn=f.join(`
135
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ke.lookbackDays}d, turns=${h.turns.length}, scanned=${h.totalScanned}`)}}catch(h){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${h.message}`)}let Vr=Z?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",pn,hn,mn=!1;if(Vr==="planner"&&!L.active&&g!=="voice"&&g!=="desktop"){try{let{planContext:h}=await import("./context-planner-LJT5IKH6.js"),f=await D("plan-context",()=>h({agentId:e.agentId,channel:g,chatId:m,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(mn=!0,pn=f.sessionHistory,rn=f.memoryContext,on=f.memoryFacts,ln=f.crossChatContext,hn=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(h){this.log(`[${e.agentId}] planner failed (non-fatal): ${h.message} \u2014 falling back to layered (keeping --resume for continuity)`)}mn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,g,m),j=void 0)}let ht=`${e.agentId}:${g}:${m}`,qe=Dn(e.message);qe&&(qe==="default"?(this.activeSouls.delete(ht),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(ht,qe),this.log(`[${e.agentId}] Soul switched to: ${qe}`)));let Zr=this.activeSouls.get(ht),eo=_n(a.def.workspace,Zr),to=En(eo),no=this.agentMemory.indexMarkdown(e.agentId),so=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
136
- 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.`:"",ro=a.def.richMessages!==!1&&(g==="telegram"||g==="whatsapp"||g==="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."].join(`
137
- `):"",fn="";if(a.def.workspace){let h=B(a.def.workspace,"CLAUDE.md");if(V(h))try{let f=Ue(h,"utf-8");fn=`[Project CLAUDE.md]
133
+ `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),_a).unref?.();try{let S=b.endedAt,P={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!h?.error,error:h?.error,...O?{status:"timeout",step:O}:{},responseText:h?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let J=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:J,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W}).then(J=>this.postQueuedResponseToChannel(e.agentId,W,J)).catch(J=>{this.log(`[${e.agentId}] queued message failed: ${J.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,C),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${M()}`);let g=e.context?.channel||"api",{evaluateRequest:T,selectRequestContext:E}=await import("./request-planner-PLBDCYKI.js"),L=await D("request-gate",()=>T(e.message,e.agentId,g));L.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let m=e.context?.chatId||e.context?.group||e.context?.sender||"default",X=e.context?.sender||"User",Z=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,m),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${m}`),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()})),e.freshSession||await D("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,g,m,e.seedHistory));let qr=[...this.sessions.getSession(e.agentId,g,m).messages].reverse().find(h=>h.role==="agent")?.content;Nr({agent:e.agentId,channel:g,chatId:m,message:e.message,previousReply:qr,taskId:w}),this.sessions.addUserMessage(e.agentId,g,m,X,e.message);let tn=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:g,chatId:m,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(tn).toISOString(),taskId:w,resumeOrigin:Vs(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,nn=this.classifier;if(nn&&g!=="a2a"&&!Z)try{Y=await D("classify",()=>nn.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(h){this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`)}let $e=this.config.workflows?.matching,ye;if(this.config.workflows?.enabled&&$e?.enabled&&!o)try{let h=new ss({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=rs({agentId:e.agentId,channel:g,message:e.message,intentPath:Y?.path},h.list());f&&f.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${$e.mode} reasons=${f.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&f.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(h){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${h?.message||h}`)}let Gr=this.wikiHub.getAgentWiki(e.agentId),sn=this.memoryStore.findRelevant(e.message,e.agentId,Z?3:8),rn=this.memoryStore.buildContext(sn),on=this.memoryStore.contextFacts(sn),Jr=this.patternStore.findRelevant(e.message,e.agentId,5),zr=this.patternStore.buildContext(Jr),an="";if(!Z)try{let{loadLocalSkills:h,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),S=await D("skills",()=>h(a.def.workspace));an=f(S,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,m):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,m):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,m):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,m)&&(this.log(`[${e.agentId}] session stale for ${g}:${m}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,m)){let h=this.sessions.getLastTurnContextTokens(e.agentId,g,m);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${m} (last turn context: ${h} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"tier-2",lastTurnInputTokens:h,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,m)){let h=this.sessions.getTurnCount(e.agentId,g,m);this.log(`[${e.agentId}] max-turns rotation for ${g}:${m} (${h} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let h=j;await D("rotate",()=>this.maybeRotateForContinuity(e,a,g,m,h))&&(j=void 0)}try{let h=await D("compact",()=>this.sessions.compactIfNeeded(e.agentId,g,m,this.memoryStore));if(h.compacted){let f=h.qualityScore??"?",S=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${m} (quality: ${f}%, ${S} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let P=h.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let Qr=process.env.AGENTX_CONTEXT_SURGERY==="1",Xr=Z?{maxMessages:8,maxChars:2400}:Qr&&Fr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Yr=!j&&!Z?Fa(Gr,e.agentId):void 0,We=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,m,Xr),Vr=j?void 0:this.sessions.getRotationMemo(e.agentId,g,m)??void 0,cn,dn=[];if(this.config.procedures?.injection?.enabled&&!j&&!Z)try{let h=new je({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=zt(e.message,h.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){cn=Qt(f),dn=f.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of f)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(h){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${h?.message||h}`)}if(pe&&pe.cat)try{let f=this.sessions.getSession(e.agentId,g,m).messages,S=f[0],P=f[f.length-1],W=We===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${We.length}c/${We.split(`
134
+ `).length}L`,J=`[${e.agentId}] ${g}:${m} ${W} | session.messages=${f.length}`+(f.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");pe.cat("context",J)}catch(h){pe.cat("context",`[${e.agentId}] context-diag error: ${h?.message??h}`)}let un;if(a.def.contextReferences&&!j)try{let h=a.def.workspace,f=this.referencesCache.get(h);if(!f){let[P,W]=await D("references",()=>Promise.all([It(a.def.workspace),St(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[J,ge]=await D("references",()=>Promise.all([It(process.cwd()),St(process.cwd())]));f={refs:J,recipes:ge}}else f={refs:P,recipes:W};this.referencesCache.set(h,f)}let S=zn({agentId:e.agentId,intentTags:Y?.path,message:e.message},f.recipes,f.refs);S.cards.length>0&&(un=Gn(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(h){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${h?.message||h}`)}let ln=this.sessions.getCrossSessionSummary(e.agentId,g,m,e.message),gn,Ke=Bs(e.message);if(Ke)try{let h=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:m,lookbackDays:Ke.lookbackDays,limit:12});if(h.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Ke.lookbackDays}d on this chat (cue-triggered)]`],S=[...h.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,J=P.role==="user"?P.senderName||"User":P.senderName||"Agent";f.push(`${W} ${J}: ${P.content}`)}h.hasMore&&f.push(`[\u2026${h.totalScanned-h.turns.length}+ older turns available \u2014 call /recall with before=${h.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),gn=f.join(`
135
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ke.lookbackDays}d, turns=${h.turns.length}, scanned=${h.totalScanned}`)}}catch(h){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${h.message}`)}let Zr=Z?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",pn,hn,mn=!1;if(Zr==="planner"&&!L.active&&g!=="voice"&&g!=="desktop"){try{let{planContext:h}=await import("./context-planner-LJT5IKH6.js"),f=await D("plan-context",()=>h({agentId:e.agentId,channel:g,chatId:m,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(mn=!0,pn=f.sessionHistory,rn=f.memoryContext,on=f.memoryFacts,ln=f.crossChatContext,hn=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(h){this.log(`[${e.agentId}] planner failed (non-fatal): ${h.message} \u2014 falling back to layered (keeping --resume for continuity)`)}mn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,g,m),j=void 0)}let ht=`${e.agentId}:${g}:${m}`,qe=Dn(e.message);qe&&(qe==="default"?(this.activeSouls.delete(ht),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(ht,qe),this.log(`[${e.agentId}] Soul switched to: ${qe}`)));let eo=this.activeSouls.get(ht),to=_n(a.def.workspace,eo),no=En(to),so=this.agentMemory.indexMarkdown(e.agentId),ro=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
136
+ 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.`:"",oo=Ba(a.def.richMessages,g),fn="";if(a.def.workspace){let h=B(a.def.workspace,"CLAUDE.md");if(V(h))try{let f=Ue(h,"utf-8");fn=`[Project CLAUDE.md]
138
137
  ${f.length>4e3?f.slice(0,4e3)+`
139
138
 
140
- [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Ge=e.context?.runbookPath,mt=[];if(Ge&&V(Ge)){let h=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,S=4e3,R=16e3;for(let W of h){if(f>=R)break;let J=B(Ge,W);if(V(J))try{let ge=Ue(J,"utf-8"),$=ge.length>S?ge.slice(0,S)+`
139
+ [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Ge=e.context?.runbookPath,mt=[];if(Ge&&V(Ge)){let h=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,S=4e3,P=16e3;for(let W of h){if(f>=P)break;let J=B(Ge,W);if(V(J))try{let ge=Ue(J,"utf-8"),$=ge.length>S?ge.slice(0,S)+`
141
140
 
142
141
  [${W} truncated to ${S} bytes]`:ge;mt.push(`[Project Runbook \u2014 ${W} from ${Ge}]
143
- ${$}`),f+=$.length}catch{}}}let oo=mt.length>0?mt.join(`
142
+ ${$}`),f+=$.length}catch{}}}let io=mt.length>0?mt.join(`
144
143
 
145
- `):"",ft=[a.def.systemPrompt||"",so,ro,fn,oo,to||"",no||""].filter(h=>h.trim().length>0).join(`
144
+ `):"",ft=[a.def.systemPrompt||"",ro,oo,fn,io,no||"",so||""].filter(h=>h.trim().length>0).join(`
146
145
 
147
- `)||void 0,yn={channel:g,chatId:m,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:a.def.systemPrompt,sender:X,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:Z||Lr(g,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:Z?void 0:Jr||void 0,procedureContext:cn,references:un,skillInjection:an||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:pn??We,memoryContext:rn||void 0,crossChatContext:ln||void 0,longMemoryRecall:gn||void 0,wikiContext:Xr,handoverNote:this.buildHandoverNote(e.agentId,g,m),rotationMemo:Yr,eventDigest:j?void 0:Na(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:g==="app"&&!j?os: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},Je=L.active&&L.preprocess?await D("select-context",()=>E(yn)):{input:yn,excluded:[]};Je.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Je.excluded.join(", ")}`);let ze=Xs(Je.input,Z?{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),io=Bn(ze,{memory:on,procedures:dn,wikiContext:Je.input.wikiContext}),yt=(ze?.length??0)+(ft?.length??0)+(e.message?.length??0),Qe={history:ze?.length??0,sysPrompt:ft?.length??0,message:e.message?.length??0},bn=mr(e.agentId,g,m);fr(bn,yt,Qe);let wn=yr(bn);wn&&this.log(`[${e.agentId}] ${wn}`),yt>16e3&&this.log(`[${e.agentId}] large context for ${g}:${m}: ${yt} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let bt,xn=Rn(a.def.tier,this.config.decisions.routing);if(!e.model&&xn&&(!L.active||L.preprocess))try{let{routeTaskModel:h}=await import("./routing-POORZC7A.js"),f=await D("route-model",()=>h({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,m),cheapModel:xn}));f.downgraded&&(bt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let ao={...e,systemPromptAppend:ft,...bt?{model:bt}:{}},le,Tn=_r({agent:e.agentId,request:e.message,taskId:w,budgetMinutes:a.def.maxExecutionMinutes??20}),co=k;k=h=>{Tn.observe(h),co?.(h)};try{let h=this.workflowAutoRunner;if(ye&&h){let U=ye;try{let G=await D("workflow-auto-run",()=>h({workflowId:U.workflowId,agentId:e.agentId,channel:g,chatId:m,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:m,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${ye.workflowId} run=${G.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),le={content:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:G.runId,workflowMatchConfidence:ye.confidence}},le}catch(G){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${G?.message||G}`)}}if(a.def.tier==="claude-code"){F("dispatch-gate");let U=a.def.persistentProcess?tt():null,G=U!=null&&U.hasLive({agentId:e.agentId,channel:g,chatId:m}),re=!!j||G,te=[ar(re),pr(re)].find(Pe=>Pe&&Pe.abort);if(te){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${te.reason}`);let Pe={content:"",error:te.message,duration:0};if(!t){b.buffer=`[error] ${te.message}`;for(let uo of b.subscribers)try{uo(b.buffer)}catch{}}return le=Pe,Pe}lr();let Me=hr();Me&&this.log(`[${e.agentId}] ${Me}`)}let f=a.def.tier==="claude-code",S=f?t:(U,G)=>{U&&x(U),t&&t(U,G)},R=!1,W=f?n:U=>{U&&(R?x(U):(x(`\u{1F4AD} ${U}`),R=!0)),n&&n(U)},J=()=>{R&&(x(`
148
- `),R=!1)},ge=f?S:S?(U,G)=>{J(),S(U,G)}:void 0,$=await D("agent",()=>Fs(a.def,ao,this.providers,ge,ze,j,k,y.signal,W),_a);if(!$.error){let U=Fa(a.def.toolUseRequired,I);if(U){let G=Array.from(I.entries()).map(([re,Xe])=>`${re}=${Xe}`).join(", ")||"none";$.error=`tool_required_not_called: ${U} (invoked: ${G})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${G}`)}}le=$;let se=$.usage?zs($.usage):void 0;if(ee().emit("task:completed",{taskId:w,agentId:e.agentId,channel:g,chatId:m,durationMs:Date.now()-tn,error:$.error||void 0,inputTokens:se?.inputTokens,outputTokens:se?.outputTokens,cacheReadTokens:se?.cacheReadTokens,cacheCreateTokens:se?.cacheCreateTokens,tier2InputTokens:se?.tier2InputTokens,tier2OutputTokens:se?.tier2OutputTokens,tier2CacheReadTokens:se?.tier2CacheReadTokens,tier2CacheCreateTokens:se?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:L.arm,numTurns:$.numTurns,injectedContext:io,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let U=$.error?`[error] ${$.error}`:$.content;b.buffer=U;for(let G of b.subscribers)try{G(U)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,m,$.content),Dr({agent:e.agentId,channel:g,chatId:m,request:e.message,reply:$.content,taskId:w}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,m,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,g,m,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,g,m,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,g,m,$.usage,$.contextTokens),$.usage){let te=$.contextTokens,Me=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(te??Me)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${m}: context=${te??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}if(Ln({channel:g,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let te=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:te,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
146
+ `)||void 0,yn={channel:g,chatId:m,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:a.def.systemPrompt,sender:X,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:Z||Fr(g,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:Z?void 0:zr||void 0,procedureContext:cn,references:un,skillInjection:an||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:pn??We,memoryContext:rn||void 0,crossChatContext:ln||void 0,longMemoryRecall:gn||void 0,wikiContext:Yr,handoverNote:this.buildHandoverNote(e.agentId,g,m),rotationMemo:Vr,eventDigest:j?void 0:La(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let h=os(g,!j,a.def.richMessages);return h?Ha(a.def.workspace,h):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},Je=L.active&&L.preprocess?await D("select-context",()=>E(yn)):{input:yn,excluded:[]};Je.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Je.excluded.join(", ")}`);let ze=Ys(Je.input,Z?{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),ao=Bn(ze,{memory:on,procedures:dn,wikiContext:Je.input.wikiContext}),yt=(ze?.length??0)+(ft?.length??0)+(e.message?.length??0),Qe={history:ze?.length??0,sysPrompt:ft?.length??0,message:e.message?.length??0},bn=fr(e.agentId,g,m);yr(bn,yt,Qe);let wn=br(bn);wn&&this.log(`[${e.agentId}] ${wn}`),yt>16e3&&this.log(`[${e.agentId}] large context for ${g}:${m}: ${yt} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let bt,xn=Pn(a.def.tier,this.config.decisions.routing);if(!e.model&&xn&&(!L.active||L.preprocess))try{let{routeTaskModel:h}=await import("./routing-POORZC7A.js"),f=await D("route-model",()=>h({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,m),cheapModel:xn}));f.downgraded&&(bt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let co={...e,systemPromptAppend:ft,...bt?{model:bt}:{}},le,Tn=Er({agent:e.agentId,request:e.message,taskId:w,budgetMinutes:a.def.maxExecutionMinutes??20}),uo=k;k=h=>{Tn.observe(h),uo?.(h)};try{let h=this.workflowAutoRunner;if(ye&&h){let U=ye;try{let G=await D("workflow-auto-run",()=>h({workflowId:U.workflowId,agentId:e.agentId,channel:g,chatId:m,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:m,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${ye.workflowId} run=${G.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),le={content:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:G.runId,workflowMatchConfidence:ye.confidence}},le}catch(G){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${G?.message||G}`)}}if(a.def.tier==="claude-code"){F("dispatch-gate");let U=a.def.persistentProcess?tt():null,G=U!=null&&U.hasLive({agentId:e.agentId,channel:g,chatId:m}),re=!!j||G,te=[cr(re),hr(re)].find(Re=>Re&&Re.abort);if(te){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${te.reason}`);let Re={content:"",error:te.message,duration:0};if(!t){b.buffer=`[error] ${te.message}`;for(let lo of b.subscribers)try{lo(b.buffer)}catch{}}return le=Re,Re}gr();let Me=mr();Me&&this.log(`[${e.agentId}] ${Me}`)}let f=a.def.tier==="claude-code",S=f?t:(U,G)=>{U&&x(U),t&&t(U,G)},P=!1,W=f?n:U=>{U&&(P?x(U):(x(`\u{1F4AD} ${U}`),P=!0)),n&&n(U)},J=()=>{P&&(x(`
147
+ `),P=!1)},ge=f?S:S?(U,G)=>{J(),S(U,G)}:void 0,$=await D("agent",()=>Hs(a.def,co,this.providers,ge,ze,j,k,y.signal,W),Ea);if(!$.error){let U=ja(a.def.toolUseRequired,I);if(U){let G=Array.from(I.entries()).map(([re,Xe])=>`${re}=${Xe}`).join(", ")||"none";$.error=`tool_required_not_called: ${U} (invoked: ${G})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${G}`)}}le=$;let se=$.usage?Qs($.usage):void 0;if(ee().emit("task:completed",{taskId:w,agentId:e.agentId,channel:g,chatId:m,durationMs:Date.now()-tn,error:$.error||void 0,inputTokens:se?.inputTokens,outputTokens:se?.outputTokens,cacheReadTokens:se?.cacheReadTokens,cacheCreateTokens:se?.cacheCreateTokens,tier2InputTokens:se?.tier2InputTokens,tier2OutputTokens:se?.tier2OutputTokens,tier2CacheReadTokens:se?.tier2CacheReadTokens,tier2CacheCreateTokens:se?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:L.arm,numTurns:$.numTurns,injectedContext:ao,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let U=$.error?`[error] ${$.error}`:$.content;b.buffer=U;for(let G of b.subscribers)try{G(U)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,m,$.content),Or({agent:e.agentId,channel:g,chatId:m,request:e.message,reply:$.content,taskId:w}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,m,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,g,m,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,g,m,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,g,m,$.usage,$.contextTokens),$.usage){let te=$.contextTokens,Me=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(te??Me)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${m}: context=${te??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}if(Ln({channel:g,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let te=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:te,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
149
148
 
150
- Agent: ${$.content}`,meta:Oa(Y,e.context)})}catch{}Fn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),tr(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=Ze(h.message);return le={content:"",error:et(f),errorKind:f.kind},le}finally{Tn.stop(),C(le)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;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=B(process.cwd(),Ae,this.safe(e.agentId),t);V(n)||$a(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Pa(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=B(process.cwd(),Ae,this.safe(e));if(!V(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"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=Da){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Ma(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(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=B(n,i),c;try{c=ne(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ns();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}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}}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,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,c=i.chatId;return new Promise(d=>{let l=!1,u=p=>{l||(l=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,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}};export{us as a,ls as b,Va as c,ps as d,Ao as e,hs as f,ys as g,uc as h,hc as i,mc as j,Bo as k,Os as l,Jo as m,zo as n,Qo as o,Fs as p,it as q,at as r,Kc as s,Bt as t,ee as u,nr as v,Ai as w,Ri as x,or as y,ad as z,ir as A,je as B,ma as C,fa as D,ya as E,ba as F,wa as G,zt as H,Fu as I,Hu as J,Oa as K,Na as L,La as M,en as N,Hr as O,jr as P,Fa as Q,Ur as R,Br as S};
151
- //# sourceMappingURL=chunk-VUB6XYWD.js.map
149
+ Agent: ${$.content}`,meta:Na(Y,e.context)})}catch{}Fn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),nr(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=Ze(h.message);return le={content:"",error:et(f),errorKind:f.kind},le}finally{Tn.stop(),C(le)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;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=B(process.cwd(),Ae,this.safe(e.agentId),t);V(n)||Ma(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Pa(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=B(process.cwd(),Ae,this.safe(e));if(!V(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"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=Oa){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Ra(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(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=B(n,i),c;try{c=ne(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ns();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}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}}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,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,c=i.chatId;return new Promise(d=>{let l=!1,u=p=>{l||(l=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,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 Ba(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(`
150
+ `)}export{ls as a,gs as b,tc as c,hs as d,$o as e,ms as f,bs as g,pc as h,yc as i,bc as j,Wo as k,Ns as l,zo as m,Qo as n,Xo as o,Hs as p,it as q,at as r,Jc as s,Bt as t,ee as u,sr as v,$i as w,_i as x,ir as y,ud as z,ar as A,je as B,fa as C,ya as D,ba as E,wa as F,xa as G,zt as H,Bu as I,Wu as J,Na as K,La as L,Fa as M,en as N,jr as O,Ur as P,ja as Q,Br as R,Wr as S,Ba as T};
151
+ //# sourceMappingURL=chunk-OTTAKMGC.js.map