agentix-cli 0.28.0 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -3
- package/dist/{App-CKPH3HHF.js → App-IEQXWJ7B.js} +2 -2
- package/dist/{ChatApp-MX7IG4K2.js → ChatApp-NWOSAP5U.js} +2 -2
- package/dist/{agent-2U574KBZ.js → agent-SPE7Q7MD.js} +2 -2
- package/dist/{board-dashboard-QR7CVTKA.js → board-dashboard-K4DM32SO.js} +4 -4
- package/dist/{chunk-VIH7ARPF.js → chunk-42DCRKUD.js} +130 -129
- package/dist/chunk-42DCRKUD.js.map +1 -0
- package/dist/chunk-45BLFNDG.js +170 -0
- package/dist/chunk-45BLFNDG.js.map +1 -0
- package/dist/{chunk-ZMYGXHPT.js → chunk-4KXBUORV.js} +2 -2
- package/dist/{chunk-H2QQU2XV.js → chunk-AUNDQPDR.js} +2 -2
- package/dist/{chunk-5IA2CYHN.js → chunk-DI7FMCDK.js} +2 -2
- package/dist/chunk-DWADWDMU.js +96 -0
- package/dist/chunk-DWADWDMU.js.map +1 -0
- package/dist/{chunk-YLBERT7N.js → chunk-EL3J74N2.js} +2 -2
- package/dist/{chunk-S2MNL5V6.js → chunk-GK7XAM3D.js} +2 -2
- package/dist/chunk-GK7XAM3D.js.map +1 -0
- package/dist/{chunk-P5ZBBEPL.js → chunk-GMNKJXTR.js} +1 -1
- package/dist/chunk-GMNKJXTR.js.map +1 -0
- package/dist/{chunk-E3UJHQGN.js → chunk-GUBMLV34.js} +142 -130
- package/dist/chunk-GUBMLV34.js.map +1 -0
- package/dist/{chunk-64CAIB3C.js → chunk-IVQO43U2.js} +2 -2
- package/dist/{chunk-G2HMRDUQ.js → chunk-JKYMXLYL.js} +2 -2
- package/dist/{chunk-YLGIZRHV.js → chunk-MGNJWBVP.js} +2 -2
- package/dist/{chunk-3LYM22IV.js → chunk-Q7CZIRBB.js} +2 -2
- package/dist/{chunk-SCTIUFL4.js → chunk-SC5DIKBB.js} +2 -2
- package/dist/{chunk-MHIMGM4G.js → chunk-UU4WOZNR.js} +2 -2
- package/dist/{chunk-QHTQPBHU.js → chunk-V4HURNMX.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-5Z3URGPY.js +2 -0
- package/dist/config-ORSGLVRW.js +2 -0
- package/dist/config-mutator-JB3S2E7H.js +2 -0
- package/dist/doctor-FS2BX6H4.js +2 -0
- package/dist/index.d.ts +187 -185
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/program-DWZAI4GY.js +2 -0
- package/dist/query-3HXGBKGM.js +2 -0
- package/dist/registry-EJRWAJYG.js +2 -0
- package/dist/request-planner-BCOXUAPA.js +2 -0
- package/dist/request-planner-BCOXUAPA.js.map +1 -0
- package/dist/{review-candidates-RQU5KNZM.js → review-candidates-O2PS7L3B.js} +2 -2
- package/dist/routing-5K7PGHPL.js +2 -0
- package/dist/scheduler-DSAOMV4O.js +2 -0
- package/dist/seat-FZRNRAHQ.js +2 -0
- package/dist/{select-X4KVMOP5.js → select-SOJYFAMI.js} +2 -2
- package/dist/wiki-34XVI32N.js +2 -0
- package/dist/workspace-setup-G6KGWPHY.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-67Q4DCPS.js +0 -54
- package/dist/chunk-67Q4DCPS.js.map +0 -1
- package/dist/chunk-E3UJHQGN.js.map +0 -1
- package/dist/chunk-I3SIXTJO.js +0 -44
- package/dist/chunk-I3SIXTJO.js.map +0 -1
- package/dist/chunk-P5ZBBEPL.js.map +0 -1
- package/dist/chunk-S2MNL5V6.js.map +0 -1
- package/dist/chunk-ULLAE6LE.js +0 -157
- package/dist/chunk-ULLAE6LE.js.map +0 -1
- package/dist/chunk-VIH7ARPF.js.map +0 -1
- package/dist/client-ZLSXGPTV.js +0 -2
- package/dist/config-HMW3EBZL.js +0 -2
- package/dist/config-mutator-4SZ5YEVD.js +0 -2
- package/dist/doctor-LRYV3QLK.js +0 -2
- package/dist/program-GSZ5AYAM.js +0 -2
- package/dist/query-SQDHE4HV.js +0 -2
- package/dist/registry-LE6FWYZC.js +0 -2
- package/dist/routing-ILERJXB6.js +0 -2
- package/dist/scheduler-BFM3EINS.js +0 -2
- package/dist/seat-7WM7II2B.js +0 -2
- package/dist/wiki-2AUFSIKO.js +0 -2
- package/dist/workspace-setup-B3F3TUDE.js +0 -2
- /package/dist/{App-CKPH3HHF.js.map → App-IEQXWJ7B.js.map} +0 -0
- /package/dist/{ChatApp-MX7IG4K2.js.map → ChatApp-NWOSAP5U.js.map} +0 -0
- /package/dist/{agent-2U574KBZ.js.map → agent-SPE7Q7MD.js.map} +0 -0
- /package/dist/{board-dashboard-QR7CVTKA.js.map → board-dashboard-K4DM32SO.js.map} +0 -0
- /package/dist/{chunk-ZMYGXHPT.js.map → chunk-4KXBUORV.js.map} +0 -0
- /package/dist/{chunk-H2QQU2XV.js.map → chunk-AUNDQPDR.js.map} +0 -0
- /package/dist/{chunk-5IA2CYHN.js.map → chunk-DI7FMCDK.js.map} +0 -0
- /package/dist/{chunk-YLBERT7N.js.map → chunk-EL3J74N2.js.map} +0 -0
- /package/dist/{chunk-64CAIB3C.js.map → chunk-IVQO43U2.js.map} +0 -0
- /package/dist/{chunk-G2HMRDUQ.js.map → chunk-JKYMXLYL.js.map} +0 -0
- /package/dist/{chunk-YLGIZRHV.js.map → chunk-MGNJWBVP.js.map} +0 -0
- /package/dist/{chunk-3LYM22IV.js.map → chunk-Q7CZIRBB.js.map} +0 -0
- /package/dist/{chunk-SCTIUFL4.js.map → chunk-SC5DIKBB.js.map} +0 -0
- /package/dist/{chunk-MHIMGM4G.js.map → chunk-UU4WOZNR.js.map} +0 -0
- /package/dist/{chunk-QHTQPBHU.js.map → chunk-V4HURNMX.js.map} +0 -0
- /package/dist/{client-ZLSXGPTV.js.map → client-5Z3URGPY.js.map} +0 -0
- /package/dist/{config-HMW3EBZL.js.map → config-ORSGLVRW.js.map} +0 -0
- /package/dist/{config-mutator-4SZ5YEVD.js.map → config-mutator-JB3S2E7H.js.map} +0 -0
- /package/dist/{doctor-LRYV3QLK.js.map → doctor-FS2BX6H4.js.map} +0 -0
- /package/dist/{program-GSZ5AYAM.js.map → program-DWZAI4GY.js.map} +0 -0
- /package/dist/{query-SQDHE4HV.js.map → query-3HXGBKGM.js.map} +0 -0
- /package/dist/{registry-LE6FWYZC.js.map → registry-EJRWAJYG.js.map} +0 -0
- /package/dist/{review-candidates-RQU5KNZM.js.map → review-candidates-O2PS7L3B.js.map} +0 -0
- /package/dist/{routing-ILERJXB6.js.map → routing-5K7PGHPL.js.map} +0 -0
- /package/dist/{scheduler-BFM3EINS.js.map → scheduler-DSAOMV4O.js.map} +0 -0
- /package/dist/{seat-7WM7II2B.js.map → seat-FZRNRAHQ.js.map} +0 -0
- /package/dist/{select-X4KVMOP5.js.map → select-SOJYFAMI.js.map} +0 -0
- /package/dist/{wiki-2AUFSIKO.js.map → wiki-34XVI32N.js.map} +0 -0
- /package/dist/{workspace-setup-B3F3TUDE.js.map → workspace-setup-G6KGWPHY.js.map} +0 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import{a as An,g as Dn,m as _n}from"./chunk-IVQO43U2.js";import{b as Mn}from"./chunk-4KXBUORV.js";import{a as xt,b as $n}from"./chunk-WPMX3VGI.js";import{a as Tt,b as Rn}from"./chunk-K33GIBSE.js";import{a as Pn}from"./chunk-W4YR2RO2.js";import{a as yn}from"./chunk-GK7XAM3D.js";import{a as bn,b as wn,c as xn,d as Tn,f as kn}from"./chunk-DWADWDMU.js";import{a as Sn}from"./chunk-77OV7346.js";import{b as In,c as vn,f as Cn}from"./chunk-AUNDQPDR.js";import{a as Qe,b as ve}from"./chunk-EVWEG3VD.js";import{q as hn,t as fn,v as he,w as mn}from"./chunk-MGNJWBVP.js";import{a as Ge,b as pn}from"./chunk-ZTEU5JVQ.js";import{a as Ie,b as Je,f as wt}from"./chunk-F4HZTZHW.js";import{c as Be,d as qe}from"./chunk-QOYAX2FT.js";import{e as de}from"./chunk-DSYKYZMT.js";mn();wt();var On="session-continuity",En={continues:Ie("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:Ie("Does the new request refer to something stated earlier in the conversation?")};function Nn(r){let e=(r.recentRequests??[]).filter(Boolean);return{newRequest:kt(r.message,1200),previousRequest:r.previousMessage?kt(r.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>kt(t,400))}:{},minutesSinceLastTurn:r.minutesSinceLastTurn,turnsSoFar:r.turnCount,currentContextTokens:r.lastTurnContextTokens,agent:r.agentId,channel:r.channel}}function Ln(r,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=r.continues.noul,s=r.needsHistory.noul;return n<=t&&s<=t}function kt(r,e){let t=String(r??"");return t.length>e?t.slice(0,e):t}import{spawn as kr,execFile as Sr}from"node:child_process";import{createHash as Ir,randomBytes as vr}from"node:crypto";import{createInterface as Cr}from"node:readline";import{promisify as Ar}from"node:util";var $r=Ar(Sr),se=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},St=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=$r("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:u})=>/^(?:opencode\s+)?v?2\./.test(u.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new se("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let s=Ir("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[u])=>d.localeCompare(u))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new se("Conversation already running",!0);o&&(o.dead||o.fingerprint!==s||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 g=[...this.entries].find(([,h])=>!h.busy);if(!g)throw new se("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:vr(32).toString("hex")},u=kr("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:u,env:d,fingerprint:s,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let l=o;u.stderr.resume(),u.on("exit",()=>this.close(l)),u.on("error",()=>this.close(l));try{await new Promise((g,h)=>{let b=Cr({input:u.stdout}),T=()=>I(new se("OpenCode server failed before dispatch",!0)),w=()=>I(new Error("task cancelled by operator")),p=setTimeout(T,15e3),I=M=>{clearTimeout(p),u.removeListener("exit",T),u.removeListener("error",T),e.signal?.removeEventListener("abort",w),b.close(),u.stdout.resume(),M?h(M):g()};u.once("exit",T),u.once("error",T),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",M=>{try{let v=new URL(JSON.parse(M).url);if(v.protocol!=="http:"||v.hostname!=="127.0.0.1"||!v.port||v.username||v.password)return;l.url=v.origin,I()}catch{}}),e.signal?.aborted&&w()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}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()))}}}},Fn=new St;import{execa as et}from"execa";import{spawn as Mr}from"node:child_process";import{createHash as Rr}from"node:crypto";import{createInterface as Pr}from"node:readline";var re=class extends Error{},Dr=r=>Mr("codex",["app-server",...r.args],{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),It=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(),Pr({input:this.child.stdout}).on("line",s=>{let o;try{o=JSON.parse(s)}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",s=>this.close(s)),this.child.stdin.on("error",s=>this.close(s)),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((s,o)=>{this.pending.set(n,{resolve:s,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()}},vt=class{constructor(e=Dr,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=Rr("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[p])=>w.localeCompare(p))])).digest("hex"),s=this.entries.get(e.key);if(s?.connection.busy)throw new re("Conversation already running");s&&(s.fingerprint!==n||e.fresh||s.connection.dead)&&(s.connection.close(),this.entries.delete(e.key),s=void 0);let o=!!s;if(!s){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,p])=>!p.connection.busy);if(!w)throw new re("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{s={fingerprint:n,connection:new It(e,this.launchProcess)}}catch{throw new re("Could not start Codex app-server")}this.entries.set(e.key,s)}let i=s.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,g=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let b=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 w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((M,v)=>{i.failTurn=v,i.notify=(f,R)=>{if(R?.threadId!==u)return;let _=R.item,A={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:f.replace("/","."),..._?{item:{..._,type:A[_.type]||_.type}}:{}}),f==="item/completed"&&_?.type==="agentMessage"&&_.phase==="final_answer"&&(d=_.text),f==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),f==="thread/tokenUsage/updated"){let H=R.tokenUsage.last;l={inputTokens:H.inputTokens,outputTokens:H.outputTokens,cacheReadTokens:H.cachedInputTokens,cacheCreateTokens:H.cacheWriteInputTokens||0}}f==="turn/completed"&&(R.turn.status==="completed"?M():v(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new re(w.message);return{content:c,codexSessionId:u,usage:l,error:w.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(b),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())}}},Hn=new vt;import{execFile as jr}from"child_process";import{StringDecoder as $e}from"string_decoder";import{mkdtempSync as Gn,readFileSync as Jn,rmSync as Qn}from"fs";import{join as Ve}from"path";import{tmpdir as zn}from"os";function ze(r){let e=(r||"").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 s=n?.error||n,o=typeof s?.type=="string"?s.type:void 0,i=typeof s?.message=="string"?s.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 Ye(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var jn=null;function Xe(){return jn}function Qi(r){jn=r}function Ce(r){return`${r.agentId}:${r.channel}:${r.chatId}`}var fe=class extends Error{constructor(t,n,s){super(t);this.scope=n;this.cap=s;this.name="RegistryCapExceeded"}},Un=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=Ce(e),s=this.handles.get(n);if(s&&s.state()!=="dead")return s.claim?.(),s;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 fe(`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 fe(`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=Ce(e),s=this.handles.get(n);s&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&s.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ce(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ce(e),s=this.handles.get(n);s&&(this.handles.delete(n),this.handleWorkspace.delete(n),await s.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 s=Ce(t.key);return this.handles.delete(s),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${s} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let s=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-s.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!==s.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=s.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 _r}from"child_process";import{existsSync as Or,readFileSync as Er}from"fs";import{resolve as Nr}from"path";function Lr(r){let e=Nr(r,"CLAUDE.md");if(!Or(e))return null;try{let t=Er(e,"utf8");return kn(t)}catch{return null}}var Fr=20*60*1e3,Hr=5e3,Ae=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Wn=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ct(e,t,this.opts)}},Ct=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let s=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=_r(s,o,{cwd:t.workspace,env:ve({...process.env}),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:Lr(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(u=>{t=u}),s=this.turnQueue;if(this.turnQueue=s.then(()=>n),await s,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??Fr,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ae(a));try{for(;;){let u=c-Date.now();if(u<=0)throw d();let l=await this.nextEvent(u);if(l===null&&!this.exited)throw d();if(l===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:l.type,raw:l},l.type==="result"){this.onResultEvent(l);return}}}finally{let u=this.snap.state==="busy";this.snap={...this.snap,...u?{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 s of t)s(null);let n=await new Promise(s=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}s(!0)},Hr);this.child.once("exit",()=>{clearTimeout(o),s(!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 s;try{s=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(s):this.pendingEvents.push(s)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,s=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(s),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"}}};function q(r){let e=ze(r);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(r||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
5
|
+
`)}return{error:Ye(e),errorKind:e.kind}}function Yn(){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 Ze(){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 Kn(){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 ie(r,e,t){let n=[];if(e.context&&!t){let s=e.context,o=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),a=s.channel==="telegram";if(s.channel&&o.push(`Channel: ${s.channel}`),s.group&&o.push(`Group: ${s.group}`),s.sender&&o.push(`Message from: ${s.sender}`),s.myHandle&&o.push(`Your handle on this channel: ${s.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&&s.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of s.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}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(`
|
|
6
|
+
`))}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(`
|
|
7
|
+
`)}function Xn(r,e,t,n,s,o){let i=["-p",e,"--output-format",t?"stream-json":"json"];t&&i.push("--verbose"),n&&i.push("--resume",n);let a=s||r.model;return a&&i.push("--model",a),r.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&i.push("--append-system-prompt",o),i}function At(r,e){return!e||e.trim().length===0?r:`[System]
|
|
8
|
+
${e.trim()}
|
|
9
|
+
|
|
10
|
+
[User]
|
|
11
|
+
${r}`}function Ur(r,e,t,n,s){let o=["run","--format","json","--thinking"],i=t||r.model;return i&&o.push("--model",i),s&&o.push("--session",s),r.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(At(e,n)),o}function Wr(r){if(!r||typeof r!="object"||r.type!=="error")return;let e=r.error?.message??r.error??r.message??r.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function Bn(r){return JSON.stringify(r)}function Vn(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Bn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(Bn).join(",")}]`]}function Zn(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Vn()),i||a.push("--color","never");let c=n||r.model;return c&&a.push("--model",c),r.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(At(e,s)),a}function tt(r,e){let t=Qe(r.workspace),n=t.HOME||process.env.HOME,s=[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(s.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),t.AGENTX_AGENT_ID=e.agentId,e.context?.channel&&(t.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(t.AGENTX_CHAT_ID=e.context.chatId),t}function Kr(r,e){let t=tt(r,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let s={...n.mcp||{}};for(let[i,a]of Object.entries(r.mcp||{}))s[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 s.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:s}),t}function Br(r){if(!r||typeof r!="object")return;if(typeof r.delta=="string")return r.delta;if(typeof r.text_delta=="string")return r.text_delta;if(typeof r.message=="string"&&/message|delta/i.test(String(r.type||"")))return r.message;if(typeof r.text=="string"&&/message|delta|response/i.test(String(r.type||"")))return r.text;let e=r.item||r.msg||r.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(r.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n)return n}}function oe(...r){for(let e of r)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function $t(r,e=0){if(!r||typeof r!="object"||e>4)return;let t=r.usage||r.token_usage||r.tokenUsage||r.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:oe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:oe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:oe(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:oe(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[r.msg,r.message,r.response,r.result,r.item]){let s=$t(n,e+1);if(s)return s}}function es(r){if(!(!r||typeof r!="object"))return typeof r.model=="string"&&r.model||typeof r.msg?.model=="string"&&r.msg.model||typeof r.message?.model=="string"&&r.message.model||typeof r.response?.model=="string"&&r.response.model||void 0}function Mt(r,e=0){if(!(!r||typeof r!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[r.msg,r.message,r.response,r.result,r.item]){let n=Mt(t,e+1);if(n)return n}}}function qr(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
12
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=$t(a)||t,n=es(a)||n,s=Mt(a)||s,o=ts(a)||o}catch{}return{usage:t,billedModel:n,sessionId:s,apiError:o}}function ts(r){if(!(!r||typeof r!="object")){if(r.type==="error"&&typeof r.message=="string")return qn(r.message);if(r.type==="turn.failed"){let e=r.error?.message??r.error;if(typeof e=="string")return qn(e)}}}function qn(r){let e=r.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 Gr(r){let e=r.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function Rt(r,e,t,n,s){let o=Gr(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${r} via=${s} model=${i} perm=${o.summary}${a}
|
|
13
|
+
`)}function Jr(r){try{let e=JSON.parse(r);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 Qr(r){try{let e=JSON.parse(r),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:r}}}async function zr(r,e,t,n,s){let o=Date.now(),i=ie(r,e,t),a=Xn(r,i,!1,n,e.model,e.systemPromptAppend);if(Rt(e.agentId,r,e.model,n,"spawn"),s?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:l,exitCode:g,killed:h}=await new Promise(w=>{let p=ve(Qe(r.workspace)),I=!1,M=jr("claude",a,{cwd:r.workspace,timeout:d,maxBuffer:10*1024*1024,env:{...p,HOME:p.HOME||"/home/"+(p.USER||"user")}},(v,f,R)=>{w({stdout:f||"",stderr:R||"",exitCode:v?v.code??1:0,killed:I})});if(M.stdin?.end(),s){let v=()=>{I=!0,c=s.reason?.message||(typeof s.reason=="string"?s.reason:"task cancelled by operator");try{M.kill("SIGTERM")}catch{}setTimeout(()=>{try{M.killed||M.kill("SIGKILL")}catch{}},3e3).unref?.()};s.aborted?v():s.addEventListener("abort",v,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&g!==0){let w;return g===143?w=`Claude Code timed out after ${Math.round(d/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:g==="ENOENT"||/ENOENT|spawn claude/i.test(l||"")?w=Yn():w=l?.trim()||`Claude Code exited with code ${g}`,{content:"",...q(w),duration:Date.now()-o}}let b=Jr(u);if(b)return{content:"",...q(b),duration:Date.now()-o};let T=Qr(u);return{content:T.text,duration:Date.now()-o,claudeSessionId:T.sessionId,usage:T.usage,numTurns:T.numTurns,billedModel:T.billedModel}}catch(d){return console.error(`[runtime] execFile threw: ${d.message}`),{content:"",error:d.message||"Claude Code failed",duration:Date.now()-o}}}async function Yr(r,e,t,n,s,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ie(r,e,n),d=Xn(r,c,!0,s,e.model,e.systemPromptAppend);Rt(e.agentId,r,e.model,s,"stream");let u="",l,g,h,b,T,w;try{let p=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),I=ve(Qe(r.workspace)),M=et("claude",d,{cwd:r.workspace,timeout:p,reject:!1,env:I,extendEnv:!1,buffer:!1,stdin:"ignore"}),v=!1,f;if(i){let D=()=>{v=!0,f=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{M.kill("SIGTERM")}catch{}setTimeout(()=>{try{M.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?D():i.addEventListener("abort",D,{once:!0})}let R="",_=new $e("utf8");M.stdout&&M.stdout.on("data",D=>{R+=_.write(D);let L=R.split(`
|
|
14
|
+
`);R=L.pop()||"";for(let O of L)if(O.trim())try{let x=JSON.parse(O);if(o)try{o(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let S=x.message.usage,k=(S.input_tokens||0)+(S.cache_read_input_tokens||0)+(S.cache_creation_input_tokens||0);k>0&&(b=k)}if(x.type==="assistant"&&x.message?.content){for(let S of x.message.content)if(S.type==="text"&&S.text){let k=S.text.slice(u.length);k&&(u=S.text,t(k,u))}}if(x.type==="content_block_delta"&&x.delta?.text&&(u+=x.delta.text,t(x.delta.text,u)),x.type==="result"&&x.result){if(x.is_error&&typeof x.result=="string")w=x.result;else{let S=(typeof x.result=="string",x.result);if(typeof S=="string"&&S.length>u.length){let k=S.slice(u.length);u=S,k&&t(k,u)}}x.usage&&(g={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.model=="string"&&(l=x.model),typeof x.session_id=="string"&&(h=x.session_id),typeof x.num_turns=="number"&&(T=x.num_turns)}x.type==="system"&&x.subtype==="init"&&(typeof x.model=="string"&&(l=x.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${x.apiKeySource} version=${x.claude_code_version} model=${x.model} permMode=${x.permissionMode}
|
|
15
|
+
`))}catch{O.trim()&&!O.startsWith("{")&&(u+=O+`
|
|
16
|
+
`,t(O+`
|
|
17
|
+
`,u))}});let A=await M,H=_.end();if(H&&(R+=H),v)return{content:"",error:f||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&A.stdout&&(u=typeof A.stdout=="string"?A.stdout:""),A.exitCode!==0&&!u){let D=typeof A.stderr=="string"?A.stderr:"",L=A,O;return L.timedOut?O=`Claude Code timed out after ${Math.round(p/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:L.signal?O=D.trim()||`Claude Code killed by signal ${L.signal}`:L.code==="ENOENT"||/ENOENT|spawn claude/i.test((L.shortMessage||"")+" "+D)?O=Yn():O=D.trim()||`Claude Code exited with code ${L.exitCode??"unknown"}`,{content:"",...q(O),duration:Date.now()-a}}return w?{content:"",...q(w),duration:Date.now()-a,usage:g,contextTokens:b,numTurns:T,billedModel:l,claudeSessionId:h}:{content:u,duration:Date.now()-a,usage:g,contextTokens:b,numTurns:T,billedModel:l,claudeSessionId:h}}catch(p){return{content:u||"",...q(p.message),duration:Date.now()-a,usage:g,contextTokens:b,numTurns:T,billedModel:l,claudeSessionId:h}}}async function Xr(r,e,t,n){let s=Date.now(),o=ie(r,e,t),i=Gn(Ve(zn(),"agentx-codex-")),a=Ve(i,"last-message.txt"),c=Zn(r,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),u=await et("codex",c,{cwd:r.workspace,timeout:d,reject:!1,env:tt(r,e),extendEnv:!1,stdin:"ignore"}),l=qr(u.stdout);if(u.exitCode!==0||l.apiError){let h=u,b;return h.timedOut?b=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:l.apiError?b=l.apiError:h.signal?b=u.stderr.trim()||`Codex CLI killed by signal ${h.signal}`:h.code==="ENOENT"||/ENOENT|spawn codex/i.test((h.shortMessage||"")+" "+u.stderr)?b=Ze():b=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${h.exitCode??"unknown"}`,{content:"",...q(b),duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}let g="";try{g=Jn(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Ze():d?.message;return{content:"",...q(u||"Codex CLI failed"),duration:Date.now()-s}}finally{Qn(i,{recursive:!0,force:!0})}}async function Vr(r,e,t,n,s,o){let i=Date.now(),a=ie(r,e,n),c=Gn(Ve(zn(),"agentx-codex-")),d=Ve(c,"last-message.txt"),u=Zn(r,a,!0,e.model,e.systemPromptAppend,d,s),l="",g,h,b,T;try{let w=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=et("codex",u,{cwd:r.workspace,timeout:w,reject:!1,env:tt(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let I="",M="",v=!1,f=new $e("utf8"),R=new $e("utf8"),_=Math.min(w,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),A,H=()=>{A&&clearTimeout(A),A=setTimeout(()=>{v=!0,p.kill("SIGTERM",{forceKillAfterTimeout:5e3})},_)};H(),p.stderr?.on("data",S=>{H(),M+=R.write(S),M.length>16e3&&(M=M.slice(-16e3))}),p.stdout?.on("data",S=>{H(),I+=f.write(S);let k=I.split(`
|
|
18
|
+
`);I=k.pop()||"";for(let E of k)if(E.trim())try{let U=JSON.parse(E);if(o)try{o(U)}catch{}g=$t(U)||g,h=es(U)||h,b=Mt(U)||b,T=ts(U)||T;let P=Br(U);if(P&&P!==l){let F=P.startsWith(l)?P.slice(l.length):P;l=P.startsWith(l)?P:l+P,F&&t(F,l)}}catch{l+=E+`
|
|
19
|
+
`,t(E+`
|
|
20
|
+
`,l)}});let D=await p;A&&clearTimeout(A);let L=f.end();L&&(I+=L);let O=R.end();if(O&&(M+=O),D.exitCode!==0&&!l||T){let S=M||(typeof D.stderr=="string"?D.stderr:""),k=D,E;return v?E=`Codex CLI produced no output for ${Math.round(_/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?E=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:T?E=T:k.signal?E=S.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+S)?E=Ze():E=S.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...q(E),duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:b||s}}let x="";try{x=Jn(d,"utf8").trim()}catch{}if(x&&x!==l){let S=x.startsWith(l)?x.slice(l.length):x;l=x,S&&t(S,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:b||s}}catch(w){let p=/ENOENT|spawn codex/i.test(w?.message||"")?Ze():w?.message;return{content:l,...q(p||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:b||s}}finally{Qn(c,{recursive:!0,force:!0})}}async function Zr(r,e,t,n,s,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=ie(r,e,n),u=Ur(r,d,e.model,e.systemPromptAppend,e.freshSession?void 0:s),l="",g,h=e.freshSession?void 0:s,b,T,w=!0,p;try{let I=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),M=Kr(r,e);if(r.persistentProcess)try{T=await Fn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:r.workspace,env:M,model:e.model||r.model,permission:r.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",T.url),M=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(S){if(!(S instanceof se))throw S;S.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:S.message})}if(i?.aborted)throw new Error("task cancelled by operator");let v=et("opencode",u,{cwd:r.workspace,timeout:I,reject:!1,env:M,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let f=!1,R,_=()=>{T?.invalidate(),f=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{v.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",_,{once:!0}),p=()=>i?.removeEventListener("abort",_),i?.aborted&&_();let A="",H="",D=new $e("utf8"),L=new $e("utf8"),O=S=>{if(S.trim())try{let k=JSON.parse(S);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(h=k.sessionID);let E=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;E&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),l+=E,t?.(E,l));let U=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;U&&a?.(U);let P=k.type==="step_finish"?k.part?.tokens:void 0;P&&(g={inputTokens:oe(P.input),outputTokens:oe(P.output),cacheReadTokens:oe(P.cache?.read),cacheCreateTokens:oe(P.cache?.write)}),b=Wr(k)||b}catch{l+=S+`
|
|
21
|
+
`,t?.(S+`
|
|
22
|
+
`,l)}};v.stdout?.on("data",S=>{A+=D.write(S);let k=A.split(`
|
|
23
|
+
`);A=k.pop()||"";for(let E of k)O(E)}),v.stderr?.on("data",S=>{H+=L.write(S)});let x=await v;if(i&&i.removeEventListener("abort",_),A+=D.end(),A.trim()&&O(A),H+=L.end(),f)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(x.exitCode!==0||b){let S=x,k;return S.timedOut?k=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?k=b:S.code==="ENOENT"||/ENOENT|spawn opencode/i.test((S.shortMessage||"")+" "+H)?k=Kn():k=H.trim()||`OpenCode exited with code ${S.exitCode??"unknown"}`,{content:"",...q(k),duration:Date.now()-c,usage:g,opencodeSessionId:h}}return w=!1,{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||r.model,opencodeSessionId:h}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let M=/ENOENT|spawn opencode/i.test(I?.message||"")?Kn():I?.message;return{content:l,...q(M||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:h}}finally{p?.(),T?.release(w)}}async function eo(r,e,t,n){let s=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ie(r,e,n),c="",d=i({prompt:a,options:{model:e.model||r.model,cwd:r.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-s}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-s}}}async function to(r,e,t,n,s,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,h=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(w))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let b=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);b.unref?.();let T=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=r.provider||"claude-code",p=n?`${n}
|
|
24
|
+
|
|
25
|
+
${e.message}`:e.message,I=e.context?.sender,M=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),v=e.context?.channel==="web-chat"&&M?{userId:I,agentId:e.agentId||"acme-public"}:void 0,f=Tn(r),R=Object.keys(f).length>0,_={task:p,cwd:r.workspace,provider:w,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:v,providerOpts:o,abortSignal:l.signal,mcpServers:R?f:void 0};if(s){let{generateStream:O}=await import("./agent-SPE7Q7MD.js"),x="",S,k,E,U;for await(let P of O(_)){if(c)try{c(P)}catch{}if(P.type==="text_delta")x+=P.text,s(P.text,x);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==x){let F=P.result.content.slice(x.length);F?(x=P.result.content,s(F,x)):x=P.result.content}S=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(E=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==x){let F=P.result.content.slice(x.length);F?(x=P.result.content,s(F,x)):x=P.result.content}P.result.tokensUsed!=null&&(S=P.result.tokensUsed)}else P.type==="error"&&(U=P.error)}return U&&!x?g?T():U==="cancelled"||a?.aborted||l.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||E===void 0)&&S&&(k=Math.round(S*.7),E=S-k),{content:x||"Done.",tokensUsed:S,usage:k!==void 0||E!==void 0?{inputTokens:k||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:A}=await import("./agent-SPE7Q7MD.js"),H=await A(_),D=H.inputTokens,L=H.outputTokens;if((D===void 0||L===void 0)&&H.tokensUsed){let O=H.tokensUsed;D=Math.round(O*.7),L=O-D}return{content:H.content||"Done.",tokensUsed:H.tokensUsed,usage:D!==void 0||L!==void 0?{inputTokens:D||0,outputTokens:L||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return g?T():w?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",h)}}async function no(r,e,t,n,s,o,i){let a=Xe();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",u=e.context?.chatId||e.context?.group||e.context?.sender||"default",l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,h=!1;try{let x=a.list().length;g=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:r.workspace,model:e.model||r.model,permissionMode:r.permissionMode,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>x}catch(x){return x instanceof fe,null}h&&Rt(e.agentId,r,e.model,n,"persistent");let b=ie(r,e,t),T="",w,p,I,M,v,f,R,_="",A="",H=x=>{if(!i||!x)return;let S;if(A&&x.startsWith(A)?S=x.slice(A.length):S=_&&!_.endsWith(`
|
|
26
|
+
`)?`
|
|
27
|
+
|
|
28
|
+
${x}`:x,A=x,!!S){_+=S;try{i(S,_)}catch{}}},D=!1,L=()=>{D=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?L():o.addEventListener("abort",L,{once:!0}));let O=!1;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4);for await(let S of g.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:x})){if(O=!0,s)try{s(S.raw)}catch{}if(S.type==="assistant"){let k=S.raw.message?.content??[];for(let U of k)U.type==="text"&&typeof U.text=="string"?(T=U.text,H(U.text)):U.type==="tool_use"&&(A="");let E=S.raw.message?.usage;if(E){let U=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);U>0&&(M=U)}}if(S.type==="result"){let k=S.raw;if(k.is_error){let E=q(typeof k.result=="string"?k.result:"claude error");w=E.error,p=E.errorKind}else typeof k.result=="string"&&k.result.length>0&&(T=k.result,_||H(k.result));typeof k.session_id=="string"&&(R=k.session_id),k.usage&&(I={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"&&(v=k.num_turns),typeof k.message?.model=="string"?f=k.message.model:typeof k.model=="string"&&(f=k.model)}}}catch(x){if(D)w="task cancelled by operator",p="cancelled";else if(O)if(x instanceof Ae){let S=q(`Claude Code timed out after ${Math.round(x.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||e.agentId}" if tasks need longer.`);w=S.error,p=S.errorKind}else{let S=q(`persistent claude process error: ${x?.message||String(x)}`);w=S.error,p=S.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${x?.message||x}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",L),null}finally{o&&o.removeEventListener("abort",L)}return D&&!w&&(w="task cancelled by operator",p="cancelled"),{content:D?"":T,error:w,errorKind:p,duration:Date.now()-c,usage:I,contextTokens:M,numTurns:v,billedModel:f,claudeSessionId:R}}async function ns(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await no(r,e,s,o,i,a,n);if(d!==null)return d}return n?Yr(r,e,n,s,o,i,a):zr(r,e,s,o,a);case"codex-cli":if(r.persistentProcess)try{let d=await Hn.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:r.workspace,env:tt(r,e),args:Vn(),model:e.model||r.model,bypass:r.permissionMode==="bypassPermissions",prompt:At(ie(r,e,s),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...d,...d.error?q(d.error):{}}}catch(d){if(!(d instanceof re))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Vr(r,e,n,s,o,i):Xr(r,e,s,o);case"opencode":return Zr(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?eo(r,e,u,s):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=r.provider||"claude-code",u=t[d],l=u?.apiKey;return to(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as me,writeFileSync as ss,mkdirSync as so,existsSync as Pt,readdirSync as Dt}from"fs";import{resolve as ye}from"path";var _t=12e3,Me=30,ro=720,oo=40,io=18e4,ao="[Compacted conversation summary",co=7*864e5,uo=[/\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 lo(r){return r?uo.some(e=>e.test(r)):!1}var go=[{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 os(r){if(!r)return null;let e=0;for(let t of go)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function rs(r,e,t,n){if(r.length===0)return!1;let s=r[r.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function is(r,e){let t=(r??[]).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(r,e,t){if(t<=0)return[];let n=(r??[]).filter(i=>i.role==="user"),s=n[n.length-1],o=(s&&s.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function po(r){let e=r.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let s=Math.floor(n/15)*15;return`${t}:${s.toString().padStart(2,"0")}`}var nt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=ye(e,".agentx/sessions"),Pt(this.sessionsDir)||so(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??ro),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??oo),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??io)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,s){if(s?.length){let u=this.getSession(e,t,n);u.messages.length===0&&this.appendSeededMessages(u,s);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 u=await c.seedHistory(n,{maxMessages:Me,maxChars:_t});u.length>0&&this.appendSeededMessages(a,u)}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 s=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}),s++);s!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let s=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${s}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return ye(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let s=this.sessionKey(e,t,n);if(this.cache.has(s))return this.cache.get(s);let o=this.sessionFile(s);if(Pt(o))try{let d=JSON.parse(me(o,"utf-8"));return this.cache.set(s,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:s,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(s,c),this.save(c),c}loadPreviousDaySession(e,t,n){let s=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${s}`,i=this.sessionFile(o);if(!Pt(i))return null;try{return JSON.parse(me(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);rs(i.messages,"user",s,o)||(i.messages.push({role:"user",name:s,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,s){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(s||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,s){let o=this.getSession(e,t,n);rs(o.messages,"agent",e,s)||(o.messages.push({role:"agent",name:e,content:s,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,s){let o=this.getSession(e,t,n);o.claudeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.codexSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.opencodeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,s={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,s.maxMessages??Me),a=Math.max(200,s.maxChars??_t),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let h=o.messages[g];if(d+=h.content.length,c.push(h),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let h=po(g.timestamp);h!==l&&(u.push(`\u2014 ${h} \u2014`),l=h);let b=g.name||(g.role==="user"?"User":"Agent");u.push(`${b}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
29
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let s=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??s,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Dt(this.sessionsDir).filter(v=>v.startsWith(`${a}:`)&&v.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(v=>{let f=v.match(l);if(!f)return!1;let R=f[1];return R>=d&&R<=u}),h=[],b=0,T=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let v of g){let f;try{f=JSON.parse(me(ye(this.sessionsDir,v),"utf-8"))}catch{continue}if(f.agentId===e.agentId&&!(e.channel&&f.channel!==e.channel)&&!(e.chatId&&f.chatId!==e.chatId))for(let R of f.messages)b++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(w&&R.role==="user"&&!w.has(R.name??"")||T&&!R.content.toLowerCase().includes(T)||h.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:f.channel,chatId:f.chatId,day:f.day,sessionFile:v}))}h.sort((v,f)=>f.ts.localeCompare(v.ts));let p=h.slice(0,t),I=p.length>0?p[p.length-1].ts:null,M=h.length>t;return{turns:p,oldestTs:I,hasMore:M,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Me,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),o;try{o=Dt(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=s:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(me(ye(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let h of g.messages)!h.timestamp||h.timestamp<n||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}sessionIdleMs(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?null:Date.now()-new Date(s.updatedAt).getTime()}isSessionStale(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:Date.now()-new Date(s.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,s){if(s!==void 0&&s!==""&&!lo(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Dt(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 u=JSON.parse(me(ye(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),h=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,b=l.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${h} (${u.channel}):
|
|
30
|
+
${b.join(`
|
|
31
|
+
`)}`)}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(`
|
|
32
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,s){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,s);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 s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(ao)}clearClaudeSessionId(e,t,n){let s=this.getSession(e,t,n);delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}clearSession(e,t,n){let s=this.getSession(e,t,n);s.messages=[],delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}shouldRotateByTurns(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.lastTurnContextTokens??s.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,s,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return ye(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(me(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,s,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:s,reason:o,capturedAt:new Date().toISOString()},ss(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let s=this.readRotationMemos()[`${e}:${t}:${n}`];if(!s?.memo)return null;let o=Date.now()-Date.parse(s.capturedAt);return!Number.isFinite(o)||o>co?null:s}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 s=this.getSession(e,t,n);return s.lastTurnContextTokens??s.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>Me&&(e.messages=e.messages.slice(-Me));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>_t&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let s=t-e.messages.length;s>0&&de.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${s} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);ss(t,JSON.stringify(e,null,2))}catch{}}};var ho=new Set(["cron","a2a","workflow","selftest"]),fo=[[/^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 cs(r){if(r.responseLength<=50)return{capture:!1,reason:"response too short"};let t=(r.channel??"").toLowerCase().split("@")[0];if(ho.has(t))return{capture:!1,reason:`machine channel: ${t}`};let n=r.content.slice(0,400);for(let[s,o]of fo)if(s.test(n))return{capture:!1,reason:o};return{capture:!0}}var st=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)||[],s=t-36e5,o=n.filter(c=>c>s),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,s=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=s)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=s-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(s=>s>t-6e4).length,lastHour:n.filter(s=>s>t-36e5).length}}};import{readFileSync as Re,writeFileSync as ds,appendFileSync as mo,existsSync as be,mkdirSync as yo}from"fs";import{resolve as we}from"path";var ls={"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}},gs=2e5,bo=1.5;function wo(r){let e=r.toLowerCase(),t=(...n)=>n.some(s=>e.includes(s));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 ps(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>gs?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:r.inputTokens,tier2OutputTokens:r.outputTokens,tier2CacheReadTokens:r.cacheReadTokens,tier2CacheCreateTokens:r.cacheCreateTokens}:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheCreateTokens:r.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var us=500,xo=".agentx/pricing/custom.json",xe=class{dir;cache=null;pricing;constructor(e=we(process.cwd(),".agentx/usage")){this.dir=e,yo(this.dir,{recursive:!0}),this.pricing=To()}getPricing(){return this.pricing}static calculateCost(e,t,n=ls){let s=wo(t||e.model||"claude-sonnet"),o=n[s]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,u=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,l=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return u+l*bo}cost(e,t){return xe.calculateCost(e,t,this.pricing)}record(e,t,n,s,o,i,a,c,d){let u=this.today(),l=u.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:[]};l.tasks++,l.totalDuration+=t,a&&(l.model=a);let g=0,h=0,b=0,T=0,w=0,p=0,I=0,M=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>gs?(w=n.inputTokens,p=n.outputTokens,I=n.cacheReadTokens,M=n.cacheCreateTokens):(g=n.inputTokens,h=n.outputTokens,b=n.cacheReadTokens,T=n.cacheCreateTokens):s!==void 0&&o!==void 0&&(g=Math.ceil(s/4),h=Math.ceil(o/4)),l.inputTokens+=g,l.outputTokens+=h,l.cacheReadTokens+=b,l.cacheCreateTokens+=T,l.tier2InputTokens=(l.tier2InputTokens||0)+w,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+I,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+M,i&&l.errors++,l.byChannel||(l.byChannel={});let v=(c||"other").toLowerCase(),f=l.byChannel[v]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};f.tasks++,f.totalDuration+=t,f.inputTokens+=g,f.outputTokens+=h,f.cacheReadTokens+=b,f.cacheCreateTokens+=T,f.tier2InputTokens+=w,f.tier2OutputTokens+=p,f.tier2CacheReadTokens+=I,f.tier2CacheCreateTokens+=M,i&&f.errors++,l.byChannel[v]=f,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>us&&l.sessionKeys.splice(0,l.sessionKeys.length-us))),u.agents[e]=l,this.save(u)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(be(t))try{return this.cache=JSON.parse(Re(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!be(t))return null;try{return JSON.parse(Re(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 s=0,o=0,i=0,a=0,c=0,d=0,u="",l=0,g={},h={},b={};for(let[T,w]of Object.entries(n.agents)){let p=this.cost(w);g[T]=p,s+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=T);let I=w.sessionKeys?.length||0;h[T]={sessions:I,avgTasksPerSession:I>0?w.tasks/I:w.tasks};for(let[M,v]of Object.entries(w.byChannel||{})){let f=this.cost(v,w.model);b[M]=(b[M]||0)+f}}return{date:t,totalTasks:s,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:u,topCost:l,agentCosts:g,agentSessionStats:h,byChannel:b}}appendToTokenCosts(e,t){let n=t||we(process.cwd(),".agentx/TOKEN_COSTS.md"),s=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],[,u])=>u-d).map(([d,u])=>{let l=e.agentSessionStats[d],g=l&&l.sessions>0?` (${l.sessions}s, ${l.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${s(u)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,u])=>u-d).map(([d,u])=>`${d}: $${s(u)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${s(e.totalCost)} | ${i} | ${a} |`;be(n)?mo(n,c+`
|
|
33
|
+
`):ds(n,`# Token Costs
|
|
34
|
+
|
|
35
|
+
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
36
|
+
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
37
|
+
|
|
38
|
+
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
39
|
+
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
40
|
+
`+c+`
|
|
41
|
+
`)}hasTokenCostsEntry(e,t){let n=t||we(process.cwd(),".agentx/TOKEN_COSTS.md");if(!be(n))return!1;try{let s=Re(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||we(process.cwd(),".agentx/TOKEN_COSTS.md");if(!be(t))return null;try{let s=Re(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(s.length===0)return null;let o=s.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,s=[],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),s.push(c))}return s}summary(e=7){let t=0,n=0,s=0,o=0,i=0,a=0,c=0,d={},u={};for(let b=0;b<e;b++){let T=new Date(Date.now()-b*864e5).toISOString().slice(0,10),w=this.getDate(T);if(w)for(let[p,I]of Object.entries(w.agents)){let M=this.cost(I);t+=I.tasks;let v=(I.inputTokens||0)+(I.tier2InputTokens||0),f=(I.outputTokens||0)+(I.tier2OutputTokens||0),R=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),_=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=v,s+=f,o+=R,i+=_,a+=I.errors,c+=M;let A=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};A.tasks+=I.tasks,A.input+=v,A.output+=f,A.cacheRead+=R,A.cacheCreate+=_,A.total=A.input+A.output+A.cacheRead+A.cacheCreate,A.totalDuration+=I.totalDuration,A.avgDuration=A.totalDuration/A.tasks,A.cost+=M,A.sessions+=I.sessionKeys?.length||0,I.model&&(A.model=I.model),d[p]=A;for(let[H,D]of Object.entries(I.byChannel||{})){let L=this.cost(D,I.model),O=u[H]||{tasks:0,cost:0};O.tasks+=D.tasks,O.cost+=L,u[H]=O}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,h={};for(let[b,T]of Object.entries(d))h[b]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:l,totalInput:n,totalOutput:s,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:u,sessionStats:h}}filePath(e){return we(this.dir,`${e}.json`)}save(e){try{ds(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function To(){let r=JSON.parse(JSON.stringify(ls));try{let e=we(process.cwd(),xo);if(!be(e))return r;let t=JSON.parse(Re(e,"utf-8"));for(let[n,s]of Object.entries(t))r[n]||(r[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(r[n],s)}catch{}return r}var ko={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}},hs=4;function fs(r,e=ko){let t=So(r,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,o=e.totalBudget*hs;for(let i of t){if(!i.content)continue;let a=i.maxTokens*hs,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(s+c.length>o){let d=o-s;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),s+=c.length}return n.join(`
|
|
42
|
+
|
|
43
|
+
`)}function So(r,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(Io(r,t("channel",200))),n.push(vo(r,t("scope",200))),r.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:r.landscape,tags:["landscape","world-model"]}),r.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:r.systemPrompt.split(`
|
|
44
|
+
`)[0],tags:["identity",r.agentId]}),r.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:r.bootstrapContext,tags:["bootstrap","identity","personality"]}),r.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:r.references,tags:["references","verified","deterministic"]}),r.intent&&r.intent.path.length>0){let i=[`[Intent path: ${r.intent.pathLabel}${r.intent.status==="pending"?" (pending approval)":""}]`],a=r.intent.path[r.intent.path.length-1],c=r.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,l])=>` ${u}: ${l}`).join(`
|
|
45
|
+
`);i.push(d)}r.intent.leaf?.input&&i.push(` input: ${r.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
46
|
+
`),tags:["intent",...r.intent.path]})}else{let i=Co(r.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let s=[];r.replyToText&&s.push(`[Replying to]: ${r.replyToText.slice(0,300)}`),r.mediaPath&&(s.push(`[Attached file: ${r.mediaPath}]`),s.push(`[File type: ${r.mediaType||"unknown"}]`),r.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):r.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),r.issueMR&&s.push(`[${r.issueMR.type} #${r.issueMR.iid}: ${r.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
47
|
+
`),tags:["artifacts",...r.mediaType?["media"]:[]]}),r.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:r.skillInjection,tags:["skills","auto-inject"]}),r.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:r.patternContext,tags:["patterns","behavioral","self-improving"]}),r.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:r.procedureContext,tags:["procedures","sop"]}),r.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:r.memoryContext,tags:["memory","persistent"]});let o=r.groupHistory||r.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),r.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:r.crossChatContext,tags:["history","cross-chat"]}),r.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:r.longMemoryRecall,tags:["history","long-memory"]}),r.handoverNote){let i=[`[Handover] You are taking over this conversation from ${r.handoverNote.fromAgent}.`];r.handoverNote.summary&&i.push(`Operator summary: ${r.handoverNote.summary}`),i.push(`Handover time: ${r.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
48
|
+
`),tags:["handover",r.handoverNote.fromAgent]})}return r.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 (${r.rotationMemo.reason}, ${r.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,r.rotationMemo.memo].join(`
|
|
49
|
+
`),tags:["continuity","rotation-memo"]}),r.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:r.wikiContext,tags:["wiki","knowledge"]}),n}function Io(r,e){let t=[`Channel: ${r.channel}`];r.chatId&&t.push(`Chat ID: ${r.chatId} (use this verbatim in /recall, /send)`);let n=[],s=[r.channel];switch(r.channel){case"telegram":r.agentHandle&&t.push(`Your handle: ${r.agentHandle}`),t.push(`From: ${r.sender}`),r.senderId&&t.push(`Telegram user ID: ${r.senderId}`),r.senderUsername&&t.push(`Username: @${r.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: ${r.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: ${r.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"),s.push("code-review");break;case"discord":t.push(`From: ${r.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:r.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.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(`
|
|
50
|
+
`),tags:s,rules:n}}function vo(r,e){let t=[],n=[];if(r.channelScope==="group"&&r.groupName?(t.push(`Group: ${r.groupName}`),n.push("group",r.groupName)):r.channelScope==="project"&&r.projectPath?(t.push(`Project: ${r.projectPath}`),n.push("project",r.projectPath)):r.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),r.channelMeta){let s=r.channelMeta;if(s.agents?.length&&(t.push(`[Verified bots in this chat: ${s.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.")),s.project&&t.push(`Project: ${s.project}`),s.issue&&t.push(`${s.issue.type} #${s.issue.iid}${s.issue.title?`: ${s.issue.title}`:""}`),s.facts?.length)for(let o of s.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
51
|
+
`),tags:n}}function Co(r){let e=[],t=r.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 Ao,writeFileSync as ms,appendFileSync as $o,mkdirSync as Mo,existsSync as ys}from"fs";import{resolve as Ot}from"path";var bs=200,Ro=7,rt=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=Ot(e,".agentx/memory"),ys(this.memoryDir)||Mo(this.memoryDir,{recursive:!0})}filePath(e){return Ot(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()};$o(this.filePath(e),JSON.stringify(n)+`
|
|
52
|
+
`)}getAll(e){let t=this.filePath(e);if(!ys(t))return[];try{return Ao(t,"utf-8").split(`
|
|
53
|
+
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}findRelevant(e,t,n=8){let s=this.getAll(t);if(s.length===0)return[];let o=s.map(h=>`${h.keywords.join(" ")} ${h.content}`),i=Ot(this.memoryDir,`${t}_bm25_cache.json`),a=qe(o,i),c=Be(e,a),d=new Map(c.map(h=>[h.docIndex,h.score])),l=s.map((h,b)=>{let T=d.get(b)??0;return h.category==="secret"&&(T+=2),h.category==="commitment"&&(T+=1),{memory:h,score:T}}).filter(h=>h.score>0);if(l.length===0)return s.slice(-n);let g=l.sort((h,b)=>b.score-h.score).slice(0,n).map(h=>h.memory);if(g.length>0)try{this.recordAccess(t,g.map(h=>h.id))}catch{}return g}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],n=t[0].length;for(let s of e){let i=!s.source.chatId.startsWith("-")&&/^\d+$/.test(s.source.chatId)?"DM":s.source.chatId,a=`- [${s.category}] ${s.content} (${i}, ${s.source.date})`;if(n+a.length>2400)break;t.push(a),n+=a.length}return t.push("[End Memory]"),t.join(`
|
|
54
|
+
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)if(s.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&&ms(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
55
|
+
`)+`
|
|
56
|
+
`)}getDueForReview(e,t=5){let n=this.getAll(e),s=Date.now();return n.filter(o=>o.category==="task-state"?!1:o.nextReview?new Date(o.nextReview).getTime()<=s:!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 s of t){let o=Math.round((Date.now()-new Date(s.createdAt).getTime())/864e5);n.push(`- [${s.category}] ${s.content} (${o}d old, accessed ${s.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
57
|
+
`)}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(),s=Ro*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()<s:!0),t.length>bs&&(t=t.slice(-bs));let o=this.filePath(e);ms(o,t.map(i=>JSON.stringify(i)).join(`
|
|
58
|
+
`)+`
|
|
59
|
+
`)}};import{existsSync as Pe,mkdirSync as Po,readdirSync as Do,readFileSync as _o,unlinkSync as Et,writeFileSync as ot}from"fs";import{resolve as ae}from"path";var ue=["user","feedback","project","reference"],it=class{baseDir;constructor(e={}){let t=e.baseDir??ae(process.cwd(),".agentx");this.baseDir=ae(t,"agent-memory")}dirFor(e){let t=Lt(e),n=ae(this.baseDir,t);return Po(n,{recursive:!0}),n}fileFor(e,t,n){return ae(this.dirFor(e),`${t}_${Lt(n)}.md`)}indexPath(e){return ae(this.dirFor(e),"MEMORY.md")}save(e){if(!ue.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(),s=n,o=De(t);if(o){let a=Nt(o);a&&(s=a.createdAt)}let i={name:Lt(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:s,updatedAt:n};return ot(t,Oo(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of ue){let s=this.fileFor(e,n,t);if(!Pe(s))continue;let o=Nt(De(s)??"");if(o)return o}return null}list(e){let t=this.dirFor(e);if(!Pe(t))return[];let n=[];for(let s of Do(t,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name==="MEMORY.md")continue;let o=Nt(De(ae(t,s.name))??"");o&&n.push(o)}return n.sort((s,o)=>{let i=ue.indexOf(s.type),a=ue.indexOf(o.type);return i!==a?i-a:s.name.localeCompare(o.name)})}remove(e,t){let n=!1;for(let s of ue){let o=this.fileFor(e,s,t);Pe(o)&&(Et(o),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return De(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),s=ae(t,".agentx-memory.md");n?ot(s,n+`
|
|
60
|
+
`):Pe(s)&&Et(s);let o=ae(t,"CLAUDE.md"),i="<!-- AGENTX-MEMORY-START \u2014 auto-managed by agentx; edit via `agentx memory` -->",a="<!-- AGENTX-MEMORY-END -->",c=n?`${i}
|
|
61
|
+
${n}
|
|
62
|
+
${a}`:"",d=De(o)??"",u=d.indexOf(i),l=d.indexOf(a),g;if(u>=0&&l>u){let h=d.slice(0,u).replace(/\n+$/,""),b=d.slice(l+a.length).replace(/^\n+/,"");g=c?[h,c,b].filter(Boolean).join(`
|
|
63
|
+
|
|
64
|
+
`)+`
|
|
65
|
+
`:[h,b].filter(Boolean).join(`
|
|
66
|
+
|
|
67
|
+
`)+(h||b?`
|
|
68
|
+
`:"")}else if(c)g=d?d.replace(/\n+$/,"")+`
|
|
69
|
+
|
|
70
|
+
`+c+`
|
|
71
|
+
`:c+`
|
|
72
|
+
`;else return;ot(o,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);Pe(o)&&Et(o);return}let n={user:[],feedback:[],project:[],reference:[]};for(let o of t)n[o.type].push(o);let s=[];s.push(`# Memory \u2014 ${e}`,""),s.push("This is the agent's experiential memory: user preferences,"),s.push("feedback, project-specific context, and external references."),s.push("Updated via `agentx memory` CLI or by the agent itself.");for(let o of ue){let i=n[o];if(i.length){s.push("",`## ${Lo(o)}`,"");for(let a of i)s.push(`- **${a.name}** \u2014 ${a.description} _(updated ${a.updatedAt.slice(0,10)})_`)}}s.push(""),ot(this.indexPath(e),s.join(`
|
|
73
|
+
`))}};function Oo(r){return["---",`name: ${r.name}`,`description: ${Eo(r.description)}`,`type: ${r.type}`,`created: ${r.createdAt}`,`updated: ${r.updatedAt}`,"---",""].join(`
|
|
74
|
+
`)+r.body+`
|
|
75
|
+
`}function Nt(r){if(!r.startsWith(`---
|
|
76
|
+
`))return null;let e=r.indexOf(`
|
|
77
|
+
---
|
|
78
|
+
`,4);if(e<0)return null;let t=r.slice(4,e),n=r.slice(e+5).replace(/^\n+/,"").trimEnd(),s={};for(let o of t.split(`
|
|
79
|
+
`)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=No(o.slice(i+1).trim());s[a]=c}return!s.name||!s.type||!s.description||!ue.includes(s.type)?null:{name:s.name,type:s.type,description:s.description,body:n,createdAt:s.created??"",updatedAt:s.updated??s.created??""}}function Eo(r){return/[:#\n]/.test(r)?`"${r.replace(/"/g,'\\"')}"`:r}function No(r){return r.startsWith('"')&&r.endsWith('"')&&r.length>=2?r.slice(1,-1).replace(/\\"/g,'"'):r}function Lt(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function Lo(r){return r.charAt(0).toUpperCase()+r.slice(1)}function De(r){try{return _o(r,"utf-8")}catch{return null}}var at=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let s=this.key(e,t,n);return this.queues.has(s)||this.queues.set(s,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(s)}setMode(e,t,n,s){this.getOrCreate(e,t,n).mode=s}onFlush(e,t,n,s){this.getOrCreate(e,t,n).onFlush=s}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let s=this.getOrCreate(e,t,n);return s.running?!1:(s.running=!0,!0)}enqueue(e,t,n,s){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(s),o.mode}}async markDone(e,t,n){let s=this.getOrCreate(e,t,n);if(s.running=!1,s.pending.length===0)return[];let o=[...s.pending];switch(s.pending=[],s.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(`
|
|
80
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return s.onFlush&&await s.onFlush([a]),[a]}case"followup":return s.onFlush&&await s.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 s=this.key(e,t,n);this.queues.delete(s)}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 Fo,writeFileSync as ws,appendFileSync as Ho,mkdirSync as jo,existsSync as xs}from"fs";import{resolve as Ft}from"path";var Ts=50,Uo="claude-haiku-4-20250514",Wo=`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.
|
|
81
|
+
|
|
82
|
+
Extract patterns like:
|
|
83
|
+
- "When asked about X, the approach that works is Y"
|
|
84
|
+
- "User prefers Z style of communication"
|
|
85
|
+
- "For deployment tasks, always check A before doing B"
|
|
86
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
87
|
+
|
|
88
|
+
SKIP:
|
|
89
|
+
- Factual information (names, dates, URLs)
|
|
90
|
+
- Routine task completions
|
|
91
|
+
- Greetings or small talk
|
|
92
|
+
|
|
93
|
+
Output a JSON array:
|
|
94
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
95
|
+
|
|
96
|
+
If nothing worth extracting, output: []`,ct=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ft(e,".agentx/patterns"),xs(this.patternsDir)||jo(this.patternsDir,{recursive:!0})}filePath(e){return Ft(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!xs(t))return[];try{return Fo(t,"utf-8").split(`
|
|
97
|
+
`).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()};Ho(this.filePath(e),JSON.stringify(n)+`
|
|
98
|
+
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let o=s.map(u=>`${u.context} ${u.pattern}`),i=Ft(this.patternsDir,`${t}_bm25_cache.json`),a=qe(o,i),d=Be(e,a).slice(0,n).map(u=>s[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.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(`
|
|
99
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return s.filter(c=>i.includes(c)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)s.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&ws(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
100
|
+
`)+`
|
|
101
|
+
`)}prune(e){let t=this.getAll(e);t.length<=Ts||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,Ts),ws(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
102
|
+
`)+`
|
|
103
|
+
`))}};async function ks(r,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-KO2DODIO.js"),c=(await o("claude").generate([{role:"system",content:Wo},{role:"user",content:`User: ${e.slice(0,500)}
|
|
104
|
+
|
|
105
|
+
Agent: ${t.slice(0,1e3)}`}],{model:Uo,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 u of d)s.hasSimilar(r,u.pattern)||s.addPattern(r,{agentId:r,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:n});Math.random()<.05&&s.prune(r)}}import{EventEmitter as Ko}from"events";var jt=class{inner=new Ko;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}},Ht;function ee(){return Ht||(Ht=new jt),Ht}pn();pn();var Ss=["manual","notify","auto"];function Bo(r){return typeof r=="string"&&Ss.includes(r)}var Ut={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var _e=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...Ut,...e}}options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),s=this.sessions.get(e);if(s)return s.lastSeenAt=n,t.cwd&&(s.cwd=t.cwd),t.model&&(s.model=t.model),s;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 s=this.sessions.get(e);if(s){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));return s.agentIds.includes(t)||s.agentIds.push(t),n&&(s.mode=n),s}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(s=>s!==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 s={id:Ge(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:qo(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(s.id,s),new Promise(o=>{this.waiters.set(s.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 s=this.pending(e)[0];if(!(!s||s.state!=="pending"))return s.state="claimed",s.claimedAt=t,n.awaitingAnswer=s.id,n.lastSeenAt=t,n.drainedThisTurn++,s}answer(e,t,n=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let o=this.items.get(s.awaitingAnswer);if(s.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 s=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!s||s.state!=="claimed"))return s.state="pending",s.claimedAt=void 0,n.lastSeenAt=t,s}expire(e,t,n=Date.now()){let s=this.items.get(e);if(!s||s.state!=="pending"&&s.state!=="claimed")return!1;let o=this.sessions.get(s.sessionId);return o?.awaitingAnswer===s.id&&(o.awaitingAnswer=void 0),this.settle(s,"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[s,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(s),n++);return n}settle(e,t,n,s){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:s??"expired"}))}};function qo(r,e){return r.length<=e?r:`${r.slice(0,e)}
|
|
106
|
+
\u2026[truncated ${r.length-e} chars]`}var Wt;function Is(){return Wt||(Wt=new _e),Wt}import{readFileSync as Go}from"fs";import{homedir as Jo}from"os";import{join as Qo}from"path";var Oe=null,zo=6e4;function Yo(){try{let r=Qo(Jo(),".claude.json"),e=Go(r,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function Xo(r,e=Date.now()){if(!r)return{available:!0,checkedAt:e,unknown:!0};let t=typeof r.cachedExtraUsageDisabledReason=="string"?r.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Vo(r=!1){let e=Date.now();return!r&&Oe&&e-Oe.checkedAt<zo||(Oe=Xo(Yo(),e)),Oe}function vs(r){let e=Vo();return e.available||r?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 Cs={warnRatio:.8},G={...Cs},Zo=5*60*60*1e3,ei=60*60*1e3,le=[];function As(r){G={...Cs,...r||{}}}function $s(r){let e=r-Zo,t=0;for(;t<le.length&&le[t]<e;)t++;t>0&&le.splice(0,t)}function Ms(r=Date.now()){$s(r),le.push(r)}function Rs(r=Date.now()){$s(r);let e=r-ei,t=0;for(let o=le.length-1;o>=0&&le[o]>=e;o--)t++;let n=le.length,s={lastHour:t,last5h:n,maxPerHour:G.maxPerHour,maxPer5h:G.maxPer5h};return G.maxPerHour&&G.maxPerHour>0&&(s.hourlyRatio=t/G.maxPerHour),G.maxPer5h&&G.maxPer5h>0&&(s.fiveHourRatio=n/G.maxPer5h),s}function Ps(r,e=Date.now()){let t=Rs(e);return r?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 Ds(r=Date.now()){let e=Rs(r),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 Kt=new Map;function _s(r,e,t){return t?`${r}:${e}:${t}`:`${r}:${e}`}function Os(r,e,t,n=Date.now()){let s=Kt.get(r);s||(s={key:r,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Kt.set(r,s)),s.samples+=1,s.baseline=.2*e+(1-.2)*s.baseline,s.current=e,s.peak=Math.max(s.peak,e),s.lastAt=n,s.ring.push({key:r,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function Es(r){let e=Kt.get(r);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 ${r}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Y,mkdirSync as Ai,readdirSync as te,readFileSync as Ne,rmSync as $i,writeFileSync as Mi}from"fs";import{resolve as W}from"path";import{existsSync as pe,mkdirSync as Bt,readFileSync as ti,readdirSync as ni,renameSync as si,unlinkSync as ri,writeFileSync as dt}from"fs";import{resolve as ce,relative as ut}from"path";import{z as B}from"zod";var ge=B.object({id:B.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:B.string().min(1),trigger:B.string().min(1,"procedures must describe when they apply"),inputs:B.array(B.string()).default([]),expected:B.string().optional(),kpis:B.array(B.string()).default([]),owner:B.string().optional(),tags:B.array(B.string()).default([]),status:B.enum(["draft","active","deprecated"]).default("active"),source:B.string().optional(),evidence:B.array(B.string()).default([]),created:B.string().optional(),updated:B.string().optional(),related:B.array(B.string()).default([])});function oi(r){let e=r.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:r};let t={};for(let n of e[1].split(`
|
|
107
|
+
`)){let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let o=s[1],i=s[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 lt(r){let e=["---"];return e.push(`id: ${r.id}`),e.push(`title: "${r.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${r.trigger.replace(/"/g,'\\"')}"`),r.inputs?.length&&e.push(`inputs: ${JSON.stringify(r.inputs)}`),r.expected&&e.push(`expected: "${r.expected.replace(/"/g,'\\"')}"`),r.kpis?.length&&e.push(`kpis: ${JSON.stringify(r.kpis)}`),r.owner&&e.push(`owner: ${r.owner}`),r.tags?.length&&e.push(`tags: ${JSON.stringify(r.tags)}`),e.push(`status: ${r.status}`),r.source&&e.push(`source: "${r.source.replace(/"/g,'\\"')}"`),r.evidence?.length&&e.push(`evidence: ${JSON.stringify(r.evidence)}`),r.related?.length&&e.push(`related: ${JSON.stringify(r.related)}`),r.created&&e.push(`created: ${r.created}`),r.updated&&e.push(`updated: ${r.updated}`),e.push("---"),e.join(`
|
|
108
|
+
`)}var Ee=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ce(process.cwd(),".agentx/procedures"),Bt(this.baseDir,{recursive:!0})}pathFor(e){return ce(this.baseDir,`${e}.md`)}get draftsDir(){return ce(this.baseDir,"_drafts")}draftPathFor(e){return ce(this.draftsDir,`${e}.md`)}parseFile(e){let t=ti(e,"utf-8"),{meta:n,body:s}=oi(t),o=ge.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:s.trim(),path:ut(this.baseDir,e)}:null}listDir(e){if(!pe(e))return[];let t=[];for(let n of ni(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let s=this.parseFile(ce(e,n.name));s&&t.push(s)}return t.sort((n,s)=>n.meta.id.localeCompare(s.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return pe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return pe(t)?this.parseFile(t):null}add(e,t){let n=ge.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(pe(s))throw new Error(`Procedure already exists: ${n.id}`);return dt(s,lt(n)+`
|
|
109
|
+
|
|
110
|
+
`+t.trim()+`
|
|
111
|
+
`),{meta:n,body:t.trim(),path:ut(this.baseDir,s)}}update(e,t,n){let s=this.get(e);if(!s)throw new Error(`Procedure not found: ${e}`);let o=ge.parse({...s.meta,...t,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:s.body;return dt(this.pathFor(e),lt(o)+`
|
|
112
|
+
|
|
113
|
+
`+i.trim()+`
|
|
114
|
+
`),{meta:o,body:i.trim(),path:s.path}}addDraft(e,t){let n=ge.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 s=this.draftPathFor(n.id);if(pe(s))throw new Error(`Draft already exists: ${n.id}`);return Bt(this.draftsDir,{recursive:!0}),dt(s,lt(n)+`
|
|
115
|
+
|
|
116
|
+
`+t.trim()+`
|
|
117
|
+
`),{meta:n,body:t.trim(),path:ut(this.baseDir,s)}}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=ge.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return dt(this.pathFor(e),lt(n)+`
|
|
118
|
+
|
|
119
|
+
`+t.body+`
|
|
120
|
+
`),ri(this.draftPathFor(e)),{meta:n,body:t.body,path:ut(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!pe(t))throw new Error(`Draft not found: ${e}`);let n=ce(this.draftsDir,"_rejected");Bt(n,{recursive:!0}),si(t,ce(n,`${e}.md`))}isRejected(e){return pe(ce(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as ii,mkdirSync as ai,readFileSync as ci,writeFileSync as di}from"fs";import{dirname as ui,resolve as li}from"path";import{z as J}from"zod";var gi=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()}),pi=J.object({minedThrough:J.string().optional(),candidates:J.array(gi).default([])});function Ns(r){return li(r,"_candidates.json")}function hi(r){let e=Ns(r);if(!ii(e))return{candidates:[]};try{let t=pi.safeParse(JSON.parse(ci(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function fi(r,e){let t=Ns(r);ai(ui(t),{recursive:!0}),di(t,JSON.stringify(e,null,2)+`
|
|
121
|
+
`)}function mi(r,e,t,n,s){let o=r.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:s,status:"counting"},r.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=s)),o}function yi(r,e){return r.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function bi(r,e,t,n){let s=r.candidates.find(o=>o.key===e);s&&(s.status=t,n&&(s.procedureId=n))}function qt(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Ls(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function Gt(r,e,t={}){let n=Math.max(1,t.limit??3),s=t.minScore??.2,o=qt(r),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Ls(o,qt(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=Ls(o,qt(u));l>0&&c.push("title/tags");let g=Math.min(1,d*.7+l*.5);g>=s&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Jt(r){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...r.map(t=>{let n=t.procedure,s=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&s.push(`Inputs: ${n.meta.inputs.join(", ")}`),s.push(n.body),n.meta.expected&&s.push(`Done when: ${n.meta.expected}`),s.push(`(details: agentx procedure show ${n.meta.id})`),s.join(`
|
|
122
|
+
`)})].join(`
|
|
123
|
+
|
|
124
|
+
`)}mn();wt();var zt="turn-progress",Fs={progress:Je({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.")},Qt=(r,e)=>r.length>e?`${r.slice(0,e)}\u2026`:r;function Hs(r){return{agent:r.agent,request:Qt(r.request,1500),elapsedMinutes:Math.round(r.elapsedMinutes),budgetMinutes:r.budgetMinutes,trigger:r.trigger,recentSteps:r.steps.map(e=>({tool:e.tool,input:Qt(e.input,300),...e.result!==void 0?{result:Qt(e.result,300)}:{},...e.error?{failed:!0}:{}})),...r.repeated?{mostRepeatedCall:r.repeated}:{}}}wt();var js="turn-handoff",Us="approval-binding",Ws={nextStep:Je({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.")},Ks={approves:Ie("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."})},wi=(r,e)=>r.length>e?`${r.slice(0,e)}\u2026`:r,Bs=(r,e)=>r.length>e?`\u2026${r.slice(-e)}`:r,xi=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Yt(r){let e=r.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:xi.test(e.split(`
|
|
125
|
+
`).slice(-3).join(" ")):!1}var Ti=/^\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 qs(r){return r.trim().length<=160&&Ti.test(r)}function Gs(r){return r.trim().length<=160}function Js(r){return{agent:r.agent,channel:r.channel,request:wi(r.request,1500),agentReplyEnding:Bs(r.reply,1200)}}function Qs(r){return{agent:r.agent,channel:r.channel,userMessage:r.message,agentPreviousReplyEnding:Bs(r.previousReply,1200)}}var ki=5*6e4,Si=3,Ii=12,vi=24*60*6e4,zs=new Set(["cron","heartbeat","bench","a2a","business"]),Ci={observe(){},stop(){}};function Ys(r){if(fn(zt)==="off")return Ci;let e=r.now??Date.now,t=e(),n=[],s=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let g;for(let[h,b]of o)b>1&&(!g||b>g.times)&&(g={call:h,times:b});return g},u=g=>{if(c)return;c=!0,a=n.length;let h=Hs({agent:r.agent,request:r.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:r.budgetMinutes,steps:n.slice(-Ii),repeated:d(),trigger:g});he(zt,h,Fs,{links:[{kind:"task",id:r.taskId}],features:{agent:r.agent,trigger:g}}).finally(()=>{c=!1})},l=setInterval(()=>{n.length>a&&u("checkpoint")},r.checkpointMs??ki);return l.unref?.(),{observe(g){let h=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let b of h){if(b?.type!=="tool_use")continue;let T=b.input?JSON.stringify(b.input):"",w={tool:b.name||"tool",input:T};n.push(w),typeof b.id=="string"&&s.set(b.id,w);let p=`${w.tool}(${T})`,I=(o.get(p)??0)+1;o.set(p,I),I>=Si&&!i.has(p)&&(i.add(p),u("repetition"))}else if(g?.type==="user")for(let b of h){if(b?.type!=="tool_result")continue;let T=s.get(b.tool_use_id);T&&(T.result=Array.isArray(b.content)?b.content.map(w=>typeof w?.text=="string"?w.text:"").join(""):typeof b.content=="string"?b.content:"",b.is_error&&(T.error=!0))}},stop(){clearInterval(l)}}}var Xt=new Map,Xs=(r,e,t)=>`${r}\0${e}\0${t}`;function Vs(r){if(zs.has(r.channel)||!Yt(r.reply))return;let e=Xs(r.agent,r.channel,r.chatId);he(js,Js(r),Ws,{links:[{kind:"task",id:r.taskId}],features:{agent:r.agent,channel:r.channel}}).then(t=>{t?.callId&&Xt.set(e,{callId:t.callId,at:Date.now()})})}function Zs(r){if(zs.has(r.channel))return;let e=Xs(r.agent,r.channel,r.chatId),t=Xt.get(e);if(t){Xt.delete(e);let n=hn().store;if(n&&Date.now()-t.at<vi)try{n.label(t.callId,"userReply",qs(r.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!r.previousReply||!Gs(r.message)||!Yt(r.previousReply)||he(Us,Qs({agent:r.agent,channel:r.channel,message:r.message,previousReply:r.previousReply}),Ks,{links:[{kind:"task",id:r.taskId}],features:{agent:r.agent,channel:r.channel}})}function er(r,e){return e!=="claude-code"&&e!=="codex-cli"?!1:r==="github"||r==="gitlab"}var ir;function ld(r){ir=r}function gd(){return ir}var tr=64*1024,Ri=5*60*1e3,Te=".agentx/task-history",Pi=30;function Le(r,e=800){return r.length<=e?r:r.slice(0,e)+` \u2026[+${r.length-e} chars]`}function Di(r,e){let t={};return r?.path?.length&&(t.intentPath=r.path,t.intentPathLabel=r.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 _i(r,e,t={}){let n;try{n=r.listArticles(e)}catch{return""}if(n.length===0)return"";let s=new Map;for(let u of n){let l=u.meta.type||"untyped",g=s.get(l)||[];g.push(u.meta.title),s.set(l,g)}let o=t.maxArticles??400,i=n.length<=o,a=Array.from(s.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
|
|
126
|
+
`),c=process.argv[1]||"dist/cli.js",d=r.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:
|
|
127
|
+
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(`
|
|
128
|
+
`)}var Vt=8*1024;function nr(r){if(r.length<=Vt)return r;let e=r.length-Vt;return r.slice(0,Vt)+`\u2026[+${e}]`}function sr(r,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 s=typeof n.name=="string"?n.name:"";s&&r.set(s,(r.get(s)??0)+1)}}function Oi(r,e){if(!r||r.length===0)return null;for(let t of r)if((e.get(t)??0)===0)return t;return null}function rr(r,e,t){if(!t||typeof t!="object")return;let n=t.type,s=new Date().toISOString(),o=ee();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:r,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?nr(a):null,at:s})}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:r,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?nr(a):null,at:s})}return}}function Ei(){let r="",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
|
|
129
|
+
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
130
|
+
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
131
|
+
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
132
|
+
`;if(n==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
|
|
133
|
+
`;if(n==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
|
|
134
|
+
`;if(n==="codex.spawned"){let s=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${s}${o}
|
|
135
|
+
`}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
136
|
+
`;if(n==="turn.started")return`. codex turn started
|
|
137
|
+
`;if(n==="turn.completed"){let s=t.usage||{},o=s.input_tokens??s.inputTokens,i=s.output_tokens??s.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
|
|
138
|
+
`}if(n==="item.started"||n==="item.completed"){let s=t.item||{};if(s.type==="agent_message"&&typeof s.text=="string"){let c=s.text,d=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,d}let o=s.type||"item",i=s.name||s.command||s.tool_name||s.id||"";if(n==="item.started")return`
|
|
139
|
+
> codex ${o}${i?` ${i}`:""}
|
|
140
|
+
`;let a=s.output||s.result||s.text||s.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${Le(String(a),800)}`:""}
|
|
141
|
+
`}if(n==="error"||n==="turn.failed"){let s=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${Le(String(s),800)}
|
|
142
|
+
`}if(n==="system"&&t.subtype==="init"){let s=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${s}${o}
|
|
143
|
+
`}if(n==="assistant"&&t.message?.content){let s="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>r.length&&(s+=o.text.slice(r.length),r=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")s+=`
|
|
144
|
+
\u{1F4AD} ${Le(o.thinking,600)}
|
|
145
|
+
`;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?Le(JSON.stringify(o.input),400):"";s+=`
|
|
146
|
+
\u2192 ${i}(${a})
|
|
147
|
+
`}return s}if(n==="user"&&t.message?.content){let s="";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 ";s+=`${a}${Le(i,800)}
|
|
148
|
+
`}return s}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
149
|
+
`:""}}var or=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new it;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new An;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 nt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Cn(void 0,void 0,"unified"),this.memoryStore=new rt,this.patternStore=new ct,this.rateLimiter=new st,this.tokenTracker=new xe,this.messageQueue=new at,As({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new In({baseDir:W(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new vn({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...s)=>t("[classifier]",...s)})}for(let[n,s]of Object.entries(e.agents))this.agents.set(n,{id:n,def:s,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 s=this.handoverStore.get(t,n);if(!s||s.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&s.summaryConsumedAt))return{fromAgent:s.fromAgent,summary:o||s.summary,at:s.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),s,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&&(s=i,o=d.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(s);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,s,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,s);i=is(g.messages,e.message??""),c=as(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,s),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,s)||null,agentId:e.agentId,channel:n},u=await he(On,Nn(d),En,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${s}`}],features:{agent:e.agentId,channel:n}});return!u||u.mode!=="active"||!Ln(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${s} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,s,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,s),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:s,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,s,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-7T75BLEX.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",s,...d],source:{channel:s,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,s,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[s,o]of this.agents)s!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(s,t),role:o.def.systemPrompt?.split(`
|
|
150
|
+
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(s=>s.startsWith("@")):n.mentions[0]}async execute(e,t,n,s){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,s)}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";Mn().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,s){let o=Is().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(o){let m=await o;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 i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let m=this.meshFallback.directory().find(y=>y.healthy&&y.skills.some($=>$.id===e.agentId));if(m){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${m.peer}"`);try{let y=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:y}),viaMesh:m.peer}}catch(y){return this.log(`[${e.agentId}] mesh fallback to "${m.peer}" failed: ${y?.message??y}`),{content:"",error:`mesh fallback failed: ${y?.message??y}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let a=e.context?.channel||"api",c=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(i.activeTasks>=i.def.maxConcurrent)if(a==="api"){let m=Date.now(),y=25*6e4,$=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-m>y)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(y/6e4)}m`};await new Promise(N=>setTimeout(N,$))}}else{let m=i.def.queueMode||"collect",y=this.messageQueue.enqueue(e.agentId,a,c,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:a,chatId:c,originalContext:e.context});if(y==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(y){let $=this.messageQueue.pendingCount(e.agentId,a,c);return this.log(`[${e.agentId}] busy, message queued (mode: ${y}, pending: ${$})`),{content:"",error:`__queued__:${y}:${$}`}}}let d=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(m,y)=>{this.log(`[${e.agentId}] ${m} \u2014 queued, resumes in ~${Math.max(1,Math.round(y/1e3))}s`)}});if(!d.ok)return this.log(`[${e.agentId}] ${d.reason}`),{content:"",error:d.reason};i.activeTasks++,i.totalTasks++,i.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};i.runningTasks.push(u);let l=new AbortController;this.taskAborts.set(u.id,{agentId:e.agentId,channel:u.channel,chatId:typeof u.chatId=="string"?u.chatId:"",originalMessage:e.message||"",controller:l});let g={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(u.id,g);let h=m=>{if(m){g.buffer+=m,g.buffer.length>tr&&(g.buffer=g.buffer.slice(g.buffer.length-tr));for(let y of g.subscribers)try{y(m)}catch{}}},b=Ge();e.taskId=b;let T=new Map,w;if(t){let m=Ei();w=y=>{let $=m(y);if($&&h($),rr(b,e.agentId,y),sr(T,y),s)try{s(y)}catch{}}}else w=m=>{if(rr(b,e.agentId,m),sr(T,m),s)try{s(m)}catch{}};this.messageQueue.markRunning(e.agentId,a,c),this.log(`[${e.agentId}] executing task (${i.activeTasks}/${i.def.maxConcurrent})`);let p=e.context?.channel||"api",{evaluateRequest:I,selectRequestContext:M}=await import("./request-planner-BCOXUAPA.js"),v=await I(e.message,e.agentId,p),f=e.context?.chatId||e.context?.group||e.context?.sender||"default",R=e.context?.sender||"User",_=i.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,f),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${f}`),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,p,f,e.seedHistory);let A=[...this.sessions.getSession(e.agentId,p,f).messages].reverse().find(m=>m.role==="agent")?.content;Zs({agent:e.agentId,channel:p,chatId:f,message:e.message,previousReply:A,taskId:b}),this.sessions.addUserMessage(e.agentId,p,f,R,e.message);let H=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:p,chatId:f,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(H).toISOString(),taskId:b});let D;if(this.classifier&&p!=="a2a"&&!_)try{D=await this.classifier.classify({text:e.message,channel:p,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,O;if(this.config.workflows?.enabled&&L?.enabled)try{let m=new Dn({baseDir:W(process.cwd(),this.config.workflows.dir)}),y=_n({agentId:e.agentId,channel:p,message:e.message,intentPath:D?.path},m.list());y&&y.confidence>=L.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${y.workflow.id} confidence=${y.confidence.toFixed(2)} mode=${L.mode} reasons=${y.reasons.join(",")||"n/a"}`),L.mode==="auto"&&y.confidence>=L.autoRunThreshold&&(this.workflowAutoRunner?O={workflowId:y.workflow.id,confidence:y.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 x=this.wikiHub.getAgentWiki(e.agentId),S=this.memoryStore.findRelevant(e.message,e.agentId,_?3:8),k=this.memoryStore.buildContext(S),E=this.patternStore.findRelevant(e.message,e.agentId,5),U=this.patternStore.buildContext(E),P="";if(!_)try{let{loadLocalSkills:m,getAutoInjectSkills:y}=await import("./loader-BOKE5M5S.js"),$=await m(i.def.workspace);P=y($,e.message)}catch{}let F=i.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,f):i.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,f):i.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,f):void 0;if(F&&this.sessions.isSessionStale(e.agentId,p,f)&&(this.log(`[${e.agentId}] session stale for ${p}:${f}, starting fresh`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,F,p,f,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,p,f)){let m=this.sessions.getLastTurnContextTokens(e.agentId,p,f);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${f} (last turn context: ${m} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,F,p,f,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"tier-2",lastTurnInputTokens:m,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,p,f)){let m=this.sessions.getTurnCount(e.agentId,p,f);this.log(`[${e.agentId}] max-turns rotation for ${p}:${f} (${m} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,F,p,f,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"max-turns",at:new Date().toISOString()}),F=void 0}F&&i.def.tier==="claude-code"&&await this.maybeRotateForContinuity(e,i,p,f,F)&&(F=void 0);try{let m=await this.sessions.compactIfNeeded(e.agentId,p,f,this.memoryStore);if(m.compacted){let y=m.qualityScore??"?",$=m.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${f} (quality: ${y}%, ${$} 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",cr=_?{maxMessages:8,maxChars:2400}:ar&&er(p,i.def.tier)?{maxMessages:6,maxChars:1800}:void 0,dr=!F&&!_?_i(x,e.agentId):void 0,Fe=F?void 0:this.sessions.buildHistoryContext(e.agentId,p,f,cr),ur=F?void 0:this.sessions.getRotationMemo(e.agentId,p,f)??void 0,Zt;if(this.config.procedures?.injection?.enabled&&!F&&!_)try{let m=new Ee({baseDir:W(process.cwd(),this.config.procedures.dir)}),y=Gt(e.message,m.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(y.length>0){Zt=Jt(y);for(let $ of y)this.log(`[${e.agentId}] procedure match ${$.procedure.meta.id} score=${$.score.toFixed(2)} (${$.reasons.join(",")})`)}}catch(m){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${m?.message||m}`)}if(de&&de.cat)try{let y=this.sessions.getSession(e.agentId,p,f).messages,$=y[0],N=y[y.length-1],K=Fe===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${Fe.length}c/${Fe.split(`
|
|
151
|
+
`).length}L`,X=`[${e.agentId}] ${p}:${f} ${K} | session.messages=${y.length}`+(y.length>0?` first=${$.timestamp.slice(11,19)}(${$.role}:${($.content||"").slice(0,40).replace(/\n/g," ")}) last=${N.timestamp.slice(11,19)}(${N.role}:${(N.content||"").slice(0,40).replace(/\n/g," ")})`:"");de.cat("context",X)}catch(m){de.cat("context",`[${e.agentId}] context-diag error: ${m?.message??m}`)}let en;if(i.def.contextReferences&&!F)try{let m=i.def.workspace,y=this.referencesCache.get(m);if(!y){let[N,K]=await Promise.all([xt(i.def.workspace),Tt(i.def.workspace)]);if(N.byId.size===0&&K.recipes.length===0){let[X,C]=await Promise.all([xt(process.cwd()),Tt(process.cwd())]);y={refs:X,recipes:C}}else y={refs:N,recipes:K};this.referencesCache.set(m,y)}let $=Rn({agentId:e.agentId,intentTags:D?.path,message:e.message},y.recipes,y.refs);$.cards.length>0&&(en=$n($.cards,500*4)),$.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${$.unresolvedIds.join(", ")}`)}catch(m){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${m?.message||m}`)}let tn=this.sessions.getCrossSessionSummary(e.agentId,p,f,e.message),nn,He=os(e.message);if(He)try{let m=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:f,lookbackDays:He.lookbackDays,limit:12});if(m.turns.length>0){let y=[`[Long-memory recall \u2014 last ${He.lookbackDays}d on this chat (cue-triggered)]`],$=[...m.turns].sort((N,K)=>N.ts.localeCompare(K.ts));for(let N of $){let K=N.ts.slice(11,16)+" "+N.day,X=N.role==="user"?N.senderName||"User":N.senderName||"Agent";y.push(`${K} ${X}: ${N.content}`)}m.hasMore&&y.push(`[\u2026${m.totalScanned-m.turns.length}+ older turns available \u2014 call /recall with before=${m.oldestTs} to walk further back]`),y.push("[End of long-memory recall \u2014 respond to the latest message above]"),nn=y.join(`
|
|
152
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${He.lookbackDays}d, turns=${m.turns.length}, scanned=${m.totalScanned}`)}}catch(m){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${m.message}`)}let lr=_?"layered":e.contextStrategy??i.def.contextStrategy??this.config.session.contextStrategy??"layered",sn,rn,on=!1;if(lr==="planner"&&!v.active&&p!=="voice"&&p!=="desktop"){try{let{planContext:m}=await import("./context-planner-AQHJMVY2.js"),y=await m({agentId:e.agentId,channel:p,chatId:f,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});y?(on=!0,sn=y.sessionHistory,k=y.memoryContext,tn=y.crossChatContext,rn=y.debug,this.log(`[${e.agentId}] planner: turns=${y.debug.recentTurns}, mem=${y.debug.memoryIncluded?"yes":"no"}, xchat=${y.debug.crossChatIncluded?"yes":"no"} (${y.debug.planLatencyMs}ms) \u2014 ${y.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)`)}on&&F&&(this.sessions.clearClaudeSessionId(e.agentId,p,f),F=void 0)}let gt=`${e.agentId}:${p}:${f}`,je=xn(e.message);je&&(je==="default"?(this.activeSouls.delete(gt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(gt,je),this.log(`[${e.agentId}] Soul switched to: ${je}`)));let gr=this.activeSouls.get(gt),pr=bn(i.def.workspace,gr),hr=wn(pr),fr=this.agentMemory.indexMarkdown(e.agentId),mr=i.def.tier==="claude-code"||i.def.tier==="codex-cli"?`[Operating principle]
|
|
153
|
+
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.`:"",yr=i.def.richMessages!==!1&&(p==="telegram"||p==="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(`
|
|
154
|
+
`):"",an="";if(i.def.workspace){let m=W(i.def.workspace,"CLAUDE.md");if(Y(m))try{let y=Ne(m,"utf-8");an=`[Project CLAUDE.md]
|
|
155
|
+
${y.length>4e3?y.slice(0,4e3)+`
|
|
156
|
+
|
|
157
|
+
[CLAUDE.md truncated to 4KB]`:y}`}catch{}}let Ue=e.context?.runbookPath,pt=[];if(Ue&&Y(Ue)){let m=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],y=0,$=4e3,N=16e3;for(let K of m){if(y>=N)break;let X=W(Ue,K);if(Y(X))try{let C=Ne(X,"utf-8"),z=C.length>$?C.slice(0,$)+`
|
|
158
|
+
|
|
159
|
+
[${K} truncated to ${$} bytes]`:C;pt.push(`[Project Runbook \u2014 ${K} from ${Ue}]
|
|
160
|
+
${z}`),y+=z.length}catch{}}}let br=pt.length>0?pt.join(`
|
|
161
|
+
|
|
162
|
+
`):"",ht=[i.def.systemPrompt||"",mr,yr,an,br,hr||"",fr||""].filter(m=>m.trim().length>0).join(`
|
|
163
|
+
|
|
164
|
+
`)||void 0,cn={channel:p,chatId:f,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:i.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:i.def.systemPrompt,sender:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:_||er(p,i.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:_?void 0:U||void 0,procedureContext:Zt,references:en,skillInjection:P||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:sn??Fe,memoryContext:k||void 0,crossChatContext:tn||void 0,longMemoryRecall:nn||void 0,wikiContext:dr,handoverNote:this.buildHandoverNote(e.agentId,p,f),rotationMemo:ur,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},ft=v.active&&v.preprocess?await M(cn):{input:cn,excluded:[]};ft.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${ft.excluded.join(", ")}`);let mt=fs(ft.input,_?{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),yt=(mt?.length??0)+(ht?.length??0)+(e.message?.length??0),We={history:mt?.length??0,sysPrompt:ht?.length??0,message:e.message?.length??0},dn=_s(e.agentId,p,f);Os(dn,yt,We);let un=Es(dn);un&&this.log(`[${e.agentId}] ${un}`),yt>16e3&&this.log(`[${e.agentId}] large context for ${p}:${f}: ${yt} bytes (history=${We.history}, sysPrompt=${We.sysPrompt}, message=${We.message})`);let bt,ln=yn(i.def.tier,this.config.decisions.routing);if(!e.model&&ln&&(!v.active||v.preprocess))try{let{routeTaskModel:m}=await import("./routing-5K7PGHPL.js"),y=await m({message:e.message,agent:e.agentId,channel:p,isFollowUp:!!F,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,p,f),cheapModel:ln});y.downgraded&&(bt=y.model,this.log(`[${e.agentId}] ${y.reason}`))}catch{}let wr={...e,systemPromptAppend:ht,...bt?{model:bt}:{}},V,gn=Ys({agent:e.agentId,request:e.message,taskId:b,budgetMinutes:i.def.maxExecutionMinutes??20}),xr=w;w=m=>{gn.observe(m),xr?.(m)};try{if(O&&this.workflowAutoRunner)try{let j=await this.workflowAutoRunner({workflowId:O.workflowId,agentId:e.agentId,channel:p,chatId:f,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:f,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:D?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${O.workflowId} run=${j.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),V={content:"",duration:0,metadata:{handledByWorkflow:O.workflowId,workflowRunId:j.runId,workflowMatchConfidence:O.confidence}},V}catch(j){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${j?.message||j}`)}if(i.def.tier==="claude-code"){let j=i.def.persistentProcess?Xe():null,Q=j!=null&&j.hasLive({agentId:e.agentId,channel:p,chatId:f}),ne=!!F||Q,Z=[vs(ne),Ps(ne)].find(Se=>Se&&Se.abort);if(Z){i.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Z.reason}`);let Se={content:"",error:Z.message,duration:0};if(!t){g.buffer=`[error] ${Z.message}`;for(let Tr of g.subscribers)try{Tr(g.buffer)}catch{}}return V=Se,Se}Ms();let ke=Ds();ke&&this.log(`[${e.agentId}] ${ke}`)}let m=i.def.tier==="claude-code",y=m?t:(j,Q)=>{j&&h(j),t&&t(j,Q)},$=!1,N=m?n:j=>{j&&($?h(j):(h(`\u{1F4AD} ${j}`),$=!0)),n&&n(j)},K=()=>{$&&(h(`
|
|
165
|
+
`),$=!1)},X=m?y:y?(j,Q)=>{K(),y(j,Q)}:void 0,C=await ns(i.def,wr,this.providers,X,mt,F,w,l.signal,N);if(!C.error){let j=Oi(i.def.toolUseRequired,T);if(j){let Q=Array.from(T.entries()).map(([ne,Ke])=>`${ne}=${Ke}`).join(", ")||"none";C.error=`tool_required_not_called: ${j} (invoked: ${Q})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${j}, observed ${Q}`)}}V=C;let z=C.usage?ps(C.usage):void 0;if(ee().emit("task:completed",{taskId:b,agentId:e.agentId,channel:p,chatId:f,durationMs:Date.now()-H,error:C.error||void 0,inputTokens:z?.inputTokens,outputTokens:z?.outputTokens,cacheReadTokens:z?.cacheReadTokens,cacheCreateTokens:z?.cacheCreateTokens,tier2InputTokens:z?.tier2InputTokens,tier2OutputTokens:z?.tier2OutputTokens,tier2CacheReadTokens:z?.tier2CacheReadTokens,tier2CacheCreateTokens:z?.tier2CacheCreateTokens,finalResponse:C.content||void 0,billedModel:C.billedModel||i.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let j=C.error?`[error] ${C.error}`:C.content;g.buffer=j;for(let Q of g.subscribers)try{Q(j)}catch{}}if(C.error)i.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,f,C.content),Vs({agent:e.agentId,channel:p,chatId:f,request:e.message,reply:C.content,taskId:b}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,f,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,f,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,f,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,p,f,C.usage,C.contextTokens),C.usage){let Z=C.contextTokens,ke=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(Z??ke)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${f}: context=${Z??"n/a"} tokens (cumulative turn total=${ke}) \u2014 next turn will rotate`)}if(cs({channel:p,content:`User: ${e.message}`,responseLength:C.content.length}).capture){try{let Z=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:Z,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:p,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
166
|
+
|
|
167
|
+
Agent: ${C.content}`,meta:Di(D,e.context)})}catch{}Sn(e.agentId,e.message,C.content,{channel:p,chatId:f,sender:R},this.memoryStore).catch(()=>{}),ks(e.agentId,e.message,C.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||i.def.model,ne=e.context?.channel,Ke=ne&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ne}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,Q,ne,Ke),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:""))}return C}catch(m){i.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`);let y=ze(m.message);return V={content:"",error:Ye(y),errorKind:y.kind},V}finally{gn.stop(),i.activeTasks--;let m=i.runningTasks.findIndex(y=>y.id===u.id);m!==-1&&i.runningTasks.splice(m,1),this.taskAborts.delete(u.id),g.done=!0,g.endedAt=new Date;for(let y of g.subscribers)try{y(`
|
|
168
|
+
[task finished]
|
|
169
|
+
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),Ri).unref?.();try{let y=g.endedAt,$={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:y.toISOString(),durationMs:y.getTime()-u.startedAt.getTime(),ok:!V?.error,error:V?.error,responseText:V?.content||"",transcript:g.buffer};this.persistTaskRecord($);let N=($.responseText||$.error||"").trim();if(N){let K=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:K,at:y,ok:$.ok})}}catch(y){this.log(`[${e.agentId}] task history persist failed: ${y?.message}`)}this.messageQueue.markDone(e.agentId,a,c).then(y=>{if(y.length!==0){this.log(`[${e.agentId}] flushing ${y.length} queued message(s)`);for(let $ of y){let N=$.originalContext||{channel:$.channel,sender:$.sender,chatId:$.chatId};this.execute({message:$.text,agentId:e.agentId,context:N}).then(K=>this.postQueuedResponseToChannel(e.agentId,N,K)).catch(K=>{this.log(`[${e.agentId}] queued message failed: ${K.message}`)})}}}).catch(y=>{this.log(`[${e.agentId}] queue flush failed: ${y.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(),Te,this.safe(e.agentId),t);Y(n)||Ai(n,{recursive:!0});let s=W(n,`${this.safe(e.id)}.json`);Mi(s,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),s=this.sparklineCache.get(e);if(s&&n-s.at<6e4&&s.hourly.length===t)return s.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=W(process.cwd(),Te,this.safe(e));if(!Y(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 l of[d,c]){let g=W(a,l);if(Y(g))try{for(let h of te(g)){if(!h.endsWith(".json"))continue;let b=h.split("-")[0],T=parseInt(b,10);if(!Number.isFinite(T)||T<i||T>n)continue;let w=Math.floor((n-T)/36e5),p=t-1-w;p>=0&&p<t&&o[p]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=W(process.cwd(),Te);if(!Y(e))return 0;let t=0;for(let n of te(e)){let s=W(e,n),o;try{o=te(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=W(s,i),c;try{c=te(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ne(W(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Pi){let t=W(process.cwd(),Te);if(!Y(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let o of te(t)){let i=W(t,o),a;try{a=te(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{$i(W(i,c),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=W(process.cwd(),Te,this.safe(e));if(!Y(n))return[];let s=te(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of s){if(o.length>=t)break;let a=W(n,i),c;try{c=te(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Ne(W(a,d),"utf-8")),{transcript:l,responseText:g,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=W(process.cwd(),Te,this.safe(e));if(!Y(n))return null;let s=this.safe(t),o=te(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=W(n,i,`${s}.json`);if(Y(a))try{return JSON.parse(Ne(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let s=Pn();if(!s)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&&s.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,s={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),h=!1;if(s.replace){let b=s.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:g}}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{Fn as a,Hn as b,Qi as c,Un as d,Lr as e,Wn as f,Gr as g,zr as h,Zr as i,eo as j,to as k,ns as l,nt as m,st as n,it as o,ee as p,Ss as q,Bo as r,Is as s,Ee as t,hi as u,fi as v,mi as w,yi as x,bi as y,Gt as z,ld as A,gd as B,Di as C,_i as D,Vt as E,nr as F,sr as G,Oi as H,rr as I,or as J};
|
|
170
|
+
//# sourceMappingURL=chunk-45BLFNDG.js.map
|