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