agentix-cli 0.27.0 → 0.29.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 +93 -118
- package/apps/mac-helper/Sources/AgentXHelper/AXTree.swift +159 -0
- package/apps/mac-helper/Sources/AgentXHelper/Brand.swift +63 -0
- package/apps/mac-helper/Sources/AgentXHelper/Focus.swift +97 -0
- package/apps/mac-helper/Sources/AgentXHelper/HUD.swift +179 -0
- package/apps/mac-helper/Sources/AgentXHelper/OCR.swift +117 -0
- package/apps/mac-helper/Sources/AgentXHelper/Pointer.swift +309 -0
- package/apps/mac-helper/Sources/AgentXHelper/Screens.swift +67 -0
- package/apps/mac-helper/Sources/AgentXHelper/Typer.swift +185 -0
- package/apps/mac-helper/Sources/AgentXHelper/Vision.swift +201 -0
- package/apps/mac-helper/Sources/AgentXHelper/main.swift +265 -0
- package/apps/mac-helper/build.sh +39 -0
- package/apps/mac-voice/Resources/Info.plist +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +108 -0
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +123 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +68 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hold.swift +74 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +76 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +140 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +275 -0
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +147 -0
- package/apps/mac-voice/Sources/AgentXVoice/Recorder.swift +139 -0
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +162 -0
- package/apps/mac-voice/Sources/AgentXVoice/SmartPaste.swift +72 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +192 -0
- package/apps/mac-voice/Sources/AgentXVoice/StepLabel.swift +159 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +380 -0
- package/apps/mac-voice/build.sh +32 -0
- package/dist/{App-U52IPUK2.js → App-IEQXWJ7B.js} +2 -2
- package/dist/{ChatApp-XP4OMHPL.js → ChatApp-NWOSAP5U.js} +2 -2
- package/dist/{agent-V2CA4TXD.js → agent-LS4CZPJ6.js} +2 -2
- package/dist/{board-dashboard-TTMAYRLG.js → board-dashboard-6QQCKFB3.js} +8 -10
- package/dist/board-dashboard-6QQCKFB3.js.map +1 -0
- package/dist/{chunk-DCDQZR7I.js → chunk-3QVOWDHZ.js} +6 -6
- package/dist/chunk-3QVOWDHZ.js.map +1 -0
- package/dist/{chunk-FIEJDZVC.js → chunk-4KXBUORV.js} +2 -2
- package/dist/{chunk-UFAGYX73.js → chunk-6F2IKJ2F.js} +8 -8
- package/dist/chunk-6F2IKJ2F.js.map +1 -0
- package/dist/chunk-AE2LDMZU.js +2 -0
- package/dist/chunk-AE2LDMZU.js.map +1 -0
- package/dist/{chunk-VTE7L6LO.js → chunk-DI7FMCDK.js} +2 -2
- package/dist/{chunk-AX2PWSRT.js → chunk-F5AEXRPR.js} +2 -2
- package/dist/{chunk-CJQQIRPD.js → chunk-GMNKJXTR.js} +7 -7
- package/dist/chunk-GMNKJXTR.js.map +1 -0
- package/dist/{chunk-L2IZPR6P.js → chunk-JIOLJIBM.js} +2 -2
- package/dist/{chunk-IB3F7VBE.js → chunk-JKYMXLYL.js} +3 -3
- package/dist/chunk-JKYMXLYL.js.map +1 -0
- package/dist/{chunk-LNRB5MCU.js → chunk-LNWX4MPX.js} +151 -134
- package/dist/chunk-LNWX4MPX.js.map +1 -0
- package/dist/{chunk-WZ72HX5C.js → chunk-OTXDKKEU.js} +145 -138
- package/dist/chunk-OTXDKKEU.js.map +1 -0
- package/dist/{chunk-IBUSGCLQ.js → chunk-SBCZLZG3.js} +2 -2
- package/dist/{chunk-2T5W3ETS.js → chunk-SC5DIKBB.js} +2 -2
- package/dist/{chunk-BPIRO4YD.js → chunk-UYSNGBDT.js} +2 -2
- package/dist/chunk-XPXO5K4L.js +164 -0
- package/dist/chunk-XPXO5K4L.js.map +1 -0
- package/dist/{chunk-GDWJUGB5.js → chunk-Z2Y24ETP.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 +63 -42
- package/dist/index.js +12 -19
- package/dist/index.js.map +1 -1
- package/dist/program-I4J63BQ7.js +2 -0
- package/dist/query-R7EI3VGX.js +2 -0
- package/dist/registry-UJIJBLUR.js +2 -0
- package/dist/request-planner-BKT6RZKX.js +2 -0
- package/dist/request-planner-BKT6RZKX.js.map +1 -0
- package/dist/{review-candidates-AEUXRQQC.js → review-candidates-F3OFYTCZ.js} +2 -2
- package/dist/routing-S5WSFIAD.js +2 -0
- package/dist/scheduler-DSAOMV4O.js +2 -0
- package/dist/{seat-VZ7AVO27.js → seat-ZVHXNAEN.js} +2 -2
- package/dist/{select-F5I5PO2O.js → select-L7C52URW.js} +2 -2
- package/dist/wiki-5YQI4YKM.js +2 -0
- package/dist/wiki-5YQI4YKM.js.map +1 -0
- package/package.json +14 -3
- package/scripts/postinstall.mjs +80 -0
- package/dist/board-dashboard-TTMAYRLG.js.map +0 -1
- package/dist/chunk-CJQQIRPD.js.map +0 -1
- package/dist/chunk-DCDQZR7I.js.map +0 -1
- package/dist/chunk-IB3F7VBE.js.map +0 -1
- package/dist/chunk-LNRB5MCU.js.map +0 -1
- package/dist/chunk-OPHIXXGI.js +0 -157
- package/dist/chunk-OPHIXXGI.js.map +0 -1
- package/dist/chunk-UFAGYX73.js.map +0 -1
- package/dist/chunk-WZ72HX5C.js.map +0 -1
- package/dist/client-PX25MD47.js +0 -2
- package/dist/config-HL5F36V4.js +0 -2
- package/dist/config-mutator-HBX53OMJ.js +0 -2
- package/dist/doctor-PBAH6XL3.js +0 -2
- package/dist/program-YGXVCV2Y.js +0 -2
- package/dist/query-ZKTFJMNE.js +0 -2
- package/dist/registry-PSZDPFZK.js +0 -2
- package/dist/routing-4PV66BK6.js +0 -2
- package/dist/routing-4PV66BK6.js.map +0 -1
- package/dist/scheduler-GZZAN6ZG.js +0 -2
- package/dist/wiki-N5SMP3DT.js +0 -2
- /package/dist/{App-U52IPUK2.js.map → App-IEQXWJ7B.js.map} +0 -0
- /package/dist/{ChatApp-XP4OMHPL.js.map → ChatApp-NWOSAP5U.js.map} +0 -0
- /package/dist/{agent-V2CA4TXD.js.map → agent-LS4CZPJ6.js.map} +0 -0
- /package/dist/{chunk-FIEJDZVC.js.map → chunk-4KXBUORV.js.map} +0 -0
- /package/dist/{chunk-VTE7L6LO.js.map → chunk-DI7FMCDK.js.map} +0 -0
- /package/dist/{chunk-AX2PWSRT.js.map → chunk-F5AEXRPR.js.map} +0 -0
- /package/dist/{chunk-L2IZPR6P.js.map → chunk-JIOLJIBM.js.map} +0 -0
- /package/dist/{chunk-IBUSGCLQ.js.map → chunk-SBCZLZG3.js.map} +0 -0
- /package/dist/{chunk-2T5W3ETS.js.map → chunk-SC5DIKBB.js.map} +0 -0
- /package/dist/{chunk-BPIRO4YD.js.map → chunk-UYSNGBDT.js.map} +0 -0
- /package/dist/{chunk-GDWJUGB5.js.map → chunk-Z2Y24ETP.js.map} +0 -0
- /package/dist/{client-PX25MD47.js.map → client-5Z3URGPY.js.map} +0 -0
- /package/dist/{config-HL5F36V4.js.map → config-ORSGLVRW.js.map} +0 -0
- /package/dist/{config-mutator-HBX53OMJ.js.map → config-mutator-JB3S2E7H.js.map} +0 -0
- /package/dist/{doctor-PBAH6XL3.js.map → doctor-FS2BX6H4.js.map} +0 -0
- /package/dist/{program-YGXVCV2Y.js.map → program-I4J63BQ7.js.map} +0 -0
- /package/dist/{query-ZKTFJMNE.js.map → query-R7EI3VGX.js.map} +0 -0
- /package/dist/{registry-PSZDPFZK.js.map → registry-UJIJBLUR.js.map} +0 -0
- /package/dist/{review-candidates-AEUXRQQC.js.map → review-candidates-F3OFYTCZ.js.map} +0 -0
- /package/dist/{scheduler-GZZAN6ZG.js.map → routing-S5WSFIAD.js.map} +0 -0
- /package/dist/{seat-VZ7AVO27.js.map → scheduler-DSAOMV4O.js.map} +0 -0
- /package/dist/{wiki-N5SMP3DT.js.map → seat-ZVHXNAEN.js.map} +0 -0
- /package/dist/{select-F5I5PO2O.js.map → select-L7C52URW.js.map} +0 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import{a as ln,g as xn,m as wn}from"./chunk-Z2Y24ETP.js";import{c as on,e as gn,f as pn,h as fn}from"./chunk-67Q4DCPS.js";import{a as yt,b as yn}from"./chunk-K33GIBSE.js";import{a as bn}from"./chunk-W4YR2RO2.js";import{b as mn}from"./chunk-4KXBUORV.js";import{a as rn}from"./chunk-AE2LDMZU.js";import{a as an}from"./chunk-77OV7346.js";import{b as cn,c as dn,f as un}from"./chunk-SBCZLZG3.js";import{a as Ke,b as ht}from"./chunk-EVWEG3VD.js";import{v as sn,w as qs}from"./chunk-F5AEXRPR.js";import{a as ft,f as Bs}from"./chunk-F4HZTZHW.js";import{a as We,b as nn}from"./chunk-ZTEU5JVQ.js";import{c as He,d as Ue}from"./chunk-QOYAX2FT.js";import{a as mt,b as hn}from"./chunk-WPMX3VGI.js";import{e as de}from"./chunk-DSYKYZMT.js";qs();Bs();var Tn="session-continuity",kn={continues:ft("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:ft("Does the new request refer to something stated earlier in the conversation?")};function In(r){let e=(r.recentRequests??[]).filter(Boolean);return{newRequest:bt(r.message,1200),previousRequest:r.previousMessage?bt(r.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>bt(t,400))}:{},minutesSinceLastTurn:r.minutesSinceLastTurn,turnsSoFar:r.turnCount,currentContextTokens:r.lastTurnContextTokens,agent:r.agentId,channel:r.channel}}function Sn(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 bt(r,e){let t=String(r??"");return t.length>e?t.slice(0,e):t}import{spawn as Gs,execFile as Js}from"node:child_process";import{createHash as zs,randomBytes as Qs}from"node:crypto";import{createInterface as Ys}from"node:readline";import{promisify as Xs}from"node:util";var Vs=Xs(Js),se=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},xt=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=Vs("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=zs("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:Qs(32).toString("hex")},u=Gs("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 w=Ys({input:u.stdout}),b=()=>I(new se("OpenCode server failed before dispatch",!0)),x=()=>I(new Error("task cancelled by operator")),p=setTimeout(b,15e3),I=P=>{clearTimeout(p),u.removeListener("exit",b),u.removeListener("error",b),e.signal?.removeEventListener("abort",x),w.close(),u.stdout.resume(),P?h(P):g()};u.once("exit",b),u.once("error",b),e.signal?.addEventListener("abort",x,{once:!0}),w.on("line",P=>{try{let S=new URL(JSON.parse(P).url);if(S.protocol!=="http:"||S.hostname!=="127.0.0.1"||!S.port||S.username||S.password)return;l.url=S.origin,I()}catch{}}),e.signal?.aborted&&x()})}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()))}}}},Cn=new xt;import{execa as Qe}from"execa";import{spawn as Zs}from"node:child_process";import{createHash as er}from"node:crypto";import{createInterface as tr}from"node:readline";var re=class extends Error{},nr=r=>Zs("codex",["app-server",...r.args],{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),wt=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(),tr({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()}},Tt=class{constructor(e=nr,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=er("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[p])=>x.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 x=[...this.entries].find(([,p])=>!p.connection.busy);if(!x)throw new re("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{s={fingerprint:n,connection:new wt(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 w=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),b=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(b),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((P,S)=>{i.failTurn=S,i.notify=(f,M)=>{if(M?.threadId!==u)return;let O=M.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:f.replace("/","."),...O?{item:{...O,type:D[O.type]||O.type}}:{}}),f==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(d=O.text),f==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),f==="thread/tokenUsage/updated"){let v=M.tokenUsage.last;l={inputTokens:v.inputTokens,outputTokens:v.outputTokens,cacheReadTokens:v.cachedInputTokens,cacheCreateTokens:v.cacheWriteInputTokens||0}}f==="turn/completed"&&(M.turn.status==="completed"?P():S(new Error(M.turn.error?.message||`Codex turn ${M.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(x){if(i.close(),!a&&!e.signal?.aborted)throw new re(x.message);return{content:c,codexSessionId:u,usage:l,error:x.message,duration:Date.now()-t}}finally{clearTimeout(b),clearTimeout(w),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},vn=new Tt;import{execFile as sr}from"child_process";import{StringDecoder as Se}from"string_decoder";import{mkdtempSync as Dn,readFileSync as _n,rmSync as On}from"fs";import{join as Je}from"path";import{tmpdir as En}from"os";function Be(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 qe(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var $n=null;function Ge(){return $n}function si(r){$n=r}function Ie(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"}},An=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=Ie(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=Ie(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=Ie(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ie(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=Ie(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})`)}}}}}};function K(r){let e=Be(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}
|
|
3
|
+
`)}return{error:qe(e),errorKind:e.kind}}function Nn(){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 Mn(){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(`
|
|
4
|
+
`))}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(`
|
|
5
|
+
`)}function Ln(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 kt(r,e){return!e||e.trim().length===0?r:`[System]
|
|
6
|
+
${e.trim()}
|
|
7
|
+
|
|
8
|
+
[User]
|
|
9
|
+
${r}`}function rr(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(kt(e,n)),o}function or(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 Rn(r){return JSON.stringify(r)}function Fn(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Rn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(Rn).join(",")}]`]}function jn(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Fn()),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(kt(e,s)),a}function Ye(r,e){let t=Ke(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 ir(r,e){let t=Ye(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 ar(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 It(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=It(n,e+1);if(s)return s}}function Hn(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 St(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=St(t,e+1);if(n)return n}}}function cr(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
10
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=It(a)||t,n=Hn(a)||n,s=St(a)||s,o=Un(a)||o}catch{}return{usage:t,billedModel:n,sessionId:s,apiError:o}}function Un(r){if(!(!r||typeof r!="object")){if(r.type==="error"&&typeof r.message=="string")return Pn(r.message);if(r.type==="turn.failed"){let e=r.error?.message??r.error;if(typeof e=="string")return Pn(e)}}}function Pn(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 dr(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 Ct(r,e,t,n,s){let o=dr(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}
|
|
11
|
+
`)}function ur(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 lr(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 gr(r,e,t,n,s){let o=Date.now(),i=ie(r,e,t),a=Ln(r,i,!1,n,e.model,e.systemPromptAppend);if(Ct(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(x=>{let p=ht(Ke(r.workspace)),I=!1,P=sr("claude",a,{cwd:r.workspace,timeout:d,maxBuffer:10*1024*1024,env:{...p,HOME:p.HOME||"/home/"+(p.USER||"user")}},(S,f,M)=>{x({stdout:f||"",stderr:M||"",exitCode:S?S.code??1:0,killed:I})});if(P.stdin?.end(),s){let S=()=>{I=!0,c=s.reason?.message||(typeof s.reason=="string"?s.reason:"task cancelled by operator");try{P.kill("SIGTERM")}catch{}setTimeout(()=>{try{P.killed||P.kill("SIGKILL")}catch{}},3e3).unref?.()};s.aborted?S():s.addEventListener("abort",S,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&g!==0){let x;return g===143?x=`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||"")?x=Nn():x=l?.trim()||`Claude Code exited with code ${g}`,{content:"",...K(x),duration:Date.now()-o}}let w=ur(u);if(w)return{content:"",...K(w),duration:Date.now()-o};let b=lr(u);return{content:b.text,duration:Date.now()-o,claudeSessionId:b.sessionId,usage:b.usage,numTurns:b.numTurns,billedModel:b.billedModel}}catch(d){return console.error(`[runtime] execFile threw: ${d.message}`),{content:"",error:d.message||"Claude Code failed",duration:Date.now()-o}}}async function pr(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=Ln(r,c,!0,s,e.model,e.systemPromptAppend);Ct(e.agentId,r,e.model,s,"stream");let u="",l,g,h,w,b,x;try{let p=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),I=ht(Ke(r.workspace)),P=Qe("claude",d,{cwd:r.workspace,timeout:p,reject:!1,env:I,extendEnv:!1,buffer:!1,stdin:"ignore"}),S=!1,f;if(i){let C=()=>{S=!0,f=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{P.kill("SIGTERM")}catch{}setTimeout(()=>{try{P.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?C():i.addEventListener("abort",C,{once:!0})}let M="",O=new Se("utf8");P.stdout&&P.stdout.on("data",C=>{M+=O.write(C);let E=M.split(`
|
|
12
|
+
`);M=E.pop()||"";for(let N of E)if(N.trim())try{let k=JSON.parse(N);if(o)try{o(k)}catch{}if(k.type==="assistant"&&k.message?.usage){let $=k.message.usage,_=($.input_tokens||0)+($.cache_read_input_tokens||0)+($.cache_creation_input_tokens||0);_>0&&(w=_)}if(k.type==="assistant"&&k.message?.content){for(let $ of k.message.content)if($.type==="text"&&$.text){let _=$.text.slice(u.length);_&&(u=$.text,t(_,u))}}if(k.type==="content_block_delta"&&k.delta?.text&&(u+=k.delta.text,t(k.delta.text,u)),k.type==="result"&&k.result){if(k.is_error&&typeof k.result=="string")x=k.result;else{let $=(typeof k.result=="string",k.result);if(typeof $=="string"&&$.length>u.length){let _=$.slice(u.length);u=$,_&&t(_,u)}}k.usage&&(g={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.model=="string"&&(l=k.model),typeof k.session_id=="string"&&(h=k.session_id),typeof k.num_turns=="number"&&(b=k.num_turns)}k.type==="system"&&k.subtype==="init"&&(typeof k.model=="string"&&(l=k.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${k.apiKeySource} version=${k.claude_code_version} model=${k.model} permMode=${k.permissionMode}
|
|
13
|
+
`))}catch{N.trim()&&!N.startsWith("{")&&(u+=N+`
|
|
14
|
+
`,t(N+`
|
|
15
|
+
`,u))}});let D=await P,v=O.end();if(v&&(M+=v),S)return{content:"",error:f||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&D.stdout&&(u=typeof D.stdout=="string"?D.stdout:""),D.exitCode!==0&&!u){let C=typeof D.stderr=="string"?D.stderr:"",E=D,N;return E.timedOut?N=`Claude Code timed out after ${Math.round(p/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:E.signal?N=C.trim()||`Claude Code killed by signal ${E.signal}`:E.code==="ENOENT"||/ENOENT|spawn claude/i.test((E.shortMessage||"")+" "+C)?N=Nn():N=C.trim()||`Claude Code exited with code ${E.exitCode??"unknown"}`,{content:"",...K(N),duration:Date.now()-a}}return x?{content:"",...K(x),duration:Date.now()-a,usage:g,contextTokens:w,numTurns:b,billedModel:l,claudeSessionId:h}:{content:u,duration:Date.now()-a,usage:g,contextTokens:w,numTurns:b,billedModel:l,claudeSessionId:h}}catch(p){return{content:u||"",...K(p.message),duration:Date.now()-a,usage:g,contextTokens:w,numTurns:b,billedModel:l,claudeSessionId:h}}}async function fr(r,e,t,n){let s=Date.now(),o=ie(r,e,t),i=Dn(Je(En(),"agentx-codex-")),a=Je(i,"last-message.txt"),c=jn(r,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),u=await Qe("codex",c,{cwd:r.workspace,timeout:d,reject:!1,env:Ye(r,e),extendEnv:!1,stdin:"ignore"}),l=cr(u.stdout);if(u.exitCode!==0||l.apiError){let h=u,w;return h.timedOut?w=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:l.apiError?w=l.apiError:h.signal?w=u.stderr.trim()||`Codex CLI killed by signal ${h.signal}`:h.code==="ENOENT"||/ENOENT|spawn codex/i.test((h.shortMessage||"")+" "+u.stderr)?w=ze():w=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${h.exitCode??"unknown"}`,{content:"",...K(w),duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}let g="";try{g=_n(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:"",...K(u||"Codex CLI failed"),duration:Date.now()-s}}finally{On(i,{recursive:!0,force:!0})}}async function hr(r,e,t,n,s,o){let i=Date.now(),a=ie(r,e,n),c=Dn(Je(En(),"agentx-codex-")),d=Je(c,"last-message.txt"),u=jn(r,a,!0,e.model,e.systemPromptAppend,d,s),l="",g,h,w,b;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=Qe("codex",u,{cwd:r.workspace,timeout:x,reject:!1,env:Ye(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="",P="",S=!1,f=new Se("utf8"),M=new Se("utf8"),O=Math.min(x,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),D,v=()=>{D&&clearTimeout(D),D=setTimeout(()=>{S=!0,p.kill("SIGTERM",{forceKillAfterTimeout:5e3})},O)};v(),p.stderr?.on("data",$=>{v(),P+=M.write($),P.length>16e3&&(P=P.slice(-16e3))}),p.stdout?.on("data",$=>{v(),I+=f.write($);let _=I.split(`
|
|
16
|
+
`);I=_.pop()||"";for(let j of _)if(j.trim())try{let B=JSON.parse(j);if(o)try{o(B)}catch{}g=It(B)||g,h=Hn(B)||h,w=St(B)||w,b=Un(B)||b;let T=ar(B);if(T&&T!==l){let Y=T.startsWith(l)?T.slice(l.length):T;l=T.startsWith(l)?T:l+T,Y&&t(Y,l)}}catch{l+=j+`
|
|
17
|
+
`,t(j+`
|
|
18
|
+
`,l)}});let C=await p;D&&clearTimeout(D);let E=f.end();E&&(I+=E);let N=M.end();if(N&&(P+=N),C.exitCode!==0&&!l||b){let $=P||(typeof C.stderr=="string"?C.stderr:""),_=C,j;return S?j=`Codex CLI produced no output for ${Math.round(O/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.`:_.timedOut?j=`Codex CLI timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?j=b:_.signal?j=$.trim()||`Codex CLI killed by signal ${_.signal}`:_.code==="ENOENT"||/ENOENT|spawn codex/i.test((_.shortMessage||"")+" "+$)?j=ze():j=$.trim()||`Codex CLI exited with code ${_.exitCode??"unknown"}`,{content:"",...K(j),duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:w||s}}let k="";try{k=_n(d,"utf8").trim()}catch{}if(k&&k!==l){let $=k.startsWith(l)?k.slice(l.length):k;l=k,$&&t($,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:w||s}}catch(x){let p=/ENOENT|spawn codex/i.test(x?.message||"")?ze():x?.message;return{content:l,...K(p||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:h,codexSessionId:w||s}}finally{On(c,{recursive:!0,force:!0})}}async function mr(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=rr(r,d,e.model,e.systemPromptAppend,e.freshSession?void 0:s),l="",g,h=e.freshSession?void 0:s,w,b,x=!0,p;try{let I=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),P=ir(r,e);if(r.persistentProcess)try{b=await Cn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:r.workspace,env:P,model:e.model||r.model,permission:r.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",b.url),P=b.env,o?.({type:"opencode.ready",reused:b.reused,startupMs:Date.now()-c})}catch($){if(!($ instanceof se))throw $;$.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:$.message})}if(i?.aborted)throw new Error("task cancelled by operator");let S=Qe("opencode",u,{cwd:r.workspace,timeout:I,reject:!1,env:P,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let f=!1,M,O=()=>{b?.invalidate(),f=!0,M=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{S.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",O,{once:!0}),p=()=>i?.removeEventListener("abort",O),i?.aborted&&O();let D="",v="",C=new Se("utf8"),E=new Se("utf8"),N=$=>{if($.trim())try{let _=JSON.parse($);try{o?.(_)}catch{}typeof _.sessionID=="string"&&(h=_.sessionID);let j=_.type==="text"&&typeof _.part?.text=="string"?_.part.text:void 0;j&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:b?.reused??!1}),l+=j,t?.(j,l));let B=_.type==="reasoning"&&typeof _.part?.text=="string"?_.part.text:void 0;B&&a?.(B);let T=_.type==="step_finish"?_.part?.tokens:void 0;T&&(g={inputTokens:oe(T.input),outputTokens:oe(T.output),cacheReadTokens:oe(T.cache?.read),cacheCreateTokens:oe(T.cache?.write)}),w=or(_)||w}catch{l+=$+`
|
|
19
|
+
`,t?.($+`
|
|
20
|
+
`,l)}};S.stdout?.on("data",$=>{D+=C.write($);let _=D.split(`
|
|
21
|
+
`);D=_.pop()||"";for(let j of _)N(j)}),S.stderr?.on("data",$=>{v+=E.write($)});let k=await S;if(i&&i.removeEventListener("abort",O),D+=C.end(),D.trim()&&N(D),v+=E.end(),f)return{content:"",error:M||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(k.exitCode!==0||w){let $=k,_;return $.timedOut?_=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:w?_=w:$.code==="ENOENT"||/ENOENT|spawn opencode/i.test(($.shortMessage||"")+" "+v)?_=Mn():_=v.trim()||`OpenCode exited with code ${$.exitCode??"unknown"}`,{content:"",...K(_),duration:Date.now()-c,usage:g,opencodeSessionId:h}}return x=!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 P=/ENOENT|spawn opencode/i.test(I?.message||"")?Mn():I?.message;return{content:l,...K(P||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:h}}finally{p?.(),b?.release(x)}}async function yr(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:"",...K(`SDK error: ${o.message}`),duration:Date.now()-s}}}async function br(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 x=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(x))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let w=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);w.unref?.();let b=()=>({content:"",...K(`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 x=r.provider||"claude-code",p=n?`${n}
|
|
22
|
+
|
|
23
|
+
${e.message}`:e.message,I=e.context?.sender,P=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),S=e.context?.channel==="web-chat"&&P?{userId:I,agentId:e.agentId||"acme-public"}:void 0,f=on(r),M=Object.keys(f).length>0,O={task:p,cwd:r.workspace,provider:x,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:S,providerOpts:o,abortSignal:l.signal,mcpServers:M?f:void 0};if(s){let{generateStream:N}=await import("./agent-LS4CZPJ6.js"),k="",$,_,j,B;for await(let T of N(O)){if(c)try{c(T)}catch{}if(T.type==="text_delta")k+=T.text,s(T.text,k);else if(T.type==="thinking_delta")T.text&&i&&i(T.text);else if(T.type==="generate_result"){if(T.result.content&&T.result.content!==k){let Y=T.result.content.slice(k.length);Y?(k=T.result.content,s(Y,k)):k=T.result.content}$=T.result.tokensUsed,T.result.inputTokens!=null&&(_=T.result.inputTokens),T.result.outputTokens!=null&&(j=T.result.outputTokens)}else if(T.type==="done"){if(T.result.content&&T.result.content!==k){let Y=T.result.content.slice(k.length);Y?(k=T.result.content,s(Y,k)):k=T.result.content}T.result.tokensUsed!=null&&($=T.result.tokensUsed)}else T.type==="error"&&(B=T.error)}return B&&!k?g?b():B==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${B}`),duration:Date.now()-d}:((_===void 0||j===void 0)&&$&&(_=Math.round($*.7),j=$-_),{content:k||"Done.",tokensUsed:$,usage:_!==void 0||j!==void 0?{inputTokens:_||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:D}=await import("./agent-LS4CZPJ6.js"),v=await D(O),C=v.inputTokens,E=v.outputTokens;if((C===void 0||E===void 0)&&v.tokensUsed){let N=v.tokensUsed;C=Math.round(N*.7),E=N-C}return{content:v.content||"Done.",tokensUsed:v.tokensUsed,usage:C!==void 0||E!==void 0?{inputTokens:C||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(x){return g?b():x?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${x.message}`),duration:Date.now()-d}}finally{clearTimeout(w),a&&a.removeEventListener("abort",h)}}async function xr(r,e,t,n,s,o){let i=Ge();if(!i)return null;let a=Date.now(),c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:c,chatId:d};if(e.freshSession)try{await i.kill(u,"freshSession=true")}catch{}let l,g=!1;try{let v=i.list().length;l=i.acquire(u,{agentId:e.agentId,channel:c,chatId:d,workspace:r.workspace,model:e.model||r.model,permissionMode:r.permissionMode,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),g=i.list().length>v}catch(v){return v instanceof fe,null}g&&Ct(e.agentId,r,e.model,n,"persistent");let h=ie(r,e,t),w="",b,x,p,I,P,S,f,M=!1,O=()=>{M=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?O():o.addEventListener("abort",O,{once:!0}));let D=!1;try{for await(let v of l.runTurn({message:h,taskId:e.taskId??"unknown"})){if(D=!0,s)try{s(v.raw)}catch{}if(v.type==="assistant"){let C=v.raw.message?.content??[];for(let N of C)N.type==="text"&&typeof N.text=="string"&&(w=N.text);let E=v.raw.message?.usage;if(E){let N=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);N>0&&(I=N)}}if(v.type==="result"){let C=v.raw;if(C.is_error){let E=K(typeof C.result=="string"?C.result:"claude error");b=E.error,x=E.errorKind}else typeof C.result=="string"&&C.result.length>0&&(w=C.result);typeof C.session_id=="string"&&(f=C.session_id),C.usage&&(p={inputTokens:C.usage.input_tokens||0,outputTokens:C.usage.output_tokens||0,cacheReadTokens:C.usage.cache_read_input_tokens||0,cacheCreateTokens:C.usage.cache_creation_input_tokens||0}),typeof C.num_turns=="number"&&(P=C.num_turns),typeof C.message?.model=="string"?S=C.message.model:typeof C.model=="string"&&(S=C.model)}}}catch(v){if(M)b="task cancelled by operator",x="cancelled";else if(D){let C=K(`persistent claude process error: ${v?.message||String(v)}`);b=C.error,x=C.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",O),null}finally{o&&o.removeEventListener("abort",O)}return M&&!b&&(b="task cancelled by operator",x="cancelled"),{content:M?"":w,error:b,errorKind:x,duration:Date.now()-a,usage:p,contextTokens:I,numTurns:P,billedModel:S,claudeSessionId:f}}async function Wn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await xr(r,e,s,o,i,a);if(d!==null)return d}return n?pr(r,e,n,s,o,i,a):gr(r,e,s,o,a);case"codex-cli":if(r.persistentProcess)try{let d=await vn.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:r.workspace,env:Ye(r,e),args:Fn(),model:e.model||r.model,bypass:r.permissionMode==="bypassPermissions",prompt:kt(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?K(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?hr(r,e,n,s,o,i):fr(r,e,s,o);case"opencode":return mr(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?yr(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 br(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as he,writeFileSync as Kn,mkdirSync as wr,existsSync as vt,readdirSync as $t}from"fs";import{resolve as me}from"path";var At=12e3,Ce=30,Tr=720,kr=40,Ir=18e4,Sr="[Compacted conversation summary",Cr=7*864e5,vr=[/\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 $r(r){return r?vr.some(e=>e.test(r)):!1}var Ar=[{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 qn(r){if(!r)return null;let e=0;for(let t of Ar)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Bn(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 Gn(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 Jn(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 Mr(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 Xe=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=me(e,".agentx/sessions"),vt(this.sessionsDir)||wr(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Tr),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??kr),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Ir)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n){if(!this.adapterResolver)return;let s=this.sessionKey(e,t,n),o=this.seedingPromises.get(s);if(o)return o;let i=this.getSession(e,t,n);if(i.messages.length>0)return;let a=this.adapterResolver(t);if(!a?.seedHistory)return;let c=(async()=>{try{let d=await a.seedHistory(n,{maxMessages:Ce,maxChars:At});d.length>0&&this.appendSeededMessages(i,d)}catch{}})();this.seedingPromises.set(s,c);try{await c}finally{this.seedingPromises.delete(s)}}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 me(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(vt(o))try{let d=JSON.parse(he(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(!vt(i))return null;try{return JSON.parse(he(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);Bn(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);Bn(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??Ce),a=Math.max(200,s.maxChars??At),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=Mr(g.timestamp);h!==l&&(u.push(`\u2014 ${h} \u2014`),l=h);let w=g.name||(g.role==="user"?"User":"Agent");u.push(`${w}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
24
|
+
`)}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=$t(this.sessionsDir).filter(S=>S.startsWith(`${a}:`)&&S.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(S=>{let f=S.match(l);if(!f)return!1;let M=f[1];return M>=d&&M<=u}),h=[],w=0,b=e.query?.toLowerCase(),x=e.participants?.length?new Set(e.participants):void 0;for(let S of g){let f;try{f=JSON.parse(he(me(this.sessionsDir,S),"utf-8"))}catch{continue}if(f.agentId===e.agentId&&!(e.channel&&f.channel!==e.channel)&&!(e.chatId&&f.chatId!==e.chatId))for(let M of f.messages)w++,!(!M.timestamp||M.timestamp<o||M.timestamp>=i)&&(x&&M.role==="user"&&!x.has(M.name??"")||b&&!M.content.toLowerCase().includes(b)||h.push({ts:M.timestamp,role:M.role,senderName:M.name??"",content:M.content,channel:f.channel,chatId:f.chatId,day:f.day,sessionFile:S}))}h.sort((S,f)=>f.ts.localeCompare(S.ts));let p=h.slice(0,t),I=p.length>0?p[p.length-1].ts:null,P=h.length>t;return{turns:p,oldestTs:I,hasMore:P,totalScanned:w}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ce,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),o;try{o=$t(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(he(me(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!==""&&!$r(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=$t(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(he(me(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,w=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);c.push(`From ${h} (${u.channel}):
|
|
25
|
+
${w.join(`
|
|
26
|
+
`)}`)}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(`
|
|
27
|
+
`)}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(Sr)}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 me(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(he(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()},Kn(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>Cr?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>Ce&&(e.messages=e.messages.slice(-Ce));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>At&&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);Kn(t,JSON.stringify(e,null,2))}catch{}}};var Rr=new Set(["cron","a2a","workflow","selftest"]),Pr=[[/^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 zn(r){if(r.responseLength<=50)return{capture:!1,reason:"response too short"};let t=(r.channel??"").toLowerCase().split("@")[0];if(Rr.has(t))return{capture:!1,reason:`machine channel: ${t}`};let n=r.content.slice(0,400);for(let[s,o]of Pr)if(s.test(n))return{capture:!1,reason:o};return{capture:!0}}var Ve=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 ve,writeFileSync as Qn,appendFileSync as Dr,existsSync as ye,mkdirSync as _r}from"fs";import{resolve as be}from"path";var Xn={"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}},Vn=2e5,Or=1.5;function Er(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 Zn(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>Vn?{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 Yn=500,Nr=".agentx/pricing/custom.json",xe=class{dir;cache=null;pricing;constructor(e=be(process.cwd(),".agentx/usage")){this.dir=e,_r(this.dir,{recursive:!0}),this.pricing=Lr()}getPricing(){return this.pricing}static calculateCost(e,t,n=Xn){let s=Er(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*Or}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,w=0,b=0,x=0,p=0,I=0,P=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Vn?(x=n.inputTokens,p=n.outputTokens,I=n.cacheReadTokens,P=n.cacheCreateTokens):(g=n.inputTokens,h=n.outputTokens,w=n.cacheReadTokens,b=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+=w,l.cacheCreateTokens+=b,l.tier2InputTokens=(l.tier2InputTokens||0)+x,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+I,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+P,i&&l.errors++,l.byChannel||(l.byChannel={});let S=(c||"other").toLowerCase(),f=l.byChannel[S]||{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+=w,f.cacheCreateTokens+=b,f.tier2InputTokens+=x,f.tier2OutputTokens+=p,f.tier2CacheReadTokens+=I,f.tier2CacheCreateTokens+=P,i&&f.errors++,l.byChannel[S]=f,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>Yn&&l.sessionKeys.splice(0,l.sessionKeys.length-Yn))),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(ye(t))try{return this.cache=JSON.parse(ve(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ye(t))return null;try{return JSON.parse(ve(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={},w={};for(let[b,x]of Object.entries(n.agents)){let p=this.cost(x);g[b]=p,s+=x.tasks,o+=(x.inputTokens||0)+(x.tier2InputTokens||0),i+=(x.outputTokens||0)+(x.tier2OutputTokens||0),a+=(x.cacheReadTokens||0)+(x.tier2CacheReadTokens||0),c+=(x.cacheCreateTokens||0)+(x.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=b);let I=x.sessionKeys?.length||0;h[b]={sessions:I,avgTasksPerSession:I>0?x.tasks/I:x.tasks};for(let[P,S]of Object.entries(x.byChannel||{})){let f=this.cost(S,x.model);w[P]=(w[P]||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:w}}appendToTokenCosts(e,t){let n=t||be(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} |`;ye(n)?Dr(n,c+`
|
|
28
|
+
`):Qn(n,`# Token Costs
|
|
29
|
+
|
|
30
|
+
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
31
|
+
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
32
|
+
|
|
33
|
+
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
34
|
+
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
35
|
+
`+c+`
|
|
36
|
+
`)}hasTokenCostsEntry(e,t){let n=t||be(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ye(n))return!1;try{let s=ve(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||be(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ye(t))return null;try{let s=ve(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 w=0;w<e;w++){let b=new Date(Date.now()-w*864e5).toISOString().slice(0,10),x=this.getDate(b);if(x)for(let[p,I]of Object.entries(x.agents)){let P=this.cost(I);t+=I.tasks;let S=(I.inputTokens||0)+(I.tier2InputTokens||0),f=(I.outputTokens||0)+(I.tier2OutputTokens||0),M=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),O=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=S,s+=f,o+=M,i+=O,a+=I.errors,c+=P;let D=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};D.tasks+=I.tasks,D.input+=S,D.output+=f,D.cacheRead+=M,D.cacheCreate+=O,D.total=D.input+D.output+D.cacheRead+D.cacheCreate,D.totalDuration+=I.totalDuration,D.avgDuration=D.totalDuration/D.tasks,D.cost+=P,D.sessions+=I.sessionKeys?.length||0,I.model&&(D.model=I.model),d[p]=D;for(let[v,C]of Object.entries(I.byChannel||{})){let E=this.cost(C,I.model),N=u[v]||{tasks:0,cost:0};N.tasks+=C.tasks,N.cost+=E,u[v]=N}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,h={};for(let[w,b]of Object.entries(d))h[w]={sessions:b.sessions,avgTasksPerSession:b.sessions>0?b.tasks/b.sessions:b.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 be(this.dir,`${e}.json`)}save(e){try{Qn(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Lr(){let r=JSON.parse(JSON.stringify(Xn));try{let e=be(process.cwd(),Nr);if(!ye(e))return r;let t=JSON.parse(ve(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 Fr={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,memory:400,history:1200,"cross-chat":800,wiki:2500}},es=4;function ts(r,e=Fr){let t=jr(r,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,o=e.totalBudget*es;for(let i of t){if(!i.content)continue;let a=i.maxTokens*es,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(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(`
|
|
37
|
+
|
|
38
|
+
`)}function jr(r,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(Hr(r,t("channel",200))),n.push(Ur(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(`
|
|
39
|
+
`)[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(`
|
|
40
|
+
`);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(`
|
|
41
|
+
`),tags:["intent",...r.intent.path]})}else{let i=Wr(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(`
|
|
42
|
+
`),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(`
|
|
43
|
+
`),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(`
|
|
44
|
+
`),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 Hr(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(`
|
|
45
|
+
`),tags:s,rules:n}}function Ur(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(`
|
|
46
|
+
`),tags:n}}function Wr(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 Kr,writeFileSync as ns,appendFileSync as Br,mkdirSync as qr,existsSync as ss}from"fs";import{resolve as Mt}from"path";var rs=200,Gr=7,Ze=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=Mt(e,".agentx/memory"),ss(this.memoryDir)||qr(this.memoryDir,{recursive:!0})}filePath(e){return Mt(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()};Br(this.filePath(e),JSON.stringify(n)+`
|
|
47
|
+
`)}getAll(e){let t=this.filePath(e);if(!ss(t))return[];try{return Kr(t,"utf-8").split(`
|
|
48
|
+
`).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=Mt(this.memoryDir,`${t}_bm25_cache.json`),a=Ue(o,i),c=He(e,a),d=new Map(c.map(h=>[h.docIndex,h.score])),l=s.map((h,w)=>{let b=d.get(w)??0;return h.category==="secret"&&(b+=2),h.category==="commitment"&&(b+=1),{memory:h,score:b}}).filter(h=>h.score>0);if(l.length===0)return s.slice(-n);let g=l.sort((h,w)=>w.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(`
|
|
49
|
+
`)}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&&ns(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
50
|
+
`)+`
|
|
51
|
+
`)}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(`
|
|
52
|
+
`)}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=Gr*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>rs&&(t=t.slice(-rs));let o=this.filePath(e);ns(o,t.map(i=>JSON.stringify(i)).join(`
|
|
53
|
+
`)+`
|
|
54
|
+
`)}};import{existsSync as $e,mkdirSync as Jr,readdirSync as zr,readFileSync as Qr,unlinkSync as Rt,writeFileSync as et}from"fs";import{resolve as ae}from"path";var ue=["user","feedback","project","reference"],tt=class{baseDir;constructor(e={}){let t=e.baseDir??ae(process.cwd(),".agentx");this.baseDir=ae(t,"agent-memory")}dirFor(e){let t=Dt(e),n=ae(this.baseDir,t);return Jr(n,{recursive:!0}),n}fileFor(e,t,n){return ae(this.dirFor(e),`${t}_${Dt(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=Ae(t);if(o){let a=Pt(o);a&&(s=a.createdAt)}let i={name:Dt(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:s,updatedAt:n};return et(t,Yr(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of ue){let s=this.fileFor(e,n,t);if(!$e(s))continue;let o=Pt(Ae(s)??"");if(o)return o}return null}list(e){let t=this.dirFor(e);if(!$e(t))return[];let n=[];for(let s of zr(t,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name==="MEMORY.md")continue;let o=Pt(Ae(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);$e(o)&&(Rt(o),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return Ae(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),s=ae(t,".agentx-memory.md");n?et(s,n+`
|
|
55
|
+
`):$e(s)&&Rt(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}
|
|
56
|
+
${n}
|
|
57
|
+
${a}`:"",d=Ae(o)??"",u=d.indexOf(i),l=d.indexOf(a),g;if(u>=0&&l>u){let h=d.slice(0,u).replace(/\n+$/,""),w=d.slice(l+a.length).replace(/^\n+/,"");g=c?[h,c,w].filter(Boolean).join(`
|
|
58
|
+
|
|
59
|
+
`)+`
|
|
60
|
+
`:[h,w].filter(Boolean).join(`
|
|
61
|
+
|
|
62
|
+
`)+(h||w?`
|
|
63
|
+
`:"")}else if(c)g=d?d.replace(/\n+$/,"")+`
|
|
64
|
+
|
|
65
|
+
`+c+`
|
|
66
|
+
`:c+`
|
|
67
|
+
`;else return;et(o,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);$e(o)&&Rt(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("",`## ${Zr(o)}`,"");for(let a of i)s.push(`- **${a.name}** \u2014 ${a.description} _(updated ${a.updatedAt.slice(0,10)})_`)}}s.push(""),et(this.indexPath(e),s.join(`
|
|
68
|
+
`))}};function Yr(r){return["---",`name: ${r.name}`,`description: ${Xr(r.description)}`,`type: ${r.type}`,`created: ${r.createdAt}`,`updated: ${r.updatedAt}`,"---",""].join(`
|
|
69
|
+
`)+r.body+`
|
|
70
|
+
`}function Pt(r){if(!r.startsWith(`---
|
|
71
|
+
`))return null;let e=r.indexOf(`
|
|
72
|
+
---
|
|
73
|
+
`,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(`
|
|
74
|
+
`)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=Vr(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 Xr(r){return/[:#\n]/.test(r)?`"${r.replace(/"/g,'\\"')}"`:r}function Vr(r){return r.startsWith('"')&&r.endsWith('"')&&r.length>=2?r.slice(1,-1).replace(/\\"/g,'"'):r}function Dt(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function Zr(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Ae(r){try{return Qr(r,"utf-8")}catch{return null}}var nt=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(`
|
|
75
|
+
`),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 eo,writeFileSync as os,appendFileSync as to,mkdirSync as no,existsSync as is}from"fs";import{resolve as _t}from"path";var as=50,so="claude-haiku-4-20250514",ro=`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.
|
|
76
|
+
|
|
77
|
+
Extract patterns like:
|
|
78
|
+
- "When asked about X, the approach that works is Y"
|
|
79
|
+
- "User prefers Z style of communication"
|
|
80
|
+
- "For deployment tasks, always check A before doing B"
|
|
81
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
82
|
+
|
|
83
|
+
SKIP:
|
|
84
|
+
- Factual information (names, dates, URLs)
|
|
85
|
+
- Routine task completions
|
|
86
|
+
- Greetings or small talk
|
|
87
|
+
|
|
88
|
+
Output a JSON array:
|
|
89
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
90
|
+
|
|
91
|
+
If nothing worth extracting, output: []`,st=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=_t(e,".agentx/patterns"),is(this.patternsDir)||no(this.patternsDir,{recursive:!0})}filePath(e){return _t(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!is(t))return[];try{return eo(t,"utf-8").split(`
|
|
92
|
+
`).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()};to(this.filePath(e),JSON.stringify(n)+`
|
|
93
|
+
`)}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=_t(this.patternsDir,`${t}_bm25_cache.json`),a=Ue(o,i),d=He(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(`
|
|
94
|
+
`)}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&&os(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
95
|
+
`)+`
|
|
96
|
+
`)}prune(e){let t=this.getAll(e);t.length<=as||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,as),os(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
97
|
+
`)+`
|
|
98
|
+
`))}};async function cs(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:ro},{role:"user",content:`User: ${e.slice(0,500)}
|
|
99
|
+
|
|
100
|
+
Agent: ${t.slice(0,1e3)}`}],{model:so,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 oo}from"events";var Et=class{inner=new oo;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}},Ot;function ee(){return Ot||(Ot=new Et),Ot}nn();nn();var ds=["manual","notify","auto"];function io(r){return typeof r=="string"&&ds.includes(r)}var Nt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Me=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...Nt,...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:We(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:ao(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 ao(r,e){return r.length<=e?r:`${r.slice(0,e)}
|
|
101
|
+
\u2026[truncated ${r.length-e} chars]`}var Lt;function us(){return Lt||(Lt=new Me),Lt}import{readFileSync as co}from"fs";import{homedir as uo}from"os";import{join as lo}from"path";var Re=null,go=6e4;function po(){try{let r=lo(uo(),".claude.json"),e=co(r,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function fo(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 ho(r=!1){let e=Date.now();return!r&&Re&&e-Re.checkedAt<go||(Re=fo(po(),e)),Re}function ls(r){let e=ho();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 gs={warnRatio:.8},q={...gs},mo=5*60*60*1e3,yo=60*60*1e3,le=[];function ps(r){q={...gs,...r||{}}}function fs(r){let e=r-mo,t=0;for(;t<le.length&&le[t]<e;)t++;t>0&&le.splice(0,t)}function hs(r=Date.now()){fs(r),le.push(r)}function ms(r=Date.now()){fs(r);let e=r-yo,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:q.maxPerHour,maxPer5h:q.maxPer5h};return q.maxPerHour&&q.maxPerHour>0&&(s.hourlyRatio=t/q.maxPerHour),q.maxPer5h&&q.maxPer5h>0&&(s.fiveHourRatio=n/q.maxPer5h),s}function ys(r,e=Date.now()){let t=ms(e);return r?null:q.maxPerHour&&t.lastHour>=q.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${q.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}:q.maxPer5h&&t.last5h>=q.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${q.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 bs(r=Date.now()){let e=ms(r),t=q.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 Ft=new Map;function xs(r,e,t){return t?`${r}:${e}:${t}`:`${r}:${e}`}function ws(r,e,t,n=Date.now()){let s=Ft.get(r);s||(s={key:r,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Ft.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 Ts(r){let e=Ft.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 Q,mkdirSync as No,readdirSync as te,readFileSync as De,rmSync as Lo,writeFileSync as Fo}from"fs";import{resolve as H}from"path";import{existsSync as pe,mkdirSync as jt,readFileSync as bo,readdirSync as xo,renameSync as wo,unlinkSync as To,writeFileSync as rt}from"fs";import{resolve as ce,relative as ot}from"path";import{z as W}from"zod";var ge=W.object({id:W.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:W.string().min(1),trigger:W.string().min(1,"procedures must describe when they apply"),inputs:W.array(W.string()).default([]),expected:W.string().optional(),kpis:W.array(W.string()).default([]),owner:W.string().optional(),tags:W.array(W.string()).default([]),status:W.enum(["draft","active","deprecated"]).default("active"),source:W.string().optional(),evidence:W.array(W.string()).default([]),created:W.string().optional(),updated:W.string().optional(),related:W.array(W.string()).default([])});function ko(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(`
|
|
102
|
+
`)){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 it(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(`
|
|
103
|
+
`)}var Pe=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ce(process.cwd(),".agentx/procedures"),jt(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=bo(e,"utf-8"),{meta:n,body:s}=ko(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:ot(this.baseDir,e)}:null}listDir(e){if(!pe(e))return[];let t=[];for(let n of xo(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 rt(s,it(n)+`
|
|
104
|
+
|
|
105
|
+
`+t.trim()+`
|
|
106
|
+
`),{meta:n,body:t.trim(),path:ot(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 rt(this.pathFor(e),it(o)+`
|
|
107
|
+
|
|
108
|
+
`+i.trim()+`
|
|
109
|
+
`),{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 jt(this.draftsDir,{recursive:!0}),rt(s,it(n)+`
|
|
110
|
+
|
|
111
|
+
`+t.trim()+`
|
|
112
|
+
`),{meta:n,body:t.trim(),path:ot(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 rt(this.pathFor(e),it(n)+`
|
|
113
|
+
|
|
114
|
+
`+t.body+`
|
|
115
|
+
`),To(this.draftPathFor(e)),{meta:n,body:t.body,path:ot(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");jt(n,{recursive:!0}),wo(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 Io,mkdirSync as So,readFileSync as Co,writeFileSync as vo}from"fs";import{dirname as $o,resolve as Ao}from"path";import{z as G}from"zod";var Mo=G.object({key:G.string(),count:G.number().int().min(0).default(0),firstSeen:G.string(),lastSeen:G.string(),taskIds:G.array(G.string()).default([]),sampleMessage:G.string().default(""),status:G.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:G.string().optional()}),Ro=G.object({minedThrough:G.string().optional(),candidates:G.array(Mo).default([])});function ks(r){return Ao(r,"_candidates.json")}function Po(r){let e=ks(r);if(!Io(e))return{candidates:[]};try{let t=Ro.safeParse(JSON.parse(Co(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Do(r,e){let t=ks(r);So($o(t),{recursive:!0}),vo(t,JSON.stringify(e,null,2)+`
|
|
116
|
+
`)}function _o(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 Oo(r,e){return r.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Eo(r,e,t,n){let s=r.candidates.find(o=>o.key===e);s&&(s.status=t,n&&(s.procedureId=n))}function Ht(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Is(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 Ut(r,e,t={}){let n=Math.max(1,t.limit??3),s=t.minScore??.2,o=Ht(r),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Is(o,Ht(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=Is(o,Ht(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 Wt(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(`
|
|
117
|
+
`)})].join(`
|
|
118
|
+
|
|
119
|
+
`)}function Ss(r,e){return e!=="claude-code"&&e!=="codex-cli"?!1:r==="github"||r==="gitlab"}var Rs;function rc(r){Rs=r}function oc(){return Rs}var Cs=64*1024,jo=5*60*1e3,we=".agentx/task-history",Ho=30;function _e(r,e=800){return r.length<=e?r:r.slice(0,e)+` \u2026[+${r.length-e} chars]`}function Uo(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 Wo(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(`
|
|
120
|
+
`),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:
|
|
121
|
+
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(`
|
|
122
|
+
`)}var Kt=8*1024;function vs(r){if(r.length<=Kt)return r;let e=r.length-Kt;return r.slice(0,Kt)+`\u2026[+${e}]`}function $s(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 Ko(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 As(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?vs(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?vs(a):null,at:s})}return}}function Bo(){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
|
|
123
|
+
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
124
|
+
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
125
|
+
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
126
|
+
`;if(n==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
|
|
127
|
+
`;if(n==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
|
|
128
|
+
`;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}
|
|
129
|
+
`}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
130
|
+
`;if(n==="turn.started")return`. codex turn started
|
|
131
|
+
`;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}`:""}
|
|
132
|
+
`}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`
|
|
133
|
+
> codex ${o}${i?` ${i}`:""}
|
|
134
|
+
`;let a=s.output||s.result||s.text||s.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${_e(String(a),800)}`:""}
|
|
135
|
+
`}if(n==="error"||n==="turn.failed"){let s=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${_e(String(s),800)}
|
|
136
|
+
`}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}
|
|
137
|
+
`}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+=`
|
|
138
|
+
\u{1F4AD} ${_e(o.thinking,600)}
|
|
139
|
+
`;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?_e(JSON.stringify(o.input),400):"";s+=`
|
|
140
|
+
\u2192 ${i}(${a})
|
|
141
|
+
`}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}${_e(i,800)}
|
|
142
|
+
`}return s}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
143
|
+
`:""}}var Ms=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new tt;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new ln;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new Xe(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new un(void 0,void 0,"unified"),this.memoryStore=new Ze,this.patternStore=new st,this.rateLimiter=new Ve,this.tokenTracker=new xe,this.messageQueue=new nt,ps({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new cn({baseDir:H(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new dn({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=Gn(g.messages,e.message??""),c=Jn(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 sn(Tn,In(d),kn,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${s}`}],features:{agent:e.agentId,channel:n}});return!u||u.mode!=="active"||!Sn(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(`
|
|
144
|
+
`)[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=us().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 y=await o;if(y.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${y.sessionId}`),{content:y.text,viaAttachedSession:y.sessionId};this.log(`[${e.agentId}] attached session did not take it (${y.reason}) \u2014 spawning`)}let i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let y=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(R=>R.id===e.agentId));if(y){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${y.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(y.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:y.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${y.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}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 y=Date.now(),m=25*6e4,R=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-y>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(L=>setTimeout(L,R))}}else{let y=i.def.queueMode||"collect",m=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(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let R=this.messageQueue.pendingCount(e.agentId,a,c);return this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${R})`),{content:"",error:`__queued__:${m}:${R}`}}}let d=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(y,m)=>{this.log(`[${e.agentId}] ${y} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/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=y=>{if(y){g.buffer+=y,g.buffer.length>Cs&&(g.buffer=g.buffer.slice(g.buffer.length-Cs));for(let m of g.subscribers)try{m(y)}catch{}}},w=We();e.taskId=w;let b=new Map,x;if(t){let y=Bo();x=m=>{let R=y(m);if(R&&h(R),As(w,e.agentId,m),$s(b,m),s)try{s(m)}catch{}}}else x=y=>{if(As(w,e.agentId,y),$s(b,y),s)try{s(y)}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:P}=await import("./request-planner-BKT6RZKX.js"),S=await I(e.message,e.agentId,p),f=e.context?.chatId||e.context?.group||e.context?.sender||"default",M=e.context?.sender||"User",O=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),this.sessions.addUserMessage(e.agentId,p,f,M,e.message);let D=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(D).toISOString(),taskId:w});let v;if(this.classifier&&p!=="a2a"&&!O)try{v=await this.classifier.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(y){this.log(`[classifier] classify failed for ${e.agentId}: ${y?.message||y}`)}let C=this.config.workflows?.matching,E;if(this.config.workflows?.enabled&&C?.enabled)try{let y=new xn({baseDir:H(process.cwd(),this.config.workflows.dir)}),m=wn({agentId:e.agentId,channel:p,message:e.message,intentPath:v?.path},y.list());m&&m.confidence>=C.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${C.mode} reasons=${m.reasons.join(",")||"n/a"}`),C.mode==="auto"&&m.confidence>=C.autoRunThreshold&&(this.workflowAutoRunner?E={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(y){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${y?.message||y}`)}let N=this.wikiHub.getAgentWiki(e.agentId),k=this.memoryStore.findRelevant(e.message,e.agentId,O?3:8),$=this.memoryStore.buildContext(k),_=this.patternStore.findRelevant(e.message,e.agentId,5),j=this.patternStore.buildContext(_),B="";if(!O)try{let{loadLocalSkills:y,getAutoInjectSkills:m}=await import("./loader-BOKE5M5S.js"),R=await y(i.def.workspace);B=m(R,e.message)}catch{}let T=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(T&&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,T,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()}),T=void 0),T&&this.sessions.shouldRotateByTierTwo(e.agentId,p,f)){let y=this.sessions.getLastTurnContextTokens(e.agentId,p,f);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${f} (last turn context: ${y} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,T,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:y,at:new Date().toISOString()}),T=void 0}if(T&&this.sessions.shouldRotateByTurns(e.agentId,p,f)){let y=this.sessions.getTurnCount(e.agentId,p,f);this.log(`[${e.agentId}] max-turns rotation for ${p}:${f} (${y} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,T,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()}),T=void 0}T&&i.def.tier==="claude-code"&&await this.maybeRotateForContinuity(e,i,p,f,T)&&(T=void 0);try{let y=await this.sessions.compactIfNeeded(e.agentId,p,f,this.memoryStore);if(y.compacted){let m=y.qualityScore??"?",R=y.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${f} (quality: ${m}%, ${R} entities lost)`),y.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${y.lostEntities.slice(0,5).join(", ")}`),y.drift){let L=y.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${L.overallScore} (lexicon=${L.lexiconDecay}, tools=${L.toolShift}, semantic=${L.semanticDrift})`),L.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${L.lostWords.slice(0,5).join(", ")}`)}}}catch(y){this.log(`[${e.agentId}] compaction failed (non-fatal): ${y.message}`)}let Y=process.env.AGENTX_CONTEXT_SURGERY==="1",Ps=O?{maxMessages:8,maxChars:2400}:Y&&Ss(p,i.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ds=!T&&!O?Wo(N,e.agentId):void 0,Oe=T?void 0:this.sessions.buildHistoryContext(e.agentId,p,f,Ps),_s=T?void 0:this.sessions.getRotationMemo(e.agentId,p,f)??void 0,Bt;if(this.config.procedures?.injection?.enabled&&!T&&!O)try{let y=new Pe({baseDir:H(process.cwd(),this.config.procedures.dir)}),m=Ut(e.message,y.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Bt=Wt(m);for(let R of m)this.log(`[${e.agentId}] procedure match ${R.procedure.meta.id} score=${R.score.toFixed(2)} (${R.reasons.join(",")})`)}}catch(y){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${y?.message||y}`)}if(de&&de.cat)try{let m=this.sessions.getSession(e.agentId,p,f).messages,R=m[0],L=m[m.length-1],U=Oe===void 0?`resume=${T?T.slice(0,8):"?"} (no rebuild)`:`fresh history=${Oe.length}c/${Oe.split(`
|
|
145
|
+
`).length}L`,X=`[${e.agentId}] ${p}:${f} ${U} | session.messages=${m.length}`+(m.length>0?` first=${R.timestamp.slice(11,19)}(${R.role}:${(R.content||"").slice(0,40).replace(/\n/g," ")}) last=${L.timestamp.slice(11,19)}(${L.role}:${(L.content||"").slice(0,40).replace(/\n/g," ")})`:"");de.cat("context",X)}catch(y){de.cat("context",`[${e.agentId}] context-diag error: ${y?.message??y}`)}let qt;if(i.def.contextReferences&&!T)try{let y=i.def.workspace,m=this.referencesCache.get(y);if(!m){let[L,U]=await Promise.all([mt(i.def.workspace),yt(i.def.workspace)]);if(L.byId.size===0&&U.recipes.length===0){let[X,A]=await Promise.all([mt(process.cwd()),yt(process.cwd())]);m={refs:X,recipes:A}}else m={refs:L,recipes:U};this.referencesCache.set(y,m)}let R=yn({agentId:e.agentId,intentTags:v?.path,message:e.message},m.recipes,m.refs);R.cards.length>0&&(qt=hn(R.cards,500*4)),R.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${R.unresolvedIds.join(", ")}`)}catch(y){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${y?.message||y}`)}let Gt=this.sessions.getCrossSessionSummary(e.agentId,p,f,e.message),Jt,Ee=qn(e.message);if(Ee)try{let y=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:f,lookbackDays:Ee.lookbackDays,limit:12});if(y.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Ee.lookbackDays}d on this chat (cue-triggered)]`],R=[...y.turns].sort((L,U)=>L.ts.localeCompare(U.ts));for(let L of R){let U=L.ts.slice(11,16)+" "+L.day,X=L.role==="user"?L.senderName||"User":L.senderName||"Agent";m.push(`${U} ${X}: ${L.content}`)}y.hasMore&&m.push(`[\u2026${y.totalScanned-y.turns.length}+ older turns available \u2014 call /recall with before=${y.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),Jt=m.join(`
|
|
146
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ee.lookbackDays}d, turns=${y.turns.length}, scanned=${y.totalScanned}`)}}catch(y){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${y.message}`)}let Os=O?"layered":e.contextStrategy??i.def.contextStrategy??this.config.session.contextStrategy??"layered",zt,Qt,Yt=!1;if(Os==="planner"&&!S.active&&p!=="voice"&&p!=="desktop"){try{let{planContext:y}=await import("./context-planner-AQHJMVY2.js"),m=await y({agentId:e.agentId,channel:p,chatId:f,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});m?(Yt=!0,zt=m.sessionHistory,$=m.memoryContext,Gt=m.crossChatContext,Qt=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(y){this.log(`[${e.agentId}] planner failed (non-fatal): ${y.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Yt&&T&&(this.sessions.clearClaudeSessionId(e.agentId,p,f),T=void 0)}let at=`${e.agentId}:${p}:${f}`,Ne=fn(e.message);Ne&&(Ne==="default"?(this.activeSouls.delete(at),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(at,Ne),this.log(`[${e.agentId}] Soul switched to: ${Ne}`)));let Es=this.activeSouls.get(at),Ns=gn(i.def.workspace,Es),Ls=pn(Ns),Fs=this.agentMemory.indexMarkdown(e.agentId),js=i.def.tier==="claude-code"||i.def.tier==="codex-cli"?`[Operating principle]
|
|
147
|
+
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.`:"",Hs=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(`
|
|
148
|
+
`):"",Xt="";if(i.def.workspace){let y=H(i.def.workspace,"CLAUDE.md");if(Q(y))try{let m=De(y,"utf-8");Xt=`[Project CLAUDE.md]
|
|
149
|
+
${m.length>4e3?m.slice(0,4e3)+`
|
|
150
|
+
|
|
151
|
+
[CLAUDE.md truncated to 4KB]`:m}`}catch{}}let Le=e.context?.runbookPath,ct=[];if(Le&&Q(Le)){let y=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],m=0,R=4e3,L=16e3;for(let U of y){if(m>=L)break;let X=H(Le,U);if(Q(X))try{let A=De(X,"utf-8"),z=A.length>R?A.slice(0,R)+`
|
|
152
|
+
|
|
153
|
+
[${U} truncated to ${R} bytes]`:A;ct.push(`[Project Runbook \u2014 ${U} from ${Le}]
|
|
154
|
+
${z}`),m+=z.length}catch{}}}let Us=ct.length>0?ct.join(`
|
|
155
|
+
|
|
156
|
+
`):"",dt=[i.def.systemPrompt||"",js,Hs,Xt,Us,Ls||"",Fs||""].filter(y=>y.trim().length>0).join(`
|
|
157
|
+
|
|
158
|
+
`)||void 0,Vt={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:M,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:O||Ss(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:O?void 0:j||void 0,procedureContext:Bt,references:qt,skillInjection:B||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:zt??Oe,memoryContext:$||void 0,crossChatContext:Gt||void 0,longMemoryRecall:Jt||void 0,wikiContext:Ds,handoverNote:this.buildHandoverNote(e.agentId,p,f),rotationMemo:_s,intent:v?{path:v.path,pathLabel:v.pathLabel,pathId:v.pathId,axes:v.axes,leaf:v.leaf,status:v.status}:void 0,message:e.message},ut=S.active&&S.preprocess?await P(Vt):{input:Vt,excluded:[]};ut.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${ut.excluded.join(", ")}`);let lt=ts(ut.input,O?{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),gt=(lt?.length??0)+(dt?.length??0)+(e.message?.length??0),Fe={history:lt?.length??0,sysPrompt:dt?.length??0,message:e.message?.length??0},Zt=xs(e.agentId,p,f);ws(Zt,gt,Fe);let en=Ts(Zt);en&&this.log(`[${e.agentId}] ${en}`),gt>16e3&&this.log(`[${e.agentId}] large context for ${p}:${f}: ${gt} bytes (history=${Fe.history}, sysPrompt=${Fe.sysPrompt}, message=${Fe.message})`);let pt,tn=rn(i.def.tier,this.config.decisions.routing);if(!e.model&&tn&&(!S.active||S.preprocess))try{let{routeTaskModel:y}=await import("./routing-S5WSFIAD.js"),m=await y({message:e.message,agent:e.agentId,channel:p,isFollowUp:!!T,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,p,f),cheapModel:tn});m.downgraded&&(pt=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let Ws={...e,systemPromptAppend:dt,...pt?{model:pt}:{}},V;try{if(E&&this.workflowAutoRunner)try{let F=await this.workflowAutoRunner({workflowId:E.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:v?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${E.workflowId} run=${F.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),V={content:"",duration:0,metadata:{handledByWorkflow:E.workflowId,workflowRunId:F.runId,workflowMatchConfidence:E.confidence}},V}catch(F){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${F?.message||F}`)}if(i.def.tier==="claude-code"){let F=i.def.persistentProcess?Ge():null,J=F!=null&&F.hasLive({agentId:e.agentId,channel:p,chatId:f}),ne=!!T||J,Z=[ls(ne),ys(ne)].find(ke=>ke&&ke.abort);if(Z){i.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Z.reason}`);let ke={content:"",error:Z.message,duration:0};if(!t){g.buffer=`[error] ${Z.message}`;for(let Ks of g.subscribers)try{Ks(g.buffer)}catch{}}return V=ke,ke}hs();let Te=bs();Te&&this.log(`[${e.agentId}] ${Te}`)}let y=i.def.tier==="claude-code",m=y?t:(F,J)=>{F&&h(F),t&&t(F,J)},R=!1,L=y?n:F=>{F&&(R?h(F):(h(`\u{1F4AD} ${F}`),R=!0)),n&&n(F)},U=()=>{R&&(h(`
|
|
159
|
+
`),R=!1)},X=y?m:m?(F,J)=>{U(),m(F,J)}:void 0,A=await Wn(i.def,Ws,this.providers,X,lt,T,x,l.signal,L);if(!A.error){let F=Ko(i.def.toolUseRequired,b);if(F){let J=Array.from(b.entries()).map(([ne,je])=>`${ne}=${je}`).join(", ")||"none";A.error=`tool_required_not_called: ${F} (invoked: ${J})`,A.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${F}, observed ${J}`)}}V=A;let z=A.usage?Zn(A.usage):void 0;if(ee().emit("task:completed",{taskId:w,agentId:e.agentId,channel:p,chatId:f,durationMs:Date.now()-D,error:A.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:A.content||void 0,billedModel:A.billedModel||i.def.model||void 0,at:new Date().toISOString()}),!t&&(A.content||A.error)){let F=A.error?`[error] ${A.error}`:A.content;g.buffer=F;for(let J of g.subscribers)try{J(F)}catch{}}if(A.error)i.errors++,this.log(`[${e.agentId}] error: ${A.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,f,A.content),A.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,f,A.claudeSessionId),A.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,f,A.codexSessionId),A.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,f,A.opencodeSessionId),(A.claudeSessionId||A.codexSessionId||A.opencodeSessionId)&&A.usage&&this.sessions.recordTurnUsage(e.agentId,p,f,A.usage,A.contextTokens),A.usage){let Z=A.contextTokens,Te=(A.usage.inputTokens||0)+(A.usage.cacheReadTokens||0)+(A.usage.cacheCreateTokens||0);(Z??Te)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${f}: context=${Z??"n/a"} tokens (cumulative turn total=${Te}) \u2014 next turn will rotate`)}if(zn({channel:p,content:`User: ${e.message}`,responseLength:A.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}
|
|
160
|
+
|
|
161
|
+
Agent: ${A.content}`,meta:Uo(v,e.context)})}catch{}an(e.agentId,e.message,A.content,{channel:p,chatId:f,sender:M},this.memoryStore).catch(()=>{}),cs(e.agentId,e.message,A.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=A.billedModel||e.model||i.def.model,ne=e.context?.channel,je=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,A.duration||0,A.usage,e.message.length,A.content.length,!1,J,ne,je),this.log(`[${e.agentId}] completed in ${A.duration}ms`+(A.tokensUsed?` (${A.tokensUsed} tokens)`:""))}return A}catch(y){i.errors++,this.log(`[${e.agentId}] unexpected error: ${y.message}`);let m=Be(y.message);return V={content:"",error:qe(m),errorKind:m.kind},V}finally{i.activeTasks--;let y=i.runningTasks.findIndex(m=>m.id===u.id);y!==-1&&i.runningTasks.splice(y,1),this.taskAborts.delete(u.id),g.done=!0,g.endedAt=new Date;for(let m of g.subscribers)try{m(`
|
|
162
|
+
[task finished]
|
|
163
|
+
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),jo).unref?.();try{let m=g.endedAt,R={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:m.toISOString(),durationMs:m.getTime()-u.startedAt.getTime(),ok:!V?.error,error:V?.error,responseText:V?.content||"",transcript:g.buffer};this.persistTaskRecord(R);let L=(R.responseText||R.error||"").trim();if(L){let U=L.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:U,at:m,ok:R.ok})}}catch(m){this.log(`[${e.agentId}] task history persist failed: ${m?.message}`)}this.messageQueue.markDone(e.agentId,a,c).then(m=>{if(m.length!==0){this.log(`[${e.agentId}] flushing ${m.length} queued message(s)`);for(let R of m){let L=R.originalContext||{channel:R.channel,sender:R.sender,chatId:R.chatId};this.execute({message:R.text,agentId:e.agentId,context:L}).then(U=>this.postQueuedResponseToChannel(e.agentId,L,U)).catch(U=>{this.log(`[${e.agentId}] queued message failed: ${U.message}`)})}}}).catch(m=>{this.log(`[${e.agentId}] queue flush failed: ${m.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=H(process.cwd(),we,this.safe(e.agentId),t);Q(n)||No(n,{recursive:!0});let s=H(n,`${this.safe(e.id)}.json`);Fo(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=H(process.cwd(),we,this.safe(e));if(!Q(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=H(a,l);if(Q(g))try{for(let h of te(g)){if(!h.endsWith(".json"))continue;let w=h.split("-")[0],b=parseInt(w,10);if(!Number.isFinite(b)||b<i||b>n)continue;let x=Math.floor((n-b)/36e5),p=t-1-x;p>=0&&p<t&&o[p]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=H(process.cwd(),we);if(!Q(e))return 0;let t=0;for(let n of te(e)){let s=H(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=H(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(De(H(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=Ho){let t=H(process.cwd(),we);if(!Q(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let o of te(t)){let i=H(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{Lo(H(i,c),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=H(process.cwd(),we,this.safe(e));if(!Q(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=H(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(De(H(a,d),"utf-8")),{transcript:l,responseText:g,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=H(process.cwd(),we,this.safe(e));if(!Q(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=H(n,i,`${s}.json`);if(Q(a))try{return JSON.parse(De(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let s=bn();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 w=s.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(w))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${w}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${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{Cn as a,vn as b,si as c,An as d,dr as e,gr as f,mr as g,yr as h,br as i,Wn as j,Xe as k,Ve as l,tt as m,ee as n,ds as o,io as p,us as q,Pe as r,Po as s,Do as t,_o as u,Oo as v,Eo as w,Ut as x,rc as y,oc as z,Uo as A,Wo as B,Kt as C,vs as D,$s as E,Ko as F,As as G,Ms as H};
|
|
164
|
+
//# sourceMappingURL=chunk-XPXO5K4L.js.map
|