agentix-cli 0.44.1 → 0.45.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 (35) hide show
  1. package/apps/mac-helper/Resources/AppIcon.png +0 -0
  2. package/dist/{agent-3XDPLWMX.js → agent-BCZRXLZ6.js} +2 -2
  3. package/dist/{board-dashboard-B5FMUMGA.js → board-dashboard-U5YP4HWE.js} +3 -1
  4. package/dist/{board-dashboard-B5FMUMGA.js.map → board-dashboard-U5YP4HWE.js.map} +1 -1
  5. package/dist/{chunk-ZQOGAUQS.js → chunk-3RCFDI52.js} +200 -171
  6. package/dist/chunk-3RCFDI52.js.map +1 -0
  7. package/dist/chunk-CQR6C5FU.js +23 -0
  8. package/dist/chunk-CQR6C5FU.js.map +1 -0
  9. package/dist/{chunk-BTGPZ6B7.js → chunk-CQRSSVWG.js} +2 -2
  10. package/dist/{chunk-3TL5EIVN.js → chunk-DYSVG6T3.js} +141 -141
  11. package/dist/{chunk-3TL5EIVN.js.map → chunk-DYSVG6T3.js.map} +1 -1
  12. package/dist/chunk-Z7LNSHG3.js +182 -0
  13. package/dist/chunk-Z7LNSHG3.js.map +1 -0
  14. package/dist/cli.js +1 -1
  15. package/dist/compaction-QXU3A4LQ.js +28 -0
  16. package/dist/compaction-QXU3A4LQ.js.map +1 -0
  17. package/dist/index.d.ts +99 -14
  18. package/dist/index.js +1 -1
  19. package/dist/memory-extract-3TO7UC5B.js +2 -0
  20. package/dist/{program-JLCKBO2A.js → program-4RO4NCBU.js} +2 -2
  21. package/dist/{registry-5QOY65FS.js → registry-OUJ6HT5D.js} +2 -2
  22. package/package.json +1 -1
  23. package/dist/chunk-77OV7346.js +0 -23
  24. package/dist/chunk-77OV7346.js.map +0 -1
  25. package/dist/chunk-T76YTN34.js +0 -178
  26. package/dist/chunk-T76YTN34.js.map +0 -1
  27. package/dist/chunk-ZQOGAUQS.js.map +0 -1
  28. package/dist/compaction-FD4R23HZ.js +0 -28
  29. package/dist/compaction-FD4R23HZ.js.map +0 -1
  30. package/dist/memory-extract-F5ZHWY5E.js +0 -2
  31. /package/dist/{agent-3XDPLWMX.js.map → agent-BCZRXLZ6.js.map} +0 -0
  32. /package/dist/{chunk-BTGPZ6B7.js.map → chunk-CQRSSVWG.js.map} +0 -0
  33. /package/dist/{memory-extract-F5ZHWY5E.js.map → memory-extract-3TO7UC5B.js.map} +0 -0
  34. /package/dist/{program-JLCKBO2A.js.map → program-4RO4NCBU.js.map} +0 -0
  35. /package/dist/{registry-5QOY65FS.js.map → registry-OUJ6HT5D.js.map} +0 -0
@@ -1,178 +0,0 @@
1
- import{a as Ln,g as Wn,m as Bn}from"./chunk-TCJ3SMOF.js";import{a as vt}from"./chunk-QLTM3F7M.js";import{b as Hn}from"./chunk-BIFJSQB5.js";import{a as Ct,b as Fn}from"./chunk-WPMX3VGI.js";import{a as At,b as jn}from"./chunk-K33GIBSE.js";import{a as Un}from"./chunk-W4YR2RO2.js";import{a as An}from"./chunk-ICZPZYYR.js";import{a as $n,b as Mn,c as Rn,d as Pn,f as _n}from"./chunk-DWADWDMU.js";import{a as Dn}from"./chunk-77OV7346.js";import{b as En,c as On,f as Nn}from"./chunk-MTVRYTLL.js";import{a as Xe,c as Me}from"./chunk-2GIDVZ4H.js";import{q as Sn,t as vn,v as ye,w as Cn}from"./chunk-6HMZ5TTM.js";import{a as $e,b as Ye,f as St}from"./chunk-F4HZTZHW.js";import{a as fe,b as kt}from"./chunk-ZTEU5JVQ.js";import{c as Qe,d as ze}from"./chunk-QOYAX2FT.js";import{e as le}from"./chunk-DSYKYZMT.js";import{d as Tn,e as re,f as kn,g as In,h as It}from"./chunk-QJANPP4C.js";Cn();St();var Kn="session-continuity",qn={continues:$e("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:$e("Does the new request refer to something stated earlier in the conversation?")};function Gn(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:$t(s.message,1200),previousRequest:s.previousMessage?$t(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>$t(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Jn(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function $t(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as Wr,execFile as Br}from"node:child_process";import{createHash as Kr,randomBytes as qr}from"node:crypto";import{createInterface as Gr}from"node:readline";import{promisify as Jr}from"node:util";var Qr=Jr(Br),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Mt=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=Qr("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 oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Kr("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 oe("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(([,h])=>!h.busy);if(!p)throw new oe("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:qr(32).toString("hex")},l=Wr("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,h)=>{let w=Gr({input:l.stdout}),T=()=>g(new oe("OpenCode server failed before dispatch",!0)),x=()=>g(new Error("task cancelled by operator")),I=setTimeout(T,15e3),g=_=>{clearTimeout(I),l.removeListener("exit",T),l.removeListener("error",T),e.signal?.removeEventListener("abort",x),w.close(),l.stdout.resume(),_?h(_):p()};l.once("exit",T),l.once("error",T),e.signal?.addEventListener("abort",x,{once:!0}),w.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,g()}catch{}}),e.signal?.aborted&&x()})}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()))}}}},Qn=new Mt;import{execa as st}from"execa";import{spawn as zr}from"node:child_process";import{createHash as Yr}from"node:crypto";import{createInterface as Xr}from"node:readline";var ie=class extends Error{},Vr=s=>zr("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Rt=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(),Xr({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()}},Pt=class{constructor(e=Vr,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=Yr("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[I])=>x.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ie("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 x=[...this.entries].find(([,I])=>!I.connection.busy);if(!x)throw new ie("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:n,connection:new Rt(e,this.launchProcess)}}catch{throw new ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,p=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let w=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={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",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let g=new Promise((_,A)=>{i.failTurn=A,i.notify=(S,y)=>{if(y?.threadId!==l)return;let E=y.item,C={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...y,type:S.replace("/","."),...E?{item:{...E,type:C[E.type]||E.type}}:{}}),S==="item/completed"&&E?.type==="agentMessage"&&E.phase==="final_answer"&&(d=E.text),S==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=y.delta,e.onDelta?.(y.delta,c)),S==="thread/tokenUsage/updated"){let O=y.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)}}S==="turn/completed"&&(y.turn.status==="completed"?_():A(new Error(y.turn.error?.message||`Codex turn ${y.turn.status}`)))}});return g.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await g,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new ie(x.message);return{content:c,codexSessionId:l,usage:u,error:x.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(w),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},zn=new Pt;import{execFile as po}from"child_process";import{StringDecoder as _e}from"string_decoder";import{mkdtempSync as ds,readFileSync as us,rmSync as ls}from"fs";import{join as tt}from"path";import{tmpdir as gs}from"os";function Ve(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 Ze(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Yn=null;function et(){return Yn}function wa(s){Yn=s}function Re(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var be=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Xn=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=Re(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 be(`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 be(`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=Re(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=Re(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Re(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=Re(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 Zr}from"child_process";import{existsSync as eo,readFileSync as to}from"fs";import{resolve as no}from"path";function so(s){let e=no(s,"CLAUDE.md");if(!eo(e))return null;try{let t=to(e,"utf8");return _n(t)}catch{return null}}var ro=20*60*1e3,oo=5e3,Pe=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Vn=class{constructor(e={}){this.opts=e}spawn(e,t){return new _t(e,t,this.opts)}},_t=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=Zr(r,o,{cwd:t.workspace,env:Me({...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:so(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??ro,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Pe(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)},oo);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
- `))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};It();import{resolve as Zn,join as es}from"path";kt();var io=4e3;function ts(s){try{let e=es(Zn(s.root),".agentx","db.sqlite"),t=vt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=fe(),r=s.input.command?s.input.command.slice(0,io):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
5
- (id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
6
- verdict, effective_action, mode, severity, approver, ms)
7
- VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
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 Pa(s){let e=es(Zn(s.root),".agentx","db.sqlite"),t=vt({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)}It();var ao=50,co=6*60*60*1e3,Dt=null,we=new Map;function Oa(s){Dt=s===null?null:String(s)}function uo(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 ss(s,e,t){if(!re(s))return{args:[]};if(!Dt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:uo(Dt,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 rs(s,e){return!re(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 lo(s){for(let[e,t]of we)s-t.at>co&&we.delete(e)}function go(s,e){let t=Date.now();lo(t);let n=we.get(s)??{at:t,blocks:[]};n.blocks.length<ao&&n.blocks.push(e),n.at=t,we.set(s,n)}function os(s){if(!s)return[];let e=we.get(s);return we.delete(s),e?.blocks??[]}function ns(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Na(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=Tn.safeParse(e.level),i=o.success?kn(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 ts({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&&go(e.taskId,l),{stdout:ns(`[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:ns(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}function q(s){let e=Ve(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:Ze(e),errorKind:e.kind}}function ps(){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 nt(){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 ce(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
- `))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
12
- `)}function hs(s,e,t,n,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let c=r||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Et(s,e){return!e||e.trim().length===0?s:`[System]
13
- ${e.trim()}
14
-
15
- [User]
16
- ${s}`}function ho(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(Et(e,n)),o}function mo(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 as(s){return JSON.stringify(s)}function ms(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${as(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(as).join(",")}]`]}function fs(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...ms()),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(Et(e,r)),a}function rt(s,e){let t=Xe(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(":"),Ot(t,e)}function Ot(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function fo(s,e){let t=rt(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 yo(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 ae(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Nt(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:ae(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ae(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ae(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ae(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Nt(n,e+1);if(r)return r}}function ys(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 Lt(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=Lt(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=Nt(a)||t,n=ys(a)||n,r=Lt(a)||r,o=bs(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function bs(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return cs(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return cs(e)}}}function cs(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 Ft(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 xo(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 To(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 ws(s,e,t,n,r){let o=Date.now(),i=ce(s,e,t),a=Ts(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=hs(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Ft(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:h,killed:w}=await new Promise(I=>{let g=Me(Ot(Xe(s.workspace),e),s.billing),_=!1,A=po("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...g,HOME:g.HOME||"/home/"+(g.USER||"user")}},(S,y,E)=>{I({stdout:y||"",stderr:E||"",exitCode:S?S.code??1:0,killed:_})});if(A.stdin?.end(),r){let S=()=>{_=!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?S():r.addEventListener("abort",S,{once:!0})}});if(w)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&h!==0){let I;return h===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.`:h==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?I=ps():I=p?.trim()||`Claude Code exited with code ${h}`,{content:"",...q(I),duration:Date.now()-o}}let T=xo(u);if(T)return{content:"",...q(T),duration:Date.now()-o};let x=To(u);return{content:x.text,duration:Date.now()-o,claudeSessionId:x.sessionId,usage:x.usage,numTurns:x.numTurns,billedModel:x.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function xs(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=ce(s,e,n),d=Ts(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let l=hs(s,c,!0,r,e.model,e.systemPromptAppend,d.args);Ft(e.agentId,s,e.model,r,"stream");let u="",p,h,w,T,x,I;try{let g=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=Me(Ot(Xe(s.workspace),e),s.billing),A=st("claude",l,{cwd:s.workspace,timeout:g,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"}),S=!1,y;if(i){let D=()=>{S=!0,y=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 E="",C=new _e("utf8");A.stdout&&A.stdout.on("data",D=>{E+=C.write(D);let L=E.split(`
19
- `);E=L.pop()||"";for(let v of L)if(v.trim())try{let b=JSON.parse(v);if(o)try{o(b)}catch{}if(b.type==="assistant"&&b.message?.usage){let k=b.message.usage,P=(k.input_tokens||0)+(k.cache_read_input_tokens||0)+(k.cache_creation_input_tokens||0);P>0&&(T=P)}if(b.type==="assistant"&&b.message?.content){for(let k of b.message.content)if(k.type==="text"&&k.text){let P=k.text.slice(u.length);P&&(u=k.text,t(P,u))}}if(b.type==="content_block_delta"&&b.delta?.text&&(u+=b.delta.text,t(b.delta.text,u)),b.type==="result"&&b.result){if(b.is_error&&typeof b.result=="string")I=b.result;else{let k=(typeof b.result=="string",b.result);if(typeof k=="string"&&k.length>u.length){let P=k.slice(u.length);u=k,P&&t(P,u)}}b.usage&&(h={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.model=="string"&&(p=b.model),typeof b.session_id=="string"&&(w=b.session_id),typeof b.num_turns=="number"&&(x=b.num_turns)}b.type==="system"&&b.subtype==="init"&&(typeof b.model=="string"&&(p=b.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${b.apiKeySource} version=${b.claude_code_version} model=${b.model} permMode=${b.permissionMode}
20
- `))}catch{v.trim()&&!v.startsWith("{")&&(u+=v+`
21
- `,t(v+`
22
- `,u))}});let O=await A,F=C.end();if(F&&(E+=F),S)return{content:"",error:y||"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:"",L=O,v;return L.timedOut?v=`Claude Code timed out after ${Math.round(g/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:L.signal?v=D.trim()||`Claude Code killed by signal ${L.signal}`:L.code==="ENOENT"||/ENOENT|spawn claude/i.test((L.shortMessage||"")+" "+D)?v=ps():v=D.trim()||`Claude Code exited with code ${L.exitCode??"unknown"}`,{content:"",...q(v),duration:Date.now()-a}}return I?{content:"",...q(I),duration:Date.now()-a,usage:h,contextTokens:T,numTurns:x,billedModel:p,claudeSessionId:w}:{content:u,duration:Date.now()-a,usage:h,contextTokens:T,numTurns:x,billedModel:p,claudeSessionId:w}}catch(g){return{content:u||"",...q(g.message),duration:Date.now()-a,usage:h,contextTokens:T,numTurns:x,billedModel:p,claudeSessionId:w}}}async function ko(s,e,t,n){let r=Date.now(),o=ce(s,e,t),i=ds(tt(gs(),"agentx-codex-")),a=tt(i,"last-message.txt"),c=fs(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await st("codex",c,{cwd:s.workspace,timeout:d,reject:!1,env:rt(s,e),extendEnv:!1,stdin:"ignore"}),u=bo(l.stdout);if(l.exitCode!==0||u.apiError){let h=l,w;return h.timedOut?w=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?w=u.apiError:h.signal?w=l.stderr.trim()||`Codex CLI killed by signal ${h.signal}`:h.code==="ENOENT"||/ENOENT|spawn codex/i.test((h.shortMessage||"")+" "+l.stderr)?w=nt():w=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${h.exitCode??"unknown"}`,{content:"",...q(w),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let p="";try{p=us(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||"")?nt():d?.message;return{content:"",...q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{ls(i,{recursive:!0,force:!0})}}async function Io(s,e,t,n,r,o){let i=Date.now(),a=ce(s,e,n),c=ds(tt(gs(),"agentx-codex-")),d=tt(c,"last-message.txt"),l=fs(s,a,!0,e.model,e.systemPromptAppend,d,r),u="",p,h,w,T;try{let x=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),I=st("codex",l,{cwd:s.workspace,timeout:x,reject:!1,env:rt(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let g="",_="",A=!1,S=new _e("utf8"),y=new _e("utf8"),E=Math.min(x,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),C,O=()=>{C&&clearTimeout(C),C=setTimeout(()=>{A=!0,I.kill("SIGTERM",{forceKillAfterTimeout:5e3})},E)};O(),I.stderr?.on("data",b=>{O(),_+=y.write(b),_.length>16e3&&(_=_.slice(-16e3))}),I.stdout?.on("data",b=>{O(),g+=S.write(b);let k=g.split(`
23
- `);g=k.pop()||"";for(let P of k)if(P.trim())try{let U=JSON.parse(P);if(o)try{o(U)}catch{}p=Nt(U)||p,h=ys(U)||h,w=Lt(U)||w,T=bs(U)||T;let R=yo(U);if(R&&R!==u){let z=R.startsWith(u)?R.slice(u.length):R;u=R.startsWith(u)?R:u+R,z&&t(z,u)}}catch{u+=P+`
24
- `,t(P+`
25
- `,u)}});let F=await I;C&&clearTimeout(C);let D=S.end();D&&(g+=D);let L=y.end();if(L&&(_+=L),F.exitCode!==0&&!u||T){let b=_||(typeof F.stderr=="string"?F.stderr:""),k=F,P;return A?P=`Codex CLI produced no output for ${Math.round(E/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.`:k.timedOut?P=`Codex CLI timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?P=T:k.signal?P=b.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+b)?P=nt():P=b.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...q(P),duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:w||r}}let v="";try{v=us(d,"utf8").trim()}catch{}if(v&&v!==u){let b=v.startsWith(u)?v.slice(u.length):v;u=v,b&&t(b,u)}return{content:u,duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:w||r}}catch(x){let I=/ENOENT|spawn codex/i.test(x?.message||"")?nt():x?.message;return{content:u,...q(I||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:w||r}}finally{ls(c,{recursive:!0,force:!0})}}async function So(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=ce(s,e,n),l=ho(s,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",p,h=e.freshSession?void 0:r,w,T,x=!0,I;try{let g=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=fo(s,e);if(s.persistentProcess)try{T=await Qn.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",T.url),_=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(b){if(!(b instanceof oe))throw b;b.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:b.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=st("opencode",l,{cwd:s.workspace,timeout:g,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let S=!1,y,E=()=>{T?.invalidate(),S=!0,y=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",E,{once:!0}),I=()=>i?.removeEventListener("abort",E),i?.aborted&&E();let C="",O="",F=new _e("utf8"),D=new _e("utf8"),L=b=>{if(b.trim())try{let k=JSON.parse(b);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(h=k.sessionID);let P=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;P&&(u||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),u+=P,t?.(P,u));let U=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;U&&a?.(U);let R=k.type==="step_finish"?k.part?.tokens:void 0;R&&(p={inputTokens:ae(R.input),outputTokens:ae(R.output),cacheReadTokens:ae(R.cache?.read),cacheCreateTokens:ae(R.cache?.write)}),w=mo(k)||w}catch{u+=b+`
26
- `,t?.(b+`
27
- `,u)}};A.stdout?.on("data",b=>{C+=F.write(b);let k=C.split(`
28
- `);C=k.pop()||"";for(let P of k)L(P)}),A.stderr?.on("data",b=>{O+=D.write(b)});let v=await A;if(i&&i.removeEventListener("abort",E),C+=F.end(),C.trim()&&L(C),O+=D.end(),S)return{content:"",error:y||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(v.exitCode!==0||w){let b=v,k;return b.timedOut?k=`OpenCode timed out after ${Math.round(g/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:w?k=w:b.code==="ENOENT"||/ENOENT|spawn opencode/i.test((b.shortMessage||"")+" "+O)?k=is():k=O.trim()||`OpenCode exited with code ${b.exitCode??"unknown"}`,{content:"",...q(k),duration:Date.now()-c,usage:p,opencodeSessionId:h}}return x=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:h}}catch(g){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(g?.message||"")?is():g?.message;return{content:u,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:h}}finally{I?.(),T?.release(x)}}async function vo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ce(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 Co(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,h=()=>{let x=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(x))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let w=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);w.unref?.();let T=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let x=s.provider||"claude-code",I=n?`${n}
29
-
30
- ${e.message}`:e.message,g=e.context?.sender,_=typeof g=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(g),A=e.context?.channel==="web-chat"&&_?{userId:g,agentId:e.agentId||"acme-public"}:void 0,S=Pn(s),y=Object.keys(S).length>0,E={task:I,cwd:s.workspace,provider:x,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:y?S:void 0};if(r){let{generateStream:L}=await import("./agent-3XDPLWMX.js"),v="",b,k,P,U;for await(let R of L(E)){if(c)try{c(R)}catch{}if(R.type==="text_delta")v+=R.text,r(R.text,v);else if(R.type==="thinking_delta")R.text&&i&&i(R.text);else if(R.type==="generate_result"){if(R.result.content&&R.result.content!==v){let z=R.result.content.slice(v.length);z?(v=R.result.content,r(z,v)):v=R.result.content}b=R.result.tokensUsed,R.result.inputTokens!=null&&(k=R.result.inputTokens),R.result.outputTokens!=null&&(P=R.result.outputTokens)}else if(R.type==="done"){if(R.result.content&&R.result.content!==v){let z=R.result.content.slice(v.length);z?(v=R.result.content,r(z,v)):v=R.result.content}R.result.tokensUsed!=null&&(b=R.result.tokensUsed)}else R.type==="error"&&(U=R.error)}return U&&!v?p?T():U==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${U}`),duration:Date.now()-d}:((k===void 0||P===void 0)&&b&&(k=Math.round(b*.7),P=b-k),{content:v||"Done.",tokensUsed:b,usage:k!==void 0||P!==void 0?{inputTokens:k||0,outputTokens:P||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:C}=await import("./agent-3XDPLWMX.js"),O=await C(E),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let L=O.tokensUsed;F=Math.round(L*.7),D=L-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(x){return p?T():x?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${x.message}`),duration:Date.now()-d}}finally{clearTimeout(w),a&&a.removeEventListener("abort",h)}}async function Ao(s,e,t,n,r,o,i){let a=et();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,h=!1;try{let v=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}),h=a.list().length>v}catch(v){return v instanceof be,null}h&&Ft(e.agentId,s,e.model,n,"persistent");let w=ce(s,e,t),T="",x,I,g,_,A,S,y,E="",C="",O=v=>{if(!i||!v)return;let b;if(C&&v.startsWith(C)?b=v.slice(C.length):b=E&&!E.endsWith(`
31
- `)?`
32
-
33
- ${v}`:v,C=v,!!b){E+=b;try{i(b,E)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let L=!1;try{let v=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let b of p.runTurn({message:w,taskId:e.taskId??"unknown",deadlineMs:v})){if(L=!0,r)try{r(b.raw)}catch{}if(b.type==="assistant"){let k=b.raw.message?.content??[];for(let U of k)U.type==="text"&&typeof U.text=="string"?(T=U.text,O(U.text)):U.type==="tool_use"&&(C="");let P=b.raw.message?.usage;if(P){let U=(P.input_tokens||0)+(P.cache_read_input_tokens||0)+(P.cache_creation_input_tokens||0);U>0&&(_=U)}}if(b.type==="result"){let k=b.raw;if(k.is_error){let P=q(typeof k.result=="string"?k.result:"claude error");x=P.error,I=P.errorKind}else typeof k.result=="string"&&k.result.length>0&&(T=k.result,E||O(k.result));typeof k.session_id=="string"&&(y=k.session_id),k.usage&&(g={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(A=k.num_turns),typeof k.message?.model=="string"?S=k.message.model:typeof k.model=="string"&&(S=k.model)}}}catch(v){if(F)x="task cancelled by operator",I="cancelled";else if(L)if(v instanceof Pe){let b=q(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);x=b.error,I=b.errorKind}else{let b=q(`persistent claude process error: ${v?.message||String(v)}`);x=b.error,I=b.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); 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&&!x&&(x="task cancelled by operator",I="cancelled"),{content:F?"":T,error:x,errorKind:I,duration:Date.now()-c,usage:g,contextTokens:_,numTurns:A,billedModel:S,claudeSessionId:y}}function Ts(s){return re(s.autonomy)?s.taskId?ss(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function $o(s,e,t,n,r,o,i){let a=e.autonomy,c=rs(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:`${In(a)}
34
-
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 xs(s,l,t,n,r,o,i):await ws(s,l,n,r,i),p=os(d);return{...u,autonomy:a,...p.length?{autonomyBlocks:p}:{}}}async function ks(s,e,t,n,r,o,i,a,c){if(re(e.autonomy))return $o(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let d=await Ao(s,e,r,o,i,a,n);if(d!==null)return d}return n?xs(s,e,n,r,o,i,a):ws(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let d=await zn.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:rt(s,e),args:ms(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Et(ce(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 ie))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Io(s,e,n,r,o,i):ko(s,e,r,o);case"opencode":return So(s,e,n,r,o,i,a,c);case"sdk":{let d=s.provider||"claude",l=t[d]?.apiKey;return l?vo(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 Co(s,e,u,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as xe,writeFileSync as Is,mkdirSync as Mo,existsSync as Ht,readdirSync as jt}from"fs";import{resolve as Te}from"path";var Ut=12e3,De=30,Ro=720,Po=40,_o=18e4,Do="[Compacted conversation summary",Eo=7*864e5,Oo=[/\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 No(s){return s?Oo.some(e=>e.test(s)):!1}var Lo=[{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 vs(s){if(!s)return null;let e=0;for(let t of Lo)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Ss(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 Cs(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 As(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 Fo(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 ot=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Te(e,".agentx/sessions"),Ht(this.sessionsDir)||Mo(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Ro),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Po),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??_o)}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:De,maxChars:Ut});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 Te(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(Ht(o))try{let d=JSON.parse(xe(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(!Ht(i))return null;try{return JSON.parse(xe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);Ss(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);Ss(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??De),a=Math.max(200,r.maxChars??Ut),c=[],d=0;for(let p=o.messages.length-1;p>=0&&c.length<i;p--){let h=o.messages[p];if(d+=h.content.length,c.push(h),d>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of c){let h=Fo(p.timestamp);h!==u&&(l.push(`\u2014 ${h} \u2014`),u=h);let w=p.name||(p.role==="user"?"User":"Agent");l.push(`${w}: ${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=jt(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 S=A.match(u);if(!S)return!1;let y=S[1];return y>=d&&y<=l}),h=[],w=0,T=e.query?.toLowerCase(),x=e.participants?.length?new Set(e.participants):void 0;for(let A of p){let S;try{S=JSON.parse(xe(Te(this.sessionsDir,A),"utf-8"))}catch{continue}if(S.agentId===e.agentId&&!(e.channel&&S.channel!==e.channel)&&!(e.chatId&&S.chatId!==e.chatId))for(let y of S.messages)w++,!(!y.timestamp||y.timestamp<o||y.timestamp>=i)&&(x&&y.role==="user"&&!x.has(y.name??"")||T&&!y.content.toLowerCase().includes(T)||h.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.content,channel:S.channel,chatId:S.chatId,day:S.day,sessionFile:A}))}h.sort((A,S)=>S.ts.localeCompare(A.ts));let I=h.slice(0,t),g=I.length>0?I[I.length-1].ts:null,_=h.length>t;return{turns:I,oldestTs:g,hasMore:_,totalScanned:w}}recentByChatId(e){let t=Math.min(Math.max(e.limit??De,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=jt(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(xe(Te(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let h of p.messages)!h.timestamp||h.timestamp<n||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.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!==""&&!No(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=jt(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(xe(Te(this.sessionsDir,d),"utf-8"));if(l.id===i||l.messages.length===0)continue;let u=l.messages.slice(-4),h=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,w=u.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${h} (${l.channel}):
38
- ${w.join(`
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-FD4R23HZ.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r);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(Do)}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 Te(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(xe(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()},Is(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>Eo?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>De&&(e.messages=e.messages.slice(-De));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Ut&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&le.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);Is(t,JSON.stringify(e,null,2))}catch{}}};var Ho=new Set(["cron","a2a","workflow","selftest"]),jo=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function $s(s){if(s.responseLength<=50)return{capture:!1,reason:"response too short"};let t=(s.channel??"").toLowerCase().split("@")[0];if(Ho.has(t))return{capture:!1,reason:`machine channel: ${t}`};let n=s.content.slice(0,400);for(let[r,o]of jo)if(r.test(n))return{capture:!1,reason:o};return{capture:!0}}var it=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 Ee,writeFileSync as Ms,appendFileSync as Uo,existsSync as ke,mkdirSync as Wo}from"fs";import{resolve as Ie}from"path";var Ps={"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}},_s=2e5,Bo=1.5;function Ko(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 Ds(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>_s?{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 Rs=500,qo=".agentx/pricing/custom.json",Se=class{dir;cache=null;pricing;constructor(e=Ie(process.cwd(),".agentx/usage")){this.dir=e,Wo(this.dir,{recursive:!0}),this.pricing=Go()}getPricing(){return this.pricing}static calculateCost(e,t,n=Ps){let r=Ko(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*Bo}cost(e,t){return Se.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,h=0,w=0,T=0,x=0,I=0,g=0,_=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>_s?(x=n.inputTokens,I=n.outputTokens,g=n.cacheReadTokens,_=n.cacheCreateTokens):(p=n.inputTokens,h=n.outputTokens,w=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),h=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=h,u.cacheReadTokens+=w,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+x,u.tier2OutputTokens=(u.tier2OutputTokens||0)+I,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+g,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+_,i&&u.errors++,u.byChannel||(u.byChannel={});let A=(c||"other").toLowerCase(),S=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};S.tasks++,S.totalDuration+=t,S.inputTokens+=p,S.outputTokens+=h,S.cacheReadTokens+=w,S.cacheCreateTokens+=T,S.tier2InputTokens+=x,S.tier2OutputTokens+=I,S.tier2CacheReadTokens+=g,S.tier2CacheCreateTokens+=_,i&&S.errors++,u.byChannel[A]=S,d&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(d)||(u.sessionKeys.push(d),u.sessionKeys.length>Rs&&u.sessionKeys.splice(0,u.sessionKeys.length-Rs))),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(ke(t))try{return this.cache=JSON.parse(Ee(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ke(t))return null;try{return JSON.parse(Ee(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={},h={},w={};for(let[T,x]of Object.entries(n.agents)){let I=this.cost(x);p[T]=I,r+=x.tasks,o+=(x.inputTokens||0)+(x.tier2InputTokens||0),i+=(x.outputTokens||0)+(x.tier2OutputTokens||0),a+=(x.cacheReadTokens||0)+(x.tier2CacheReadTokens||0),c+=(x.cacheCreateTokens||0)+(x.tier2CacheCreateTokens||0),d+=I,I>u&&(u=I,l=T);let g=x.sessionKeys?.length||0;h[T]={sessions:g,avgTasksPerSession:g>0?x.tasks/g:x.tasks};for(let[_,A]of Object.entries(x.byChannel||{})){let S=this.cost(A,x.model);w[_]=(w[_]||0)+S}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:h,byChannel:w}}appendToTokenCosts(e,t){let n=t||Ie(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} |`;ke(n)?Uo(n,c+`
41
- `):Ms(n,`# Token Costs
42
-
43
- Daily token cost tracking. Auto-appended at midnight, host time.
44
- Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
45
-
46
- | Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
47
- |------|-------|-------|--------|---------|---------|------|-----------|-------------|
48
- `+c+`
49
- `)}hasTokenCostsEntry(e,t){let n=t||Ie(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ke(n))return!1;try{let r=Ee(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Ie(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ke(t))return null;try{let r=Ee(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 w=0;w<e;w++){let T=new Date(Date.now()-w*864e5).toISOString().slice(0,10),x=this.getDate(T);if(x)for(let[I,g]of Object.entries(x.agents)){let _=this.cost(g);t+=g.tasks;let A=(g.inputTokens||0)+(g.tier2InputTokens||0),S=(g.outputTokens||0)+(g.tier2OutputTokens||0),y=(g.cacheReadTokens||0)+(g.tier2CacheReadTokens||0),E=(g.cacheCreateTokens||0)+(g.tier2CacheCreateTokens||0);n+=A,r+=S,o+=y,i+=E,a+=g.errors,c+=_;let C=d[I]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};C.tasks+=g.tasks,C.input+=A,C.output+=S,C.cacheRead+=y,C.cacheCreate+=E,C.total=C.input+C.output+C.cacheRead+C.cacheCreate,C.totalDuration+=g.totalDuration,C.avgDuration=C.totalDuration/C.tasks,C.cost+=_,C.sessions+=g.sessionKeys?.length||0,g.model&&(C.model=g.model),d[I]=C;for(let[O,F]of Object.entries(g.byChannel||{})){let D=this.cost(F,g.model),L=l[O]||{tasks:0,cost:0};L.tasks+=F.tasks,L.cost+=D,l[O]=L}}}let u=n+r+o+i,p=o+i>0?o/(o+i):0,h={};for(let[w,T]of Object.entries(d))h[w]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:c,byAgent:d,byChannel:l,sessionStats:h}}filePath(e){return Ie(this.dir,`${e}.json`)}save(e){try{Ms(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Go(){let s=JSON.parse(JSON.stringify(Ps));try{let e=Ie(process.cwd(),qo);if(!ke(e))return s;let t=JSON.parse(Ee(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 Jo={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}},Es=4;function Os(s,e=Jo){let t=Qo(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Es;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Es,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
-
51
- `)}function Qo(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(zo(s,t("channel",200))),n.push(Yo(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
- `)[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
- `);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=Xo(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
- `),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
- `),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.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function zo(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 Yo(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 Xo(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}import{readFileSync as Vo,writeFileSync as Ns,appendFileSync as Zo,mkdirSync as ei,existsSync as Ls}from"fs";import{resolve as Wt}from"path";var Fs=200,ti=7,at=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=Wt(e,".agentx/memory"),Ls(this.memoryDir)||ei(this.memoryDir,{recursive:!0})}filePath(e){return Wt(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};Zo(this.filePath(e),JSON.stringify(n)+`
60
- `)}getAll(e){let t=this.filePath(e);if(!Ls(t))return[];try{return Vo(t,"utf-8").split(`
61
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return[]}}findRelevant(e,t,n=8){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(h=>`${h.keywords.join(" ")} ${h.content}`),i=Wt(this.memoryDir,`${t}_bm25_cache.json`),a=ze(o,i),c=Qe(e,a),d=new Map(c.map(h=>[h.docIndex,h.score])),u=r.map((h,w)=>{let T=d.get(w)??0;return h.category==="secret"&&(T+=2),h.category==="commitment"&&(T+=1),{memory:h,score:T}}).filter(h=>h.score>0);if(u.length===0)return r.slice(-n);let p=u.sort((h,w)=>w.score-h.score).slice(0,n).map(h=>h.memory);if(p.length>0)try{this.recordAccess(t,p.map(h=>h.id))}catch{}return p}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],n=t[0].length;for(let r of e){let i=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,a=`- [${r.category}] ${r.content} (${i}, ${r.source.date})`;if(n+a.length>2400)break;t.push(a),n+=a.length}return t.push("[End Memory]"),t.join(`
62
- `)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)if(r.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),o=!0}o&&Ns(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
63
- `)+`
64
- `)}getDueForReview(e,t=5){let n=this.getAll(e),r=Date.now();return n.filter(o=>o.category==="task-state"?!1:o.nextReview?new Date(o.nextReview).getTime()<=r:!0).sort((o,i)=>!o.nextReview&&i.nextReview?-1:o.nextReview&&!i.nextReview?1:o.nextReview&&i.nextReview?new Date(o.nextReview).getTime()-new Date(i.nextReview).getTime():(o.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let r of t){let o=Math.round((Date.now()-new Date(r.createdAt).getTime())/864e5);n.push(`- [${r.category}] ${r.content} (${o}d old, accessed ${r.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
65
- `)}hasSimilar(e,t){let n=this.getAll(e),o=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let a=i.content.toLowerCase();return o.filter(d=>a.includes(d)).length>=o.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),r=ti*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>n:i.category==="task-state"&&!i.expiresAt?n-new Date(i.createdAt).getTime()<r:!0),t.length>Fs&&(t=t.slice(-Fs));let o=this.filePath(e);Ns(o,t.map(i=>JSON.stringify(i)).join(`
66
- `)+`
67
- `)}};import{existsSync as Oe,mkdirSync as ni,readdirSync as si,readFileSync as ri,unlinkSync as Bt,writeFileSync as ct}from"fs";import{resolve as de}from"path";var ge=["user","feedback","project","reference"],dt=class{baseDir;constructor(e={}){let t=e.baseDir??de(process.cwd(),".agentx");this.baseDir=de(t,"agent-memory")}dirFor(e){let t=qt(e),n=de(this.baseDir,t);return ni(n,{recursive:!0}),n}fileFor(e,t,n){return de(this.dirFor(e),`${t}_${qt(n)}.md`)}indexPath(e){return de(this.dirFor(e),"MEMORY.md")}save(e){if(!ge.includes(e.type))throw new Error(`invalid memory type: ${e.type}`);if(!e.name.trim())throw new Error("memory name is required");if(!e.description.trim())throw new Error("memory description is required");let t=this.fileFor(e.agentId,e.type,e.name),n=new Date().toISOString(),r=n,o=Ne(t);if(o){let a=Kt(o);a&&(r=a.createdAt)}let i={name:qt(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:r,updatedAt:n};return ct(t,oi(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of ge){let r=this.fileFor(e,n,t);if(!Oe(r))continue;let o=Kt(Ne(r)??"");if(o)return o}return null}list(e){let t=this.dirFor(e);if(!Oe(t))return[];let n=[];for(let r of si(t,{withFileTypes:!0})){if(!r.isFile()||!r.name.endsWith(".md")||r.name==="MEMORY.md")continue;let o=Kt(Ne(de(t,r.name))??"");o&&n.push(o)}return n.sort((r,o)=>{let i=ge.indexOf(r.type),a=ge.indexOf(o.type);return i!==a?i-a:r.name.localeCompare(o.name)})}remove(e,t){let n=!1;for(let r of ge){let o=this.fileFor(e,r,t);Oe(o)&&(Bt(o),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return Ne(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),r=de(t,".agentx-memory.md");n?ct(r,n+`
68
- `):Oe(r)&&Bt(r);let o=de(t,"CLAUDE.md"),i="<!-- AGENTX-MEMORY-START \u2014 auto-managed by agentx; edit via `agentx memory` -->",a="<!-- AGENTX-MEMORY-END -->",c=n?`${i}
69
- ${n}
70
- ${a}`:"",d=Ne(o)??"",l=d.indexOf(i),u=d.indexOf(a),p;if(l>=0&&u>l){let h=d.slice(0,l).replace(/\n+$/,""),w=d.slice(u+a.length).replace(/^\n+/,"");p=c?[h,c,w].filter(Boolean).join(`
71
-
72
- `)+`
73
- `:[h,w].filter(Boolean).join(`
74
-
75
- `)+(h||w?`
76
- `:"")}else if(c)p=d?d.replace(/\n+$/,"")+`
77
-
78
- `+c+`
79
- `:c+`
80
- `;else return;ct(o,p)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);Oe(o)&&Bt(o);return}let n={user:[],feedback:[],project:[],reference:[]};for(let o of t)n[o.type].push(o);let r=[];r.push(`# Memory \u2014 ${e}`,""),r.push("This is the agent's experiential memory: user preferences,"),r.push("feedback, project-specific context, and external references."),r.push("Updated via `agentx memory` CLI or by the agent itself.");for(let o of ge){let i=n[o];if(i.length){r.push("",`## ${ci(o)}`,"");for(let a of i)r.push(`- **${a.name}** \u2014 ${a.description} _(updated ${a.updatedAt.slice(0,10)})_`)}}r.push(""),ct(this.indexPath(e),r.join(`
81
- `))}};function oi(s){return["---",`name: ${s.name}`,`description: ${ii(s.description)}`,`type: ${s.type}`,`created: ${s.createdAt}`,`updated: ${s.updatedAt}`,"---",""].join(`
82
- `)+s.body+`
83
- `}function Kt(s){if(!s.startsWith(`---
84
- `))return null;let e=s.indexOf(`
85
- ---
86
- `,4);if(e<0)return null;let t=s.slice(4,e),n=s.slice(e+5).replace(/^\n+/,"").trimEnd(),r={};for(let o of t.split(`
87
- `)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=ai(o.slice(i+1).trim());r[a]=c}return!r.name||!r.type||!r.description||!ge.includes(r.type)?null:{name:r.name,type:r.type,description:r.description,body:n,createdAt:r.created??"",updatedAt:r.updated??r.created??""}}function ii(s){return/[:#\n]/.test(s)?`"${s.replace(/"/g,'\\"')}"`:s}function ai(s){return s.startsWith('"')&&s.endsWith('"')&&s.length>=2?s.slice(1,-1).replace(/\\"/g,'"'):s}function qt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function ci(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Ne(s){try{return ri(s,"utf-8")}catch{return null}}var ut=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(`
88
- `),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 di,writeFileSync as Hs,appendFileSync as ui,mkdirSync as li,existsSync as js}from"fs";import{resolve as Gt}from"path";var Us=50,gi="claude-haiku-4-20250514",pi=`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.
89
-
90
- Extract patterns like:
91
- - "When asked about X, the approach that works is Y"
92
- - "User prefers Z style of communication"
93
- - "For deployment tasks, always check A before doing B"
94
- - "This codebase uses pattern X, so generate code following X"
95
-
96
- SKIP:
97
- - Factual information (names, dates, URLs)
98
- - Routine task completions
99
- - Greetings or small talk
100
-
101
- Output a JSON array:
102
- [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
103
-
104
- If nothing worth extracting, output: []`,lt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Gt(e,".agentx/patterns"),js(this.patternsDir)||li(this.patternsDir,{recursive:!0})}filePath(e){return Gt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!js(t))return[];try{return di(t,"utf-8").split(`
105
- `).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()};ui(this.filePath(e),JSON.stringify(n)+`
106
- `)}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=Gt(this.patternsDir,`${t}_bm25_cache.json`),a=ze(o,i),d=Qe(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(`
107
- `)}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&&Hs(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
108
- `)+`
109
- `)}prune(e){let t=this.getAll(e);t.length<=Us||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,Us),Hs(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
110
- `)+`
111
- `))}};async function Ws(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-KO2DODIO.js"),c=(await o("claude").generate([{role:"system",content:pi},{role:"user",content:`User: ${e.slice(0,500)}
112
-
113
- Agent: ${t.slice(0,1e3)}`}],{model:gi,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 hi}from"events";var Qt=class{inner=new hi;constructor(){this.inner.setMaxListeners(50)}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){return this.inner.emit(e,t)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this}},Jt;function te(){return Jt||(Jt=new Qt),Jt}kt();kt();var Bs=["manual","notify","auto"];function mi(s){return typeof s=="string"&&Bs.includes(s)}var zt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Le=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...zt,...e}}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={sessionId:e,cwd:t.cwd??"",agentIds:[],mode:"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return this.sessions.set(e,o),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n&&(n.lastSeenAt=t),n}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));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],n}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now()){this.sessions.delete(e);for(let n of this.items.values())n.sessionId===e&&(n.state==="pending"||n.state==="claimed")&&this.settle(n,"expired",t,"session ended")}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:fe(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:fi(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)}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 fi(s,e){return s.length<=e?s:`${s.slice(0,e)}
114
- \u2026[truncated ${s.length-e} chars]`}var Yt;function Ks(){return Yt||(Yt=new Le),Yt}It();import{readFileSync as yi}from"fs";import{homedir as bi}from"os";import{join as wi}from"path";var Fe=null,xi=6e4;function Ti(){try{let s=wi(bi(),".claude.json"),e=yi(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function ki(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 Ii(s=!1){let e=Date.now();return!s&&Fe&&e-Fe.checkedAt<xi||(Fe=ki(Ti(),e)),Fe}function qs(s){let e=Ii();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 Gs={warnRatio:.8},G={...Gs},Si=5*60*60*1e3,vi=60*60*1e3,pe=[];function Js(s){G={...Gs,...s||{}}}function Qs(s){let e=s-Si,t=0;for(;t<pe.length&&pe[t]<e;)t++;t>0&&pe.splice(0,t)}function zs(s=Date.now()){Qs(s),pe.push(s)}function Ys(s=Date.now()){Qs(s);let e=s-vi,t=0;for(let o=pe.length-1;o>=0&&pe[o]>=e;o--)t++;let n=pe.length,r={lastHour:t,last5h:n,maxPerHour:G.maxPerHour,maxPer5h:G.maxPer5h};return G.maxPerHour&&G.maxPerHour>0&&(r.hourlyRatio=t/G.maxPerHour),G.maxPer5h&&G.maxPer5h>0&&(r.fiveHourRatio=n/G.maxPer5h),r}function Xs(s,e=Date.now()){let t=Ys(e);return s?null:G.maxPerHour&&t.lastHour>=G.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${G.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}:G.maxPer5h&&t.last5h>=G.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${G.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 Vs(s=Date.now()){let e=Ys(s),t=G.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var Xt=new Map;function Zs(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function er(s,e,t,n=Date.now()){let r=Xt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Xt.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function tr(s){let e=Xt.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as X,mkdirSync as Vi,readdirSync as ne,readFileSync as je,rmSync as Zi,writeFileSync as ea}from"fs";import{resolve as W}from"path";import{existsSync as me,mkdirSync as Vt,readFileSync as Ci,readdirSync as Ai,renameSync as $i,unlinkSync as Mi,writeFileSync as gt}from"fs";import{resolve as ue,relative as pt}from"path";import{z as K}from"zod";var he=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 Ri(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(`
115
- `)){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 ht(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(`
116
- `)}var He=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ue(process.cwd(),".agentx/procedures"),Vt(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=Ci(e,"utf-8"),{meta:n,body:r}=Ri(t),o=he.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:pt(this.baseDir,e)}:null}listDir(e){if(!me(e))return[];let t=[];for(let n of Ai(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 me(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return me(t)?this.parseFile(t):null}add(e,t){let n=he.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(me(r))throw new Error(`Procedure already exists: ${n.id}`);return gt(r,ht(n)+`
117
-
118
- `+t.trim()+`
119
- `),{meta:n,body:t.trim(),path:pt(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=he.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return gt(this.pathFor(e),ht(o)+`
120
-
121
- `+i.trim()+`
122
- `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let n=he.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(n.id))throw new Error(`Procedure already exists: ${n.id}`);let r=this.draftPathFor(n.id);if(me(r))throw new Error(`Draft already exists: ${n.id}`);return Vt(this.draftsDir,{recursive:!0}),gt(r,ht(n)+`
123
-
124
- `+t.trim()+`
125
- `),{meta:n,body:t.trim(),path:pt(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=he.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return gt(this.pathFor(e),ht(n)+`
126
-
127
- `+t.body+`
128
- `),Mi(this.draftPathFor(e)),{meta:n,body:t.body,path:pt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!me(t))throw new Error(`Draft not found: ${e}`);let n=ue(this.draftsDir,"_rejected");Vt(n,{recursive:!0}),$i(t,ue(n,`${e}.md`))}isRejected(e){return me(ue(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Pi,mkdirSync as _i,readFileSync as Di,writeFileSync as Ei}from"fs";import{dirname as Oi,resolve as Ni}from"path";import{z as J}from"zod";var Li=J.object({key:J.string(),count:J.number().int().min(0).default(0),firstSeen:J.string(),lastSeen:J.string(),taskIds:J.array(J.string()).default([]),sampleMessage:J.string().default(""),status:J.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:J.string().optional()}),Fi=J.object({minedThrough:J.string().optional(),candidates:J.array(Li).default([])});function nr(s){return Ni(s,"_candidates.json")}function Hi(s){let e=nr(s);if(!Pi(e))return{candidates:[]};try{let t=Fi.safeParse(JSON.parse(Di(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function ji(s,e){let t=nr(s);_i(Oi(t),{recursive:!0}),Ei(t,JSON.stringify(e,null,2)+`
129
- `)}function Ui(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 Wi(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Bi(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Zt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function sr(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 en(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Zt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=sr(o,Zt(a.meta.trigger));d>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=sr(o,Zt(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 tn(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(`
130
- `)})].join(`
131
-
132
- `)}Cn();St();var sn="turn-progress",rr={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.")},nn=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function or(s){return{agent:s.agent,request:nn(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:nn(e.input,300),...e.result!==void 0?{result:nn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}St();var ir="turn-handoff",ar="approval-binding",cr={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.")},dr={approves:$e("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},Ki=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,ur=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,qi=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function rn(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:qi.test(e.split(`
133
- `).slice(-3).join(" ")):!1}var Gi=/^\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 lr(s){return s.trim().length<=160&&Gi.test(s)}function gr(s){return s.trim().length<=160}function pr(s){return{agent:s.agent,channel:s.channel,request:Ki(s.request,1500),agentReplyEnding:ur(s.reply,1200)}}function hr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:ur(s.previousReply,1200)}}var Ji=5*6e4,Qi=3,zi=12,Yi=24*60*6e4,mr=new Set(["cron","heartbeat","bench","a2a","business"]),Xi={observe(){},stop(){}};function fr(s){if(vn(sn)==="off")return Xi;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[h,w]of o)w>1&&(!p||w>p.times)&&(p={call:h,times:w});return p},l=p=>{if(c)return;c=!0,a=n.length;let h=or({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-zi),repeated:d(),trigger:p});ye(sn,h,rr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{c=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Ji);return u.unref?.(),{observe(p){let h=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let w of h){if(w?.type!=="tool_use")continue;let T=w.input?JSON.stringify(w.input):"",x={tool:w.name||"tool",input:T};n.push(x),typeof w.id=="string"&&r.set(w.id,x);let I=`${x.tool}(${T})`,g=(o.get(I)??0)+1;o.set(I,g),g>=Qi&&!i.has(I)&&(i.add(I),l("repetition"))}else if(p?.type==="user")for(let w of h){if(w?.type!=="tool_result")continue;let T=r.get(w.tool_use_id);T&&(T.result=Array.isArray(w.content)?w.content.map(x=>typeof x?.text=="string"?x.text:"").join(""):typeof w.content=="string"?w.content:"",w.is_error&&(T.error=!0))}},stop(){clearInterval(u)}}}var on=new Map,yr=(s,e,t)=>`${s}\0${e}\0${t}`;function br(s){if(mr.has(s.channel)||!rn(s.reply))return;let e=yr(s.agent,s.channel,s.chatId);ye(ir,pr(s),cr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&on.set(e,{callId:t.callId,at:Date.now()})})}function wr(s){if(mr.has(s.channel))return;let e=yr(s.agent,s.channel,s.chatId),t=on.get(e);if(t){on.delete(e);let n=Sn().store;if(n&&Date.now()-t.at<Yi)try{n.label(t.callId,"userReply",lr(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!gr(s.message)||!rn(s.previousReply)||ye(ar,hr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),dr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function xr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Cr;function zd(s){Cr=s}function Yd(){return Cr}var Tr=64*1024,ta=5*60*1e3,ve=".agentx/task-history",na=30;function Ue(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function sa(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 ra(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(`
134
- `),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:
135
- 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(`
136
- `)}var an=8*1024;function kr(s){if(s.length<=an)return s;let e=s.length-an;return s.slice(0,an)+`\u2026[+${e}]`}function Ir(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 oa(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 Sr(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=te();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?kr(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?kr(a):null,at:r})}return}}function ia(){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
137
- `;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
138
- `;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
139
- `;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
140
- `;if(n==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
141
- `;if(n==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
142
- `;if(n==="codex.spawned"){let r=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${r}${o}
143
- `}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
144
- `;if(n==="turn.started")return`. codex turn started
145
- `;if(n==="turn.completed"){let r=t.usage||{},o=r.input_tokens??r.inputTokens,i=r.output_tokens??r.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
146
- `}if(n==="item.started"||n==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let c=r.text,d=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,d}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(n==="item.started")return`
147
- > codex ${o}${i?` ${i}`:""}
148
- `;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${Ue(String(a),800)}`:""}
149
- `}if(n==="error"||n==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${Ue(String(r),800)}
150
- `}if(n==="system"&&t.subtype==="init"){let r=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${r}${o}
151
- `}if(n==="assistant"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>s.length&&(r+=o.text.slice(s.length),s=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")r+=`
152
- \u{1F4AD} ${Ue(o.thinking,600)}
153
- `;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?Ue(JSON.stringify(o.input),400):"";r+=`
154
- \u2192 ${i}(${a})
155
- `}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}${Ue(i,800)}
156
- `}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
157
- `:""}}var vr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new dt;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new Ln;activeSouls=new Map;taskOutputs=new Map;taskAborts=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 ot(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Nn(void 0,void 0,"unified"),this.memoryStore=new at,this.patternStore=new lt,this.rateLimiter=new it,this.tokenTracker=new Se,this.messageQueue=new ut,Js({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new En({baseDir:W(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new On({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=Cs(p.messages,e.message??""),c=As(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 ye(Kn,Gn(d),qn,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!Jn(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),te().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-QEO3COFH.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(`
158
- `)[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.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Hn().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=re(e.autonomy),i=o?null:Ks().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 m=await i;if(m.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${m.sessionId}`),{content:m.text,viaAttachedSession:m.sessionId};this.log(`[${e.agentId}] attached session did not take it (${m.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 m=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(M=>M.id===e.agentId));if(m){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${m.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(m.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:m.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${m.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";if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||o){let m=Date.now(),f=25*6e4,M=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-m>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(N=>setTimeout(N,M))}}else{let m=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 M=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${M})`),{content:"",error:`__queued__:${f}:${M}`}}}let l=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(m,f)=>{this.log(`[${e.agentId}] ${m} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!l.ok)return this.log(`[${e.agentId}] ${l.reason}`),{content:"",error:l.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let u={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(u),e.runningTaskId=u.id,e.onStart)try{e.onStart(u.id)}catch{}let p=new AbortController;this.taskAborts.set(u.id,{agentId:e.agentId,channel:u.channel,chatId:typeof u.chatId=="string"?u.chatId:"",originalMessage:e.message||"",controller:p});let h={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(u.id,h);let w=m=>{if(m){h.buffer+=m,h.buffer.length>Tr&&(h.buffer=h.buffer.slice(h.buffer.length-Tr));for(let f of h.subscribers)try{f(m)}catch{}}},T=fe();e.taskId=T;let x=new Map,I;if(t){let m=ia();I=f=>{let M=m(f);if(M&&w(M),Sr(T,e.agentId,f),Ir(x,f),r)try{r(f)}catch{}}}else I=m=>{if(Sr(T,e.agentId,m),Ir(x,m),r)try{r(m)}catch{}};this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent})`);let g=e.context?.channel||"api",{evaluateRequest:_,selectRequestContext:A}=await import("./request-planner-KYQCJDAW.js"),S=await _(e.message,e.agentId,g);S.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let y=e.context?.chatId||e.context?.group||e.context?.sender||"default",E=e.context?.sender||"User",C=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,y),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${y}`),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,g,y,e.seedHistory);let O=[...this.sessions.getSession(e.agentId,g,y).messages].reverse().find(m=>m.role==="agent")?.content;wr({agent:e.agentId,channel:g,chatId:y,message:e.message,previousReply:O,taskId:T}),this.sessions.addUserMessage(e.agentId,g,y,E,e.message);let F=Date.now();te().emit("task:started",{agentId:e.agentId,channel:g,chatId:y,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(F).toISOString(),taskId:T});let D;if(this.classifier&&g!=="a2a"&&!C)try{D=await this.classifier.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(m){this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`)}let L=this.config.workflows?.matching,v;if(this.config.workflows?.enabled&&L?.enabled&&!o)try{let m=new Wn({baseDir:W(process.cwd(),this.config.workflows.dir)}),f=Bn({agentId:e.agentId,channel:g,message:e.message,intentPath:D?.path},m.list());f&&f.confidence>=L.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${L.mode} reasons=${f.reasons.join(",")||"n/a"}`),L.mode==="auto"&&f.confidence>=L.autoRunThreshold&&(this.workflowAutoRunner?v={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(m){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${m?.message||m}`)}let b=this.wikiHub.getAgentWiki(e.agentId),k=this.memoryStore.findRelevant(e.message,e.agentId,C?3:8),P=this.memoryStore.buildContext(k),U=this.patternStore.findRelevant(e.message,e.agentId,5),R=this.patternStore.buildContext(U),z="";if(!C)try{let{loadLocalSkills:m,getAutoInjectSkills:f}=await import("./loader-BOKE5M5S.js"),M=await m(a.def.workspace);z=f(M,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,y):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,y):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,y):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,y)&&(this.log(`[${e.agentId}] session stale for ${g}:${y}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,y)){let m=this.sessions.getLastTurnContextTokens(e.agentId,g,y);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${y} (last turn context: ${m} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"tier-2",lastTurnInputTokens:m,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,y)){let m=this.sessions.getTurnCount(e.agentId,g,y);this.log(`[${e.agentId}] max-turns rotation for ${g}:${y} (${m} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"max-turns",at:new Date().toISOString()}),j=void 0}j&&a.def.tier==="claude-code"&&await this.maybeRotateForContinuity(e,a,g,y,j)&&(j=void 0);try{let m=await this.sessions.compactIfNeeded(e.agentId,g,y,this.memoryStore);if(m.compacted){let f=m.qualityScore??"?",M=m.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${y} (quality: ${f}%, ${M} entities lost)`),m.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${m.lostEntities.slice(0,5).join(", ")}`),m.drift){let N=m.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${N.overallScore} (lexicon=${N.lexiconDecay}, tools=${N.toolShift}, semantic=${N.semanticDrift})`),N.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${N.lostWords.slice(0,5).join(", ")}`)}}}catch(m){this.log(`[${e.agentId}] compaction failed (non-fatal): ${m.message}`)}let Ar=process.env.AGENTX_CONTEXT_SURGERY==="1",$r=C?{maxMessages:8,maxChars:2400}:Ar&&xr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Mr=!j&&!C?ra(b,e.agentId):void 0,We=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,y,$r),Rr=j?void 0:this.sessions.getRotationMemo(e.agentId,g,y)??void 0,cn;if(this.config.procedures?.injection?.enabled&&!j&&!C)try{let m=new He({baseDir:W(process.cwd(),this.config.procedures.dir)}),f=en(e.message,m.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){cn=tn(f);for(let M of f)this.log(`[${e.agentId}] procedure match ${M.procedure.meta.id} score=${M.score.toFixed(2)} (${M.reasons.join(",")})`)}}catch(m){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${m?.message||m}`)}if(le&&le.cat)try{let f=this.sessions.getSession(e.agentId,g,y).messages,M=f[0],N=f[f.length-1],B=We===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${We.length}c/${We.split(`
159
- `).length}L`,V=`[${e.agentId}] ${g}:${y} ${B} | session.messages=${f.length}`+(f.length>0?` first=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")}) last=${N.timestamp.slice(11,19)}(${N.role}:${(N.content||"").slice(0,40).replace(/\n/g," ")})`:"");le.cat("context",V)}catch(m){le.cat("context",`[${e.agentId}] context-diag error: ${m?.message??m}`)}let dn;if(a.def.contextReferences&&!j)try{let m=a.def.workspace,f=this.referencesCache.get(m);if(!f){let[N,B]=await Promise.all([Ct(a.def.workspace),At(a.def.workspace)]);if(N.byId.size===0&&B.recipes.length===0){let[V,$]=await Promise.all([Ct(process.cwd()),At(process.cwd())]);f={refs:V,recipes:$}}else f={refs:N,recipes:B};this.referencesCache.set(m,f)}let M=jn({agentId:e.agentId,intentTags:D?.path,message:e.message},f.recipes,f.refs);M.cards.length>0&&(dn=Fn(M.cards,500*4)),M.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${M.unresolvedIds.join(", ")}`)}catch(m){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${m?.message||m}`)}let un=this.sessions.getCrossSessionSummary(e.agentId,g,y,e.message),ln,Be=vs(e.message);if(Be)try{let m=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:y,lookbackDays:Be.lookbackDays,limit:12});if(m.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Be.lookbackDays}d on this chat (cue-triggered)]`],M=[...m.turns].sort((N,B)=>N.ts.localeCompare(B.ts));for(let N of M){let B=N.ts.slice(11,16)+" "+N.day,V=N.role==="user"?N.senderName||"User":N.senderName||"Agent";f.push(`${B} ${V}: ${N.content}`)}m.hasMore&&f.push(`[\u2026${m.totalScanned-m.turns.length}+ older turns available \u2014 call /recall with before=${m.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),ln=f.join(`
160
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Be.lookbackDays}d, turns=${m.turns.length}, scanned=${m.totalScanned}`)}}catch(m){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${m.message}`)}let Pr=C?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",gn,pn,hn=!1;if(Pr==="planner"&&!S.active&&g!=="voice"&&g!=="desktop"){try{let{planContext:m}=await import("./context-planner-AQHJMVY2.js"),f=await m({agentId:e.agentId,channel:g,chatId:y,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});f?(hn=!0,gn=f.sessionHistory,P=f.memoryContext,un=f.crossChatContext,pn=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(m){this.log(`[${e.agentId}] planner failed (non-fatal): ${m.message} \u2014 falling back to layered (keeping --resume for continuity)`)}hn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,g,y),j=void 0)}let mt=`${e.agentId}:${g}:${y}`,Ke=Rn(e.message);Ke&&(Ke==="default"?(this.activeSouls.delete(mt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(mt,Ke),this.log(`[${e.agentId}] Soul switched to: ${Ke}`)));let _r=this.activeSouls.get(mt),Dr=$n(a.def.workspace,_r),Er=Mn(Dr),Or=this.agentMemory.indexMarkdown(e.agentId),Nr=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
161
- 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.`:"",Lr=a.def.richMessages!==!1&&(g==="telegram"||g==="whatsapp")?["[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(`
162
- `):"",mn="";if(a.def.workspace){let m=W(a.def.workspace,"CLAUDE.md");if(X(m))try{let f=je(m,"utf-8");mn=`[Project CLAUDE.md]
163
- ${f.length>4e3?f.slice(0,4e3)+`
164
-
165
- [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let qe=e.context?.runbookPath,ft=[];if(qe&&X(qe)){let m=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,M=4e3,N=16e3;for(let B of m){if(f>=N)break;let V=W(qe,B);if(X(V))try{let $=je(V,"utf-8"),Y=$.length>M?$.slice(0,M)+`
166
-
167
- [${B} truncated to ${M} bytes]`:$;ft.push(`[Project Runbook \u2014 ${B} from ${qe}]
168
- ${Y}`),f+=Y.length}catch{}}}let Fr=ft.length>0?ft.join(`
169
-
170
- `):"",yt=[a.def.systemPrompt||"",Nr,Lr,mn,Fr,Er||"",Or||""].filter(m=>m.trim().length>0).join(`
171
-
172
- `)||void 0,fn={channel:g,chatId:y,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:E,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:C||xr(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:C?void 0:R||void 0,procedureContext:cn,references:dn,skillInjection:z||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:gn??We,memoryContext:P||void 0,crossChatContext:un||void 0,longMemoryRecall:ln||void 0,wikiContext:Mr,handoverNote:this.buildHandoverNote(e.agentId,g,y),rotationMemo:Rr,intent:D?{path:D.path,pathLabel:D.pathLabel,pathId:D.pathId,axes:D.axes,leaf:D.leaf,status:D.status}:void 0,message:e.message},bt=S.active&&S.preprocess?await A(fn):{input:fn,excluded:[]};bt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${bt.excluded.join(", ")}`);let wt=Os(bt.input,C?{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),xt=(wt?.length??0)+(yt?.length??0)+(e.message?.length??0),Ge={history:wt?.length??0,sysPrompt:yt?.length??0,message:e.message?.length??0},yn=Zs(e.agentId,g,y);er(yn,xt,Ge);let bn=tr(yn);bn&&this.log(`[${e.agentId}] ${bn}`),xt>16e3&&this.log(`[${e.agentId}] large context for ${g}:${y}: ${xt} bytes (history=${Ge.history}, sysPrompt=${Ge.sysPrompt}, message=${Ge.message})`);let Tt,wn=An(a.def.tier,this.config.decisions.routing);if(!e.model&&wn&&(!S.active||S.preprocess))try{let{routeTaskModel:m}=await import("./routing-OC3QJI3W.js"),f=await m({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,y),cheapModel:wn});f.downgraded&&(Tt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let Hr={...e,systemPromptAppend:yt,...Tt?{model:Tt}:{}},Z,xn=fr({agent:e.agentId,request:e.message,taskId:T,budgetMinutes:a.def.maxExecutionMinutes??20}),jr=I;I=m=>{xn.observe(m),jr?.(m)};try{if(v&&this.workflowAutoRunner)try{let H=await this.workflowAutoRunner({workflowId:v.workflowId,agentId:e.agentId,channel:g,chatId:y,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:y,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:D?.path,matchedWorkflowId:v.workflowId,matchConfidence:v.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${v.workflowId} run=${H.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),Z={content:"",duration:0,metadata:{handledByWorkflow:v.workflowId,workflowRunId:H.runId,workflowMatchConfidence:v.confidence}},Z}catch(H){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${H?.message||H}`)}if(a.def.tier==="claude-code"){let H=a.def.persistentProcess?et():null,Q=H!=null&&H.hasLive({agentId:e.agentId,channel:g,chatId:y}),se=!!j||Q,ee=[qs(se),Xs(se)].find(Ae=>Ae&&Ae.abort);if(ee){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ee.reason}`);let Ae={content:"",error:ee.message,duration:0};if(!t){h.buffer=`[error] ${ee.message}`;for(let Ur of h.subscribers)try{Ur(h.buffer)}catch{}}return Z=Ae,Ae}zs();let Ce=Vs();Ce&&this.log(`[${e.agentId}] ${Ce}`)}let m=a.def.tier==="claude-code",f=m?t:(H,Q)=>{H&&w(H),t&&t(H,Q)},M=!1,N=m?n:H=>{H&&(M?w(H):(w(`\u{1F4AD} ${H}`),M=!0)),n&&n(H)},B=()=>{M&&(w(`
173
- `),M=!1)},V=m?f:f?(H,Q)=>{B(),f(H,Q)}:void 0,$=await ks(a.def,Hr,this.providers,V,wt,j,I,p.signal,N);if(!$.error){let H=oa(a.def.toolUseRequired,x);if(H){let Q=Array.from(x.entries()).map(([se,Je])=>`${se}=${Je}`).join(", ")||"none";$.error=`tool_required_not_called: ${H} (invoked: ${Q})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${H}, observed ${Q}`)}}Z=$;let Y=$.usage?Ds($.usage):void 0;if(te().emit("task:completed",{taskId:T,agentId:e.agentId,channel:g,chatId:y,durationMs:Date.now()-F,error:$.error||void 0,inputTokens:Y?.inputTokens,outputTokens:Y?.outputTokens,cacheReadTokens:Y?.cacheReadTokens,cacheCreateTokens:Y?.cacheCreateTokens,tier2InputTokens:Y?.tier2InputTokens,tier2OutputTokens:Y?.tier2OutputTokens,tier2CacheReadTokens:Y?.tier2CacheReadTokens,tier2CacheCreateTokens:Y?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:S.arm,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let H=$.error?`[error] ${$.error}`:$.content;h.buffer=H;for(let Q of h.subscribers)try{Q(H)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,y,$.content),br({agent:e.agentId,channel:g,chatId:y,request:e.message,reply:$.content,taskId:T}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,y,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,g,y,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,g,y,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,g,y,$.usage,$.contextTokens),$.usage){let ee=$.contextTokens,Ce=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ee??Ce)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${y}: context=${ee??"n/a"} tokens (cumulative turn total=${Ce}) \u2014 next turn will rotate`)}if($s({channel:g,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let ee=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ee,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
174
-
175
- Agent: ${$.content}`,meta:sa(D,e.context)})}catch{}Dn(e.agentId,e.message,$.content,{channel:g,chatId:y,sender:E},this.memoryStore).catch(()=>{}),Ws(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=$.billedModel||e.model||a.def.model,se=e.context?.channel,Je=se&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${se}:${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,Q,se,Je),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:""))}return $}catch(m){a.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`);let f=Ve(m.message);return Z={content:"",error:Ze(f),errorKind:f.kind},Z}finally{xn.stop(),a.activeTasks--;let m=a.runningTasks.findIndex(f=>f.id===u.id);m!==-1&&a.runningTasks.splice(m,1),this.taskAborts.delete(u.id),h.done=!0,h.endedAt=new Date;for(let f of h.subscribers)try{f(`
176
- [task finished]
177
- `)}catch{}h.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),ta).unref?.();try{let f=h.endedAt,M={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:f.toISOString(),durationMs:f.getTime()-u.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:h.buffer};this.persistTaskRecord(M);let N=(M.responseText||M.error||"").trim();if(N){let B=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:f,ok:M.ok})}}catch(f){this.log(`[${e.agentId}] task history persist failed: ${f?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(f=>{if(f.length!==0){this.log(`[${e.agentId}] flushing ${f.length} queued message(s)`);for(let M of f){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(B=>this.postQueuedResponseToChannel(e.agentId,N,B)).catch(B=>{this.log(`[${e.agentId}] queued message failed: ${B.message}`)})}}}).catch(f=>{this.log(`[${e.agentId}] queue flush failed: ${f.message}`)})}}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=W(process.cwd(),ve,this.safe(e.agentId),t);X(n)||Vi(n,{recursive:!0});let r=W(n,`${this.safe(e.id)}.json`);ea(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=W(process.cwd(),ve,this.safe(e));if(!X(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=W(a,u);if(X(p))try{for(let h of ne(p)){if(!h.endsWith(".json"))continue;let w=h.split("-")[0],T=parseInt(w,10);if(!Number.isFinite(T)||T<i||T>n)continue;let x=Math.floor((n-T)/36e5),I=t-1-x;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=W(process.cwd(),ve);if(!X(e))return 0;let t=0;for(let n of ne(e)){let r=W(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=W(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(je(W(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=na){let t=W(process.cwd(),ve);if(!X(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=W(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{Zi(W(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=W(process.cwd(),ve,this.safe(e));if(!X(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=W(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(je(W(a,d),"utf-8")),{transcript:u,responseText:p,...h}=l;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=W(process.cwd(),ve,this.safe(e));if(!X(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=W(n,i,`${r}.json`);if(X(a))try{return JSON.parse(je(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Un();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}`))}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}}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),h=!1;if(r.replace){let w=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(w))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${w}`),h=!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:h,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}):u({ok:!1,status:500,error:p.error||"run did not start"})}).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{Qn as a,zn as b,wa as c,Xn as d,so as e,Vn as f,ts as g,Pa as h,Oa as i,Na as j,wo as k,ws as l,So as m,vo as n,Co as o,ks as p,ot as q,it as r,dt as s,te as t,Bs as u,mi as v,Ks as w,He as x,Hi as y,ji as z,Ui as A,Wi as B,Bi as C,en as D,zd as E,Yd as F,sa as G,ra as H,an as I,kr as J,Ir as K,oa as L,Sr as M,vr as N};
178
- //# sourceMappingURL=chunk-T76YTN34.js.map