agentix-cli 0.103.2 → 0.104.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-voice/Sources/AgentXVoice/Character.swift +31 -10
- package/apps/mac-voice/Sources/AgentXVoice/CharacterMath.swift +6 -0
- package/apps/mac-voice/Sources/AgentXVoice/CharacterSim.swift +4 -3
- package/apps/mac-voice/Sources/AgentXVoice/CharacterSimFrame.swift +3 -0
- package/apps/mac-voice/Sources/AgentXVoice/CharacterView.swift +4 -1
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +2 -0
- package/dist/{agent-MUGC4RZP.js → agent-NPE76XHC.js} +2 -2
- package/dist/{chunk-TYK6LAAG.js → chunk-2X5RPHPN.js} +3 -3
- package/dist/{chunk-UXTAK5WD.js → chunk-DEMIKEFB.js} +51 -51
- package/dist/chunk-DEMIKEFB.js.map +1 -0
- package/dist/{chunk-HVPRCHRG.js → chunk-MZQQVT3G.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-CUET27MW.js → program-X5K2P7EL.js} +4 -4
- package/dist/{registry-NQHC7ZAV.js → registry-T5HSN66G.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-UXTAK5WD.js.map +0 -1
- /package/dist/{agent-MUGC4RZP.js.map → agent-NPE76XHC.js.map} +0 -0
- /package/dist/{chunk-TYK6LAAG.js.map → chunk-2X5RPHPN.js.map} +0 -0
- /package/dist/{chunk-HVPRCHRG.js.map → chunk-MZQQVT3G.js.map} +0 -0
- /package/dist/{program-CUET27MW.js.map → program-X5K2P7EL.js.map} +0 -0
- /package/dist/{registry-NQHC7ZAV.js.map → registry-T5HSN66G.js.map} +0 -0
|
@@ -1,43 +1,43 @@
|
|
|
1
1
|
import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-FZ7VHFL5.js";import{a as fs}from"./chunk-GLQLCBJS.js";import{b as ws}from"./chunk-DP7RTNDM.js";import{a as Ps}from"./chunk-W4YR2RO2.js";import{b as ks,c as Bt,d as Ss,e as vs,h as Cs}from"./chunk-MVLNVMWI.js";import{a as hs}from"./chunk-XHUOWYNY.js";import{a as jt,b as Ts}from"./chunk-J3SOEFRE.js";import{a as Ut,b as Is}from"./chunk-SIU6STB2.js";import{e as As,i as $s,j as Ms,k as Rs}from"./chunk-X5C5W3E4.js";import{a as ss}from"./chunk-WTFNEPJ7.js";import{a as rs,c as os}from"./chunk-MYVHVJWZ.js";import{a as is,b as as,c as cs,d as ds,f as us}from"./chunk-DWADWDMU.js";import{a as ls,b as gs}from"./chunk-23A5K5UW.js";import{g as ps,h as ms}from"./chunk-Q57GZPDA.js";import{a as at,c as Le}from"./chunk-2GIDVZ4H.js";import{q as es,t as ts,v as xe,w as ns}from"./chunk-HE4PDESB.js";import{a as Ne,b as it,f as Ht}from"./chunk-72SZI2UW.js";import{a as we,b as Dt}from"./chunk-FCPTN6NF.js";import{c as Bn,d as Wn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{B as Ft,D as oi,F as Qn,J as ii,P as zn,Q as Xn,R as Oe,S as Yn,T as Vn,V as Zn,ha as ai,z as Jn}from"./chunk-IA3BC7M3.js";import{a as Lt,i as ri}from"./chunk-RJ7DASOU.js";import{g as Nt,h as si}from"./chunk-BRK6M6LA.js";import{a as qn,b as oe,c as Kn,d as Gn,e as Ot}from"./chunk-2QNT5JDS.js";ns();Ht();var Ls="session-continuity",Fs={continues:Ne("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:Ne("Does the new request refer to something stated earlier in the conversation?")};function Hs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Wt(s.message,1200),previousRequest:s.previousMessage?Wt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Wt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function js(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Wt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ht}from"execa";import{spawn as ci}from"node:child_process";import{createHash as di}from"node:crypto";import{createInterface as ui}from"node:readline";var de=class extends Error{},li=s=>ci("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),qt=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(),ui({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
|
-
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Kt=class{constructor(e=li,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=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([f],[b])=>f.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let f=[...this.entries].find(([,b])=>!b.connection.busy);if(!f)throw new de("Codex warm process capacity reached");f[1].connection.close(),this.entries.delete(f[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let h=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),k=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 f={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",{...f,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(f){if(i.close(),!a&&!e.signal?.aborted)throw new de(f.message);return{content:d,codexSessionId:l,usage:u,error:f.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(h),e.signal?.removeEventListener("abort",y),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Us=new Kt;import{execFile as Pi}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function od(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Ws=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=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}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 Te(`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 Te(`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=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=He(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{existsSync as mi,readFileSync as hi}from"fs";import{resolve as fi}from"path";function yi(s){let e=fi(s,"CLAUDE.md");if(!mi(e))return null;try{let t=hi(e,"utf8");return us(t)}catch{return null}}var bi=20*60*1e3,wi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function xi(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(xi({...process.env},e),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:yi(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 d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
|
-
`);let
|
|
4
|
-
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};Ot();ri();Dt();import{resolve as Ks,join as Gs}from"path";var
|
|
2
|
+
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Kt=class{constructor(e=li,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=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([y],[b])=>y.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let y=[...this.entries].find(([,b])=>!b.connection.busy);if(!y)throw new de("Codex warm process capacity reached");y[1].connection.close(),this.entries.delete(y[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,l,u,p=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let m=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 y={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",{...y,...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 I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(y){if(i.close(),!a&&!e.signal?.aborted)throw new de(y.message);return{content:d,codexSessionId:l,usage:u,error:y.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(m),e.signal?.removeEventListener("abort",f),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())}}},Us=new Kt;import{execFile as _i}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function id(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Ws=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=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}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 Te(`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 Te(`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=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=He(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{randomUUID as mi}from"crypto";import{existsSync as hi,readFileSync as fi}from"fs";import{resolve as yi}from"path";function bi(s){let e=yi(s,"CLAUDE.md");if(!hi(e))return null;try{let t=fi(e,"utf8");return us(t)}catch{return null}}var wi=20*60*1e3,xi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Ti(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=this.log=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(Ti({...process.env},e),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:bi(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 d=this.waiters.splice(0);for(let c of d)c(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;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=mi(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
|
+
`);let d=e.deadlineMs??wi,c=o+d,l=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new je(d)),u=!1,p=null;try{for(;;){let f=c-Date.now();if(f<=0)throw l();let m=await this.nextEvent(f);if(m===null&&this.killReason)throw new Ue(this.killReason);if(m===null&&!this.exited)throw l();if(m===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!u){if(m.type==="user"&&m.uuid===i)u=!0,p&&(yield{type:p.type,raw:p});else if(m.type==="system"&&m.subtype==="init")p=m;else if(m.type==="result"){p=null;let T=typeof m.result=="string"?m.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${T.length} chars): ${T.slice(0,120)}`)}continue}if(yield{type:m.type,raw:m},m.type==="result"){this.onResultEvent(m);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},xi);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
|
+
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};Ot();ri();Dt();import{resolve as Ks,join as Gs}from"path";var ki=4e3;function lt(s){try{let e=Gs(Ks(s.root),".agentx","db.sqlite"),t=Lt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=we(),r=s.input.command?s.input.command.slice(0,ki):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
5
5
|
(id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
|
|
6
6
|
verdict, effective_action, mode, severity, approver, ms)
|
|
7
7
|
VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
|
|
8
8
|
@verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:n,ts:Date.now(),agent_id:s.input.agentId??null,task_id:s.taskId??null,tool:s.input.tool,command:r,resolved_target:s.verdict.resolvedTarget,matched_rule:s.verdict.ruleId,verdict:s.verdict.action,effective_action:s.verdict.effectiveAction,mode:s.mode,severity:s.verdict.severity,approver:s.approver??null,ms:s.ms??null}),n}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
|
|
9
|
-
`),null}}function
|
|
9
|
+
`),null}}function wd(s){let e=Gs(Ks(s.root),".agentx","db.sqlite"),t=Lt({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}Ot();var Ii=50,Si=6*60*60*1e3,gt=null,ke=new Map;function Id(s){gt=s===null?null:String(s)}function Qs(){return gt}function vi(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function zs(s,e,t){if(!oe(s))return{args:[]};if(!gt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:vi(gt,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function Xs(s,e){return!oe(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Ci(s){for(let[e,t]of ke)s-t.at>Si&&ke.delete(e)}function Ai(s,e){let t=Date.now();Ci(t);let n=ke.get(s)??{at:t,blocks:[]};n.blocks.length<Ii&&n.blocks.push(e),n.at=t,ke.set(s,n)}function Ys(s){if(!s)return[];let e=ke.get(s);return ke.delete(s),e?.blocks??[]}function Js(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Sd(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let o=qn.safeParse(e.level),i=o.success?Kn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",d=i.ruleId??"autonomy",c=i.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:d,reason:c},u={matched:!0,action:"deny",effectiveAction:"deny",ruleId:d,severity:"high",message:c,resolvedTarget:null};return lt({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:u,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Ai(e.taskId,l),{stdout:Js(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${c} (rule: ${d}). 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:Js(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}Vn();var $i=6*60*60*1e3,Be=new Map;function Mi(s){for(let[e,t]of Be)s-t.at>$i&&Be.delete(e)}function Vs(s,e){let t=Date.now();Mi(t),Be.set(s,{at:t,limits:e})}function Zs(s){Be.delete(s)}function Ri(s,e,t){let n=new URLSearchParams({person:"1",task:e,...t?{agent:t}:{}}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${n}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function er(s,e,t){let n=Qs();if(!n)return{error:"this person's tool and skill limits cannot be enforced: guard hook endpoint is not configured"};let r={matcher:"*",hooks:[{type:"command",command:Ri(n,e,t),timeout:15}]},o=[...s],i=o.indexOf("--settings");if(i===-1)return o.push("--settings",JSON.stringify({hooks:{PreToolUse:[r]}})),{args:o};let a=JSON.parse(o[i+1]);return a.hooks=a.hooks??{},a.hooks.PreToolUse=[...a.hooks.PreToolUse??[],r],o[i+1]=JSON.stringify(a),{args:o}}function tr(s){return s==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${s??"unknown"}); refusing to run without them`}function Jt(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Pi(s,e,t){if(s.tools.some(n=>Oe(n,e)))return{skill:null,what:e};if(e==="Skill"){let n=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(n&&s.skills.some(r=>Oe(r,n)))return{skill:n,what:`the skill ${n}`}}return null}function Md(s,e){let t=s.tool_name??"unknown",n=s.tool_input??{};try{let r=e.taskId?Be.get(e.taskId):void 0;if(!r)return{stdout:Jt("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=Pi(o,t,n);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,d={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return lt({root:e.root,input:{tool:t,command:typeof n.command=="string"?n.command:t,agentId:e.agentId},verdict:d,mode:"enforce",taskId:e.taskId??null}),{stdout:Jt(`[agentx-people] Blocked: ${a} here (set by the owner). Do not work around it. Finish what you can without it and say in your answer what was not done and why.`),blocked:{personId:o.personId,tool:t,skill:i.skill,reason:a}}}catch(r){return{stdout:Jt(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var Ei=5e3;function Q(s){let e=ct(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
10
10
|
`)}return{error:dt(e),errorKind:e.kind}}function dr(){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 mt(){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 nr(){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 le(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let d of r.peers){let c=d.handle?` (mention: ${d.handle})`:"",l=d.role?` \u2014 ${d.role}`:"";o.push(`\u2022 ${d.name}${c}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
|
|
11
11
|
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
12
12
|
`)}function ur(s,e,t,n,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let d=r||s.model;return d&&a.push("--model",d),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Qt(s,e){return!e||e.trim().length===0?s:`[System]
|
|
13
13
|
${e.trim()}
|
|
14
14
|
|
|
15
15
|
[User]
|
|
16
|
-
${s}`}function
|
|
17
|
-
`))if(i.trim())try{let a=JSON.parse(i);t=Xt(a)||t,n=pr(a)||n,r=Yt(a)||r,o=mr(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function mr(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return rr(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return rr(e)}}}function rr(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function
|
|
18
|
-
`)}function
|
|
19
|
-
`);L=v.pop()||"";for(let w of v)if(w.trim())try{let x=JSON.parse(w);if(o)try{o(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let N=x.message.usage,M=(N.input_tokens||0)+(N.cache_read_input_tokens||0)+(N.cache_creation_input_tokens||0);M>0&&(
|
|
16
|
+
${s}`}function Di(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s.model;return i&&o.push("--model",i),r&&o.push("--session",r),s.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Qt(e,n)),o}function Oi(s){if(!s||typeof s!="object"||s.type!=="error")return;let e=s.error?.message??s.error??s.message??s.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function sr(s){return JSON.stringify(s)}function lr(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${sr(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(sr).join(",")}]`]}function gr(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...lr()),i||a.push("--color","never");let d=n||s.model;return d&&a.push("--model",d),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Qt(e,r)),a}function ft(s,e){let t=at(s.workspace),n=t.HOME||process.env.HOME,r=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),zt(t,e)}function zt(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(s.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function yt(s={}){return{channel:s.channel||"api",chatId:s.chatId||s.group||s.sender||"default"}}function Ni(s,e){let t=ft(s,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...n.mcp||{}};for(let[i,a]of Object.entries(s.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:r}),t}function Li(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function ue(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Xt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ue(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ue(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ue(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ue(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Xt(n,e+1);if(r)return r}}function pr(s){if(!(!s||typeof s!="object"))return typeof s.model=="string"&&s.model||typeof s.msg?.model=="string"&&s.msg.model||typeof s.message?.model=="string"&&s.message.model||typeof s.response?.model=="string"&&s.response.model||void 0}function Yt(s,e=0){if(!(!s||typeof s!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=s[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[s.msg,s.message,s.response,s.result,s.item]){let n=Yt(t,e+1);if(n)return n}}}function Fi(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
|
|
17
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=Xt(a)||t,n=pr(a)||n,r=Yt(a)||r,o=mr(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function mr(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return rr(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return rr(e)}}}function rr(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function Hi(s){let e=s.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function Vt(s,e,t,n,r){let o=Hi(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${s} via=${r} model=${i} perm=${o.summary}${a}
|
|
18
|
+
`)}function ji(s){try{let e=JSON.parse(s);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function Ui(s){try{let e=JSON.parse(s),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0}}catch{return{text:s}}}async function hr(s,e,t,n,r){let o=Date.now(),i=le(s,e,t),a=yr(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=ur(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Vt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:p,exitCode:f,killed:m}=await new Promise(b=>{let I=Le(zt(at(s.workspace),e),s.billing),E=!1,_=_i("claude",d,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...I,HOME:I.HOME||"/home/"+(I.USER||"user")}},(C,O,F)=>{b({stdout:O||"",stderr:F||"",exitCode:C?C.code??1:0,killed:E})});if(_.stdin?.end(),r){let C=()=>{E=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{_.kill("SIGTERM")}catch{}setTimeout(()=>{try{_.killed||_.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?C():r.addEventListener("abort",C,{once:!0})}});if(m)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&f!==0){let b,I=Date.now()-o;return f===143&&I<l-Ei?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(I/1e3)}s, before its ${Math.round(l/6e4)}m time limit`,errorKind:"interrupted",duration:I}:(f===143?b=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:f==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?b=dr():b=p?.trim()||`Claude Code exited with code ${f}`,{content:"",...Q(b),duration:Date.now()-o})}let T=ji(u);if(T)return{content:"",...Q(T),duration:Date.now()-o};let y=Ui(u);return{content:y.text,duration:Date.now()-o,claudeSessionId:y.sessionId,usage:y.usage,numTurns:y.numTurns,billedModel:y.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function fr(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let d=le(s,e,n),c=yr(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let l=ur(s,d,!0,r,e.model,e.systemPromptAppend,c.args);Vt(e.agentId,s,e.model,r,"stream");let u="",p,f,m,T,y,b;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),E=Le(zt(at(s.workspace),e),s.billing),_=ht("claude",l,{cwd:s.workspace,timeout:I,reject:!1,env:E,extendEnv:!1,buffer:!1,stdin:"ignore"}),C=()=>{},O=new Promise(A=>{C=A}),F=!1,D;if(i){let A=()=>{F=!0,D=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{_.kill("SIGTERM")}catch{}setTimeout(()=>{try{_.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?A():i.addEventListener("abort",A,{once:!0})}let L="",H=new We("utf8");_.stdout&&_.stdout.on("data",A=>{L+=H.write(A);let v=L.split(`
|
|
19
|
+
`);L=v.pop()||"";for(let w of v)if(w.trim())try{let x=JSON.parse(w);if(o)try{o(x)}catch{}if(x.type==="assistant"&&x.message?.usage){let N=x.message.usage,M=(N.input_tokens||0)+(N.cache_read_input_tokens||0)+(N.cache_creation_input_tokens||0);M>0&&(T=M)}if(x.type==="assistant"&&x.message?.content){for(let N of x.message.content)if(N.type==="text"&&N.text){let M=N.text.slice(u.length);M&&(u=N.text,t(M,u))}}if(x.type==="content_block_delta"&&x.delta?.text&&(u+=x.delta.text,t(x.delta.text,u)),x.type==="result"&&C(),x.type==="result"&&x.result){if(x.is_error&&typeof x.result=="string")b=x.result;else{let N=(typeof x.result=="string",x.result);if(typeof N=="string"&&N.length>u.length){let M=N.slice(u.length);u=N,M&&t(M,u)}}x.usage&&(f={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.model=="string"&&(p=x.model),typeof x.session_id=="string"&&(m=x.session_id),typeof x.num_turns=="number"&&(y=x.num_turns)}x.type==="system"&&x.subtype==="init"&&(typeof x.model=="string"&&(p=x.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${x.apiKeySource} version=${x.claude_code_version} model=${x.model} permMode=${x.permissionMode}
|
|
20
20
|
`))}catch{w.trim()&&!w.startsWith("{")&&(u+=w+`
|
|
21
21
|
`,t(w+`
|
|
22
|
-
`,u))}});let j=await
|
|
23
|
-
`);I=w.pop()||"";for(let x of w)if(x.trim())try{let N=JSON.parse(x);if(o)try{o(N)}catch{}p=Xt(N)||p,
|
|
22
|
+
`,u))}});let j=await Qi(_,O),K=H.end();if(K&&(L+=K),F)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&j.stdout&&(u=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!u){let A=typeof j.stderr=="string"?j.stderr:"",v=j,w;return v.timedOut?w=`Claude Code timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:v.signal?w=A.trim()||`Claude Code killed by signal ${v.signal}`:v.code==="ENOENT"||/ENOENT|spawn claude/i.test((v.shortMessage||"")+" "+A)?w=dr():w=A.trim()||`Claude Code exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-a}}return b?{content:"",...Q(b),duration:Date.now()-a,usage:f,contextTokens:T,numTurns:y,billedModel:p,claudeSessionId:m}:{content:u,duration:Date.now()-a,usage:f,contextTokens:T,numTurns:y,billedModel:p,claudeSessionId:m}}catch(I){return{content:u||"",...Q(I.message),duration:Date.now()-a,usage:f,contextTokens:T,numTurns:y,billedModel:p,claudeSessionId:m}}}async function Bi(s,e,t,n){let r=Date.now(),o=le(s,e,t),i=or(pt(cr(),"agentx-codex-")),a=pt(i,"last-message.txt"),d=gr(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let c=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await ht("codex",d,{cwd:s.workspace,timeout:c,reject:!1,env:ft(s,e),extendEnv:!1,stdin:"ignore"}),u=Fi(l.stdout);if(l.exitCode!==0||u.apiError){let f=l,m;return f.timedOut?m=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:u.apiError?m=u.apiError:f.signal?m=l.stderr.trim()||`Codex CLI killed by signal ${f.signal}`:f.code==="ENOENT"||/ENOENT|spawn codex/i.test((f.shortMessage||"")+" "+l.stderr)?m=mt():m=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${f.exitCode??"unknown"}`,{content:"",...Q(m),duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}let p="";try{p=ir(a,"utf8").trim()}catch{}return p||(p=l.stdout.trim()),{content:p,duration:Date.now()-r,usage:u.usage,billedModel:u.billedModel,codexSessionId:u.sessionId||n}}catch(c){let l=/ENOENT|spawn codex/i.test(c?.message||"")?mt():c?.message;return{content:"",...Q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{ar(i,{recursive:!0,force:!0})}}async function Wi(s,e,t,n,r,o){let i=Date.now(),a=le(s,e,n),d=or(pt(cr(),"agentx-codex-")),c=pt(d,"last-message.txt"),l=gr(s,a,!0,e.model,e.systemPromptAppend,c,r),u="",p,f,m,T;try{let y=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),b=ht("codex",l,{cwd:s.workspace,timeout:y,reject:!1,env:ft(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let I="",E="",_=!1,C=new We("utf8"),O=new We("utf8"),F=Math.min(y,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),D,L=()=>{D&&clearTimeout(D),D=setTimeout(()=>{_=!0,b.kill("SIGTERM",{forceKillAfterTimeout:5e3})},F)};L(),b.stderr?.on("data",v=>{L(),E+=O.write(v),E.length>16e3&&(E=E.slice(-16e3))}),b.stdout?.on("data",v=>{L(),I+=C.write(v);let w=I.split(`
|
|
23
|
+
`);I=w.pop()||"";for(let x of w)if(x.trim())try{let N=JSON.parse(x);if(o)try{o(N)}catch{}p=Xt(N)||p,f=pr(N)||f,m=Yt(N)||m,T=mr(N)||T;let M=Li(N);if(M&&M!==u){let V=M.startsWith(u)?M.slice(u.length):M;u=M.startsWith(u)?M:u+M,V&&t(V,u)}}catch{u+=x+`
|
|
24
24
|
`,t(x+`
|
|
25
|
-
`,u)}});let H=await b;D&&clearTimeout(D);let j=C.end();j&&(I+=j);let K=O.end();if(K&&(E+=K),H.exitCode!==0&&!u||
|
|
25
|
+
`,u)}});let H=await b;D&&clearTimeout(D);let j=C.end();j&&(I+=j);let K=O.end();if(K&&(E+=K),H.exitCode!==0&&!u||T){let v=E||(typeof H.stderr=="string"?H.stderr:""),w=H,x;return _?x=`Codex CLI produced no output for ${Math.round(F/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.`:w.timedOut?x=`Codex CLI timed out after ${Math.round(y/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?x=T:w.signal?x=v.trim()||`Codex CLI killed by signal ${w.signal}`:w.code==="ENOENT"||/ENOENT|spawn codex/i.test((w.shortMessage||"")+" "+v)?x=mt():x=v.trim()||`Codex CLI exited with code ${w.exitCode??"unknown"}`,{content:"",...Q(x),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}let A="";try{A=ir(c,"utf8").trim()}catch{}if(A&&A!==u){let v=A.startsWith(u)?A.slice(u.length):A;u=A,v&&t(v,u)}return{content:u,duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}catch(y){let b=/ENOENT|spawn codex/i.test(y?.message||"")?mt():y?.message;return{content:u,...Q(b||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:m||r}}finally{ar(d,{recursive:!0,force:!0})}}async function qi(s,e,t,n,r,o,i,a){let d=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let c=le(s,e,n),l=Di(s,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),u="",p,f=e.freshSession?void 0:r,m,T,y=!0,b;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),E=Ni(s,e);if(s.persistentProcess)try{T=await os.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:E,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",T.url),E=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-d})}catch(v){if(!(v instanceof rs))throw v;v.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:v.message})}if(i?.aborted)throw new Error("task cancelled by operator");let _=ht("opencode",l,{cwd:s.workspace,timeout:I,reject:!1,env:E,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let C=!1,O,F=()=>{T?.invalidate(),C=!0,O=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{_.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",F,{once:!0}),b=()=>i?.removeEventListener("abort",F),i?.aborted&&F();let D="",L="",H=new We("utf8"),j=new We("utf8"),K=v=>{if(v.trim())try{let w=JSON.parse(v);try{o?.(w)}catch{}typeof w.sessionID=="string"&&(f=w.sessionID);let x=w.type==="text"&&typeof w.part?.text=="string"?w.part.text:void 0;x&&(u||o?.({type:"opencode.first_output",elapsedMs:Date.now()-d,reused:T?.reused??!1}),u+=x,t?.(x,u));let N=w.type==="reasoning"&&typeof w.part?.text=="string"?w.part.text:void 0;N&&a?.(N);let M=w.type==="step_finish"?w.part?.tokens:void 0;M&&(p={inputTokens:ue(M.input),outputTokens:ue(M.output),cacheReadTokens:ue(M.cache?.read),cacheCreateTokens:ue(M.cache?.write)}),m=Oi(w)||m}catch{u+=v+`
|
|
26
26
|
`,t?.(v+`
|
|
27
27
|
`,u)}};_.stdout?.on("data",v=>{D+=H.write(v);let w=D.split(`
|
|
28
|
-
`);D=w.pop()||"";for(let x of w)K(x)}),_.stderr?.on("data",v=>{L+=j.write(v)});let A=await _;if(i&&i.removeEventListener("abort",F),D+=H.end(),D.trim()&&K(D),L+=j.end(),C)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:
|
|
28
|
+
`);D=w.pop()||"";for(let x of w)K(x)}),_.stderr?.on("data",v=>{L+=j.write(v)});let A=await _;if(i&&i.removeEventListener("abort",F),D+=H.end(),D.trim()&&K(D),L+=j.end(),C)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:f};if(A.exitCode!==0||m){let v=A,w;return v.timedOut?w=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:m?w=m:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+L)?w=nr():w=L.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-d,usage:p,opencodeSessionId:f}}return y=!1,{content:u.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||s.model,opencodeSessionId:f}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?nr():I?.message;return{content:u,...Q(E||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:f}}finally{b?.(),T?.release(y)}}async function Ki(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=le(s,e,n),d="",c=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of c)l.type==="result"&&l.subtype==="success"&&(d=l.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Gi(s,e,t,n,r,o,i,a,d){let c=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,f=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(y))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let m=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);m.unref?.();let T=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let y=s.provider||"claude-code",b=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-NPE76XHC.js"),A="",v,w,x,N;for await(let M of K(F)){if(d)try{d(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?p?T():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:A||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:D}=await import("./agent-NPE76XHC.js"),L=await D(F),H=L.inputTokens,j=L.outputTokens;if((H===void 0||j===void 0)&&L.tokensUsed){let K=L.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?T():y?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(m),a&&a.removeEventListener("abort",f)}}var Ji=1e3;async function Qi(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),Ji),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function zi(s,e,t,n,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=yt(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,f=!1;try{let A=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),f=a.list().length>A}catch(A){return A instanceof Te,null}f&&Vt(e.agentId,s,e.model,n,"persistent");let m=le(s,e,t),T="",y,b,I,E,_,C,O,F="",D="",L=A=>{if(!i||!A)return;let v;if(D&&A.startsWith(D)?v=A.slice(D.length):v=F&&!F.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
|
-
${A}`:A,D=A,!!v){F+=v;try{i(v,F)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:
|
|
33
|
+
${A}`:A,D=A,!!v){F+=v;try{i(v,F)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:m,taskId:e.taskId??"unknown",deadlineMs:A})){if(K=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let w=v.raw.message?.content??[];for(let N of w)N.type==="text"&&typeof N.text=="string"?(T=N.text,L(N.text)):N.type==="tool_use"&&(D="");let x=v.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(E=N)}}if(v.type==="result"){let w=v.raw;if(w.is_error){let x=Q(typeof w.result=="string"?w.result:"claude error");y=x.error,b=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(T=w.result,F||L(w.result));typeof w.session_id=="string"&&(O=w.session_id),w.usage&&(I={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(_=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(H)y="task cancelled by operator",b="cancelled";else if(K)if(A instanceof Ue)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,b="interrupted";else if(A instanceof je){let v=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);y=v.error,b=v.errorKind}else{let v=Q(`persistent claude process error: ${A?.message||String(A)}`);y=v.error,b=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!y&&(y="task cancelled by operator",b="cancelled"),{content:H?"":T,error:y,errorKind:b,duration:Date.now()-d,usage:I,contextTokens:E,numTurns:_,billedModel:C,claudeSessionId:O}}function yr(s){let e=oe(s.autonomy);if(!e&&!s.personLimits)return{args:[]};if(!s.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?zs(s.autonomy,s.agentId,s.taskId):{args:[]};return"error"in t||!s.personLimits?t:er(t.args,s.taskId,s.agentId)}function Xi(s){return oe(s.autonomy)||!!s.personLimits}async function Yi(s,e,t,n,r,o,i){let a=oe(e.autonomy)?e.autonomy:void 0,d=a&&Xs(a,s.tier)||e.personLimits&&tr(s.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:c,message:a?`${Gn(a)}
|
|
34
34
|
|
|
35
35
|
${e.message}`:e.message},u=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${u} task=${c} via=spawn (persistent process bypassed)
|
|
36
|
-
`),e.personLimits&&Vs(c,e.personLimits);try{let p=t?await fr(s,l,t,n,r,o,i):await hr(s,l,n,r,i);if(!a)return p;let
|
|
37
|
-
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),d;try{d=en(this.sessionsDir).filter(_=>_.startsWith(`${a}:`)&&_.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let c=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,p=d.filter(_=>{let C=_.match(u);if(!C)return!1;let O=C[1];return O>=c&&O<=l}),
|
|
38
|
-
${
|
|
36
|
+
`),e.personLimits&&Vs(c,e.personLimits);try{let p=t?await fr(s,l,t,n,r,o,i):await hr(s,l,n,r,i);if(!a)return p;let f=Ys(c);return{...p,autonomy:a,...f.length?{autonomyBlocks:f}:{}}}finally{e.personLimits&&Zs(c)}}async function br(s,e,t,n,r,o,i,a,d){if(Xi(e))return Yi(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let c=await zi(s,e,r,o,i,a,n);if(c!==null)return c}return n?fr(s,e,n,r,o,i,a):hr(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let c=await Us.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:ft(s,e),args:lr(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Qt(le(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...c,...c.error?Q(c.error):{}}}catch(c){if(!(c instanceof de))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Wi(s,e,n,r,o,i):Bi(s,e,r,o);case"opencode":return qi(s,e,n,r,o,i,a,d);case"sdk":{let c=s.provider||"claude",l=t[c]?.apiKey;return l?Ki(s,e,l,r):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=s.provider||"claude-code",l=t[c],u=l?.apiKey;return Gi(s,e,u,r,n,{thinking:l?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as Ie,writeFileSync as wr,mkdirSync as Vi,existsSync as Zt,readdirSync as en}from"fs";import{resolve as Se}from"path";var tn=12e3,qe=30,Zi=720,ea=40,ta=18e4,na="[Compacted conversation summary",sa=7*864e5,ra=[/\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 oa(s){return s?ra.some(e=>e.test(s)):!1}var ia=[{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 Tr(s){if(!s)return null;let e=0;for(let t of ia)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function xr(s,e,t,n){if(s.length===0)return!1;let r=s[s.length-1];return r.role===e&&(r.name??"")===t&&r.content===n}function kr(s,e){let t=(s??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function Ir(s,e,t){if(t<=0)return[];let n=(s??[]).filter(i=>i.role==="user"),r=n[n.length-1],o=(r&&r.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function aa(s){let e=s.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let r=Math.floor(n/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var bt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Se(e,".agentx/sessions"),Zt(this.sessionsDir)||Vi(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zi),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ea),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ta)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let d=this.adapterResolver(t);if(!d?.seedHistory)return;let c=(async()=>{try{let l=await d.seedHistory(n,{maxMessages:qe,maxChars:tn});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,c);try{await c}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Se(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let r=this.sessionKey(e,t,n);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(Zt(o))try{let c=JSON.parse(Ie(o,"utf-8"));return this.cache.set(r,c),c}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),d={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,d),this.save(d),d}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!Zt(i))return null;try{return JSON.parse(Ie(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);xr(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,r){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,r){let o=this.getSession(e,t,n);xr(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,r={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??qe),a=Math.max(200,r.maxChars??tn),d=[],c=0;for(let p=o.messages.length-1;p>=0&&d.length<i;p--){let f=o.messages[p];if(c+=f.content.length,d.push(f),c>=a)break}d.reverse();let l=[`[Conversation history for today (${o.day})]`],u="";for(let p of d){let f=aa(p.timestamp);f!==u&&(l.push(`\u2014 ${f} \u2014`),u=f);let m=p.name||(p.role==="user"?"User":"Agent");l.push(`${m}: ${p.content}`)}return l.push("[End of history \u2014 respond to the latest message above]"),l.push(""),l.join(`
|
|
37
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),d;try{d=en(this.sessionsDir).filter(_=>_.startsWith(`${a}:`)&&_.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let c=o.slice(0,10),l=i.slice(0,10),u=/:(\d{4}-\d{2}-\d{2})\.json$/,p=d.filter(_=>{let C=_.match(u);if(!C)return!1;let O=C[1];return O>=c&&O<=l}),f=[],m=0,T=e.query?.toLowerCase(),y=e.participants?.length?new Set(e.participants):void 0;for(let _ of p){let C;try{C=JSON.parse(Ie(Se(this.sessionsDir,_),"utf-8"))}catch{continue}if(C.agentId===e.agentId&&!(e.channel&&C.channel!==e.channel)&&!(e.chatId&&C.chatId!==e.chatId))for(let O of C.messages)m++,!(!O.timestamp||O.timestamp<o||O.timestamp>=i)&&(y&&O.role==="user"&&!y.has(O.name??"")||T&&!O.content.toLowerCase().includes(T)||f.push({ts:O.timestamp,role:O.role,senderName:O.name??"",content:O.content,channel:C.channel,chatId:C.chatId,day:C.day,sessionFile:_}))}f.sort((_,C)=>C.ts.localeCompare(_.ts));let b=f.slice(0,t),I=b.length>0?b[b.length-1].ts:null,E=f.length>t;return{turns:b,oldestTs:I,hasMore:E,totalScanned:m}}recentByChatId(e){let t=Math.min(Math.max(e.limit??qe,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=en(this.sessionsDir).filter(u=>u.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(u=>{if(!u.includes(i))return!1;let p=u.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),d=[];for(let u of a){let p;try{p=JSON.parse(Ie(Se(this.sessionsDir,u),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let f of p.messages)!f.timestamp||f.timestamp<n||d.push({ts:f.timestamp,role:f.role,senderName:f.name??"",content:f.content,agentId:p.agentId,sessionFile:u})}let c=new Set,l=[];for(let u of d){let p=`${u.ts}|${u.role}|${u.senderName}|${u.content}`;c.has(p)||(c.add(p),l.push(u))}return l.sort((u,p)=>u.ts.localeCompare(p.ts)),l.slice(-t)}sessionIdleMs(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:Date.now()-new Date(r.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,r){if(r!==void 0&&r!==""&&!oa(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=en(this.sessionsDir).filter(c=>c.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&c.includes(o)&&c.endsWith(".json")),d=[];for(let c of a)try{let l=JSON.parse(Ie(Se(this.sessionsDir,c),"utf-8"));if(l.id===i||l.messages.length===0)continue;let u=l.messages.slice(-4),f=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,m=u.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);d.push(`From ${f} (${l.channel}):
|
|
38
|
+
${m.join(`
|
|
39
39
|
`)}`)}catch{}return d.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...d,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
40
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:d}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:n});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(ta)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Se(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ie(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},wr(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>na?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>qe&&(e.messages=e.messages.slice(-qe));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>tn&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&me.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);wr(t,JSON.stringify(e,null,2))}catch{}}};var wt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as Ke,writeFileSync as Sr,appendFileSync as aa,existsSync as ve,mkdirSync as ca}from"fs";import{resolve as Ce}from"path";var Cr={"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}},Ar=2e5,da=1.5;function ua(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function $r(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Ar?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var vr=500,la=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,ca(this.dir,{recursive:!0}),this.pricing=ga()}getPricing(){return this.pricing}static calculateCost(e,t,n=Cr){let r=ua(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,d=e.tier2CacheReadTokens||0,c=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+d/1e6*o.cacheRead+c/1e6*o.cacheCreate;return l+u*da}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,d,c){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let p=0,y=0,h=0,k=0,f=0,b=0,I=0,E=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Ar?(f=n.inputTokens,b=n.outputTokens,I=n.cacheReadTokens,E=n.cacheCreateTokens):(p=n.inputTokens,y=n.outputTokens,h=n.cacheReadTokens,k=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),y=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=y,u.cacheReadTokens+=h,u.cacheCreateTokens+=k,u.tier2InputTokens=(u.tier2InputTokens||0)+f,u.tier2OutputTokens=(u.tier2OutputTokens||0)+b,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+E,i&&u.errors++,u.byChannel||(u.byChannel={});let _=(d||"other").toLowerCase(),C=u.byChannel[_]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};C.tasks++,C.totalDuration+=t,C.inputTokens+=p,C.outputTokens+=y,C.cacheReadTokens+=h,C.cacheCreateTokens+=k,C.tier2InputTokens+=f,C.tier2OutputTokens+=b,C.tier2CacheReadTokens+=I,C.tier2CacheCreateTokens+=E,i&&C.errors++,u.byChannel[_]=C,c&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(c)||(u.sessionKeys.push(c),u.sessionKeys.length>vr&&u.sessionKeys.splice(0,u.sessionKeys.length-vr))),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(ve(t))try{return this.cache=JSON.parse(Ke(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ve(t))return null;try{return JSON.parse(Ke(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,d=0,c=0,l="",u=0,p={},y={},h={};for(let[k,f]of Object.entries(n.agents)){let b=this.cost(f);p[k]=b,r+=f.tasks,o+=(f.inputTokens||0)+(f.tier2InputTokens||0),i+=(f.outputTokens||0)+(f.tier2OutputTokens||0),a+=(f.cacheReadTokens||0)+(f.tier2CacheReadTokens||0),d+=(f.cacheCreateTokens||0)+(f.tier2CacheCreateTokens||0),c+=b,b>u&&(u=b,l=k);let I=f.sessionKeys?.length||0;y[k]={sessions:I,avgTasksPerSession:I>0?f.tasks/I:f.tasks};for(let[E,_]of Object.entries(f.byChannel||{})){let C=this.cost(_,f.model);h[E]=(h[E]||0)+C}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:d,totalCost:c,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:y,byChannel:h}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=c=>c<.01?c.toFixed(4):c.toFixed(2),o=c=>c>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}K`:String(c),i=Object.entries(e.agentCosts).sort(([,c],[,l])=>l-c).map(([c,l])=>{let u=e.agentSessionStats[c],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${c}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,c],[,l])=>l-c).map(([c,l])=>`${c}: $${r(l)}`).join(", "),d=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;ve(n)?aa(n,d+`
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:d}=await import("./compaction-MECSN36J.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:n});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(na)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Se(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ie(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},wr(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>sa?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>qe&&(e.messages=e.messages.slice(-qe));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>tn&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&me.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);wr(t,JSON.stringify(e,null,2))}catch{}}};var wt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as Ke,writeFileSync as Sr,appendFileSync as ca,existsSync as ve,mkdirSync as da}from"fs";import{resolve as Ce}from"path";var Cr={"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}},Ar=2e5,ua=1.5;function la(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function $r(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Ar?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var vr=500,ga=".agentx/pricing/custom.json",Ae=class{dir;cache=null;pricing;constructor(e=Ce(process.cwd(),".agentx/usage")){this.dir=e,da(this.dir,{recursive:!0}),this.pricing=pa()}getPricing(){return this.pricing}static calculateCost(e,t,n=Cr){let r=la(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,d=e.tier2CacheReadTokens||0,c=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+d/1e6*o.cacheRead+c/1e6*o.cacheCreate;return l+u*ua}cost(e,t){return Ae.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,d,c){let l=this.today(),u=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};u.tasks++,u.totalDuration+=t,a&&(u.model=a);let p=0,f=0,m=0,T=0,y=0,b=0,I=0,E=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Ar?(y=n.inputTokens,b=n.outputTokens,I=n.cacheReadTokens,E=n.cacheCreateTokens):(p=n.inputTokens,f=n.outputTokens,m=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),f=Math.ceil(o/4)),u.inputTokens+=p,u.outputTokens+=f,u.cacheReadTokens+=m,u.cacheCreateTokens+=T,u.tier2InputTokens=(u.tier2InputTokens||0)+y,u.tier2OutputTokens=(u.tier2OutputTokens||0)+b,u.tier2CacheReadTokens=(u.tier2CacheReadTokens||0)+I,u.tier2CacheCreateTokens=(u.tier2CacheCreateTokens||0)+E,i&&u.errors++,u.byChannel||(u.byChannel={});let _=(d||"other").toLowerCase(),C=u.byChannel[_]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};C.tasks++,C.totalDuration+=t,C.inputTokens+=p,C.outputTokens+=f,C.cacheReadTokens+=m,C.cacheCreateTokens+=T,C.tier2InputTokens+=y,C.tier2OutputTokens+=b,C.tier2CacheReadTokens+=I,C.tier2CacheCreateTokens+=E,i&&C.errors++,u.byChannel[_]=C,c&&(u.sessionKeys||(u.sessionKeys=[]),u.sessionKeys.includes(c)||(u.sessionKeys.push(c),u.sessionKeys.length>vr&&u.sessionKeys.splice(0,u.sessionKeys.length-vr))),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(ve(t))try{return this.cache=JSON.parse(Ke(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!ve(t))return null;try{return JSON.parse(Ke(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,d=0,c=0,l="",u=0,p={},f={},m={};for(let[T,y]of Object.entries(n.agents)){let b=this.cost(y);p[T]=b,r+=y.tasks,o+=(y.inputTokens||0)+(y.tier2InputTokens||0),i+=(y.outputTokens||0)+(y.tier2OutputTokens||0),a+=(y.cacheReadTokens||0)+(y.tier2CacheReadTokens||0),d+=(y.cacheCreateTokens||0)+(y.tier2CacheCreateTokens||0),c+=b,b>u&&(u=b,l=T);let I=y.sessionKeys?.length||0;f[T]={sessions:I,avgTasksPerSession:I>0?y.tasks/I:y.tasks};for(let[E,_]of Object.entries(y.byChannel||{})){let C=this.cost(_,y.model);m[E]=(m[E]||0)+C}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:d,totalCost:c,topAgent:l,topCost:u,agentCosts:p,agentSessionStats:f,byChannel:m}}appendToTokenCosts(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md"),r=c=>c<.01?c.toFixed(4):c.toFixed(2),o=c=>c>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}K`:String(c),i=Object.entries(e.agentCosts).sort(([,c],[,l])=>l-c).map(([c,l])=>{let u=e.agentSessionStats[c],p=u&&u.sessions>0?` (${u.sessions}s, ${u.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${c}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,c],[,l])=>l-c).map(([c,l])=>`${c}: $${r(l)}`).join(", "),d=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;ve(n)?ca(n,d+`
|
|
41
41
|
`):Sr(n,`# Token Costs
|
|
42
42
|
|
|
43
43
|
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
@@ -46,18 +46,18 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
|
46
46
|
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
47
47
|
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
48
48
|
`+d+`
|
|
49
|
-
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=Ke(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(t))return null;try{let r=Ke(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let d=0;d<n;d++){let c=a.toISOString().slice(0,10);if(o&&c<=o)break;i.push(c),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let d of i){if(this.hasTokenCostsEntry(d,t.filePath))continue;let c=this.generateDailyReport(d);!c||c.totalTasks===0||(this.appendToTokenCosts(c,t.filePath),r.push(d))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,d=0,c={},l={};for(let
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(n))return!1;try{let r=Ke(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Ce(process.cwd(),".agentx/TOKEN_COSTS.md");if(!ve(t))return null;try{let r=Ke(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let d=0;d<n;d++){let c=a.toISOString().slice(0,10);if(o&&c<=o)break;i.push(c),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let d of i){if(this.hasTokenCostsEntry(d,t.filePath))continue;let c=this.generateDailyReport(d);!c||c.totalTasks===0||(this.appendToTokenCosts(c,t.filePath),r.push(d))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,d=0,c={},l={};for(let m=0;m<e;m++){let T=new Date(Date.now()-m*864e5).toISOString().slice(0,10),y=this.getDate(T);if(y)for(let[b,I]of Object.entries(y.agents)){let E=this.cost(I);t+=I.tasks;let _=(I.inputTokens||0)+(I.tier2InputTokens||0),C=(I.outputTokens||0)+(I.tier2OutputTokens||0),O=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),F=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=_,r+=C,o+=O,i+=F,a+=I.errors,d+=E;let D=c[b]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};D.tasks+=I.tasks,D.input+=_,D.output+=C,D.cacheRead+=O,D.cacheCreate+=F,D.total=D.input+D.output+D.cacheRead+D.cacheCreate,D.totalDuration+=I.totalDuration,D.avgDuration=D.totalDuration/D.tasks,D.cost+=E,D.sessions+=I.sessionKeys?.length||0,I.model&&(D.model=I.model),c[b]=D;for(let[L,H]of Object.entries(I.byChannel||{})){let j=this.cost(H,I.model),K=l[L]||{tasks:0,cost:0};K.tasks+=H.tasks,K.cost+=j,l[L]=K}}}let u=n+r+o+i,p=o+i>0?o/(o+i):0,f={};for(let[m,T]of Object.entries(c))f[m]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:u,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:d,byAgent:c,byChannel:l,sessionStats:f}}filePath(e){return Ce(this.dir,`${e}.json`)}save(e){try{Sr(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function pa(){let s=JSON.parse(JSON.stringify(Cr));try{let e=Ce(process.cwd(),ga);if(!ve(e))return s;let t=JSON.parse(Ke(e,"utf-8"));for(let[n,r]of Object.entries(t))s[n]||(s[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(s[n],r)}catch{}return s}var ma={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}},Mr=4;function Rr(s,e=ma){let t=ha(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Mr;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Mr,d=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+d.length>o){let c=o-r;c>100&&n.push(d.slice(0,c)+"...");break}n.push(d),r+=d.length}return n.join(`
|
|
50
50
|
|
|
51
|
-
`)}function
|
|
51
|
+
`)}function ha(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(fa(s,t("channel",200))),n.push(ya(s,t("scope",200))),s.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:s.landscape,tags:["landscape","world-model"]}),s.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:s.systemPrompt.split(`
|
|
52
52
|
`)[0],tags:["identity",s.agentId]}),s.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:s.bootstrapContext,tags:["bootstrap","identity","personality"]}),s.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:s.references,tags:["references","verified","deterministic"]}),s.intent&&s.intent.path.length>0){let i=[`[Intent path: ${s.intent.pathLabel}${s.intent.status==="pending"?" (pending approval)":""}]`],a=s.intent.path[s.intent.path.length-1],d=s.intent.axes?.[a];if(d&&Object.keys(d).length){let c=Object.entries(d).map(([l,u])=>` ${l}: ${u}`).join(`
|
|
53
53
|
`);i.push(c)}s.intent.leaf?.input&&i.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
54
|
-
`),tags:["intent",...s.intent.path]})}else{let i=
|
|
54
|
+
`),tags:["intent",...s.intent.path]})}else{let i=ba(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
55
55
|
`),tags:["artifacts",...s.mediaType?["media"]:[]]}),s.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:s.skillInjection,tags:["skills","auto-inject"]}),s.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:s.patternContext,tags:["patterns","behavioral","self-improving"]}),s.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:s.procedureContext,tags:["procedures","sop"]}),s.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:s.memoryContext,tags:["memory","persistent"]});let o=s.groupHistory||s.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),s.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:s.crossChatContext,tags:["history","cross-chat"]}),s.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:s.longMemoryRecall,tags:["history","long-memory"]}),s.handoverNote){let i=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&i.push(`Operator summary: ${s.handoverNote.summary}`),i.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
56
56
|
`),tags:["handover",s.handoverNote.fromAgent]})}return s.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${s.rotationMemo.reason}, ${s.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner:]`,s.rotationMemo.memo].join(`
|
|
57
|
-
`),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function
|
|
58
|
-
`),tags:r,rules:n}}function
|
|
59
|
-
`),tags:n}}function
|
|
60
|
-
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(d=>d.queuedAt??d.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as
|
|
57
|
+
`),tags:["continuity","rotation-memo"]}),s.eventDigest&&n.push({name:"events",priority:7.7,maxTokens:t("events",500),content:s.eventDigest,tags:["events","subscriptions"]}),s.attachHint&&n.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:s.attachHint,tags:["channel","attachments"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function fa(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
58
|
+
`),tags:r,rules:n}}function ya(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:n}}function ba(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var wa="resumeDelivery";function ou(s){if(!s||s.kind!=="direct"||!s.context||s.context[wa]||String(s.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let n=String(s.context.sender??"").match(/^agent:([^\s]+)$/);return n?n[1]:null}var xa=32e3;function Pr(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=xa?e:null}catch{return null}}function iu(s){if(!s)return null;try{let e=JSON.parse(s);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}function _r(s){return new Date(s).toISOString().slice(11,16)}function Er(s,e=Date.now()){return!Number.isFinite(s)||e-s<=6e4?null:`[queued at ${_r(s)} UTC, running at ${_r(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var xt=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(d=>`[${d.sender}, ${new Date(d.timestamp).toISOString().slice(11,16)}]: ${d.text}`).join(`
|
|
60
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(d=>d.queuedAt??d.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Ta,writeFileSync as Dr,appendFileSync as ka,mkdirSync as Ia,existsSync as Or}from"fs";import{resolve as nn}from"path";var Nr=50,Sa="claude-haiku-4-5-20251001",va=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
61
61
|
|
|
62
62
|
Extract patterns like:
|
|
63
63
|
- "When asked about X, the approach that works is Y"
|
|
@@ -73,20 +73,20 @@ SKIP:
|
|
|
73
73
|
Output a JSON array:
|
|
74
74
|
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
75
75
|
|
|
76
|
-
If nothing worth extracting, output: []`,Tt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=nn(e,".agentx/patterns"),Or(this.patternsDir)||
|
|
77
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};
|
|
76
|
+
If nothing worth extracting, output: []`,Tt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=nn(e,".agentx/patterns"),Or(this.patternsDir)||Ia(this.patternsDir,{recursive:!0})}filePath(e){return nn(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Or(t))return[];try{return Ta(t,"utf-8").split(`
|
|
77
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};ka(this.filePath(e),JSON.stringify(n)+`
|
|
78
78
|
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=nn(this.patternsDir,`${t}_bm25_cache.json`),a=Wn(o,i),c=Bn(e,a).slice(0,n).map(l=>r[l.docIndex]).filter(l=>l.confidence>=.3);return c.length>0&&this.recordAccess(t,c.map(l=>l.id)),c}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
79
79
|
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(d=>i.includes(d)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Dr(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
80
80
|
`)+`
|
|
81
81
|
`)}prune(e){let t=this.getAll(e);t.length<=Nr||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,Nr),Dr(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
82
82
|
`)+`
|
|
83
|
-
`))}};async function Lr(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-ES5KVLI4.js"),d=(await o("claude").generate([{role:"system",content:
|
|
83
|
+
`))}};async function Lr(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-ES5KVLI4.js"),d=(await o("claude").generate([{role:"system",content:va},{role:"user",content:`User: ${e.slice(0,500)}
|
|
84
84
|
|
|
85
|
-
Agent: ${t.slice(0,1e3)}`}],{model:
|
|
86
|
-
\u2026[truncated ${s.length-e} chars]`}ai();import{z as
|
|
87
|
-
`);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function
|
|
85
|
+
Agent: ${t.slice(0,1e3)}`}],{model:Sa,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!d)return;let c=JSON.parse(d[0]);if(!(!Array.isArray(c)||c.length===0)){for(let l of c)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as Ca}from"events";var Aa=2e4,rn=class{inner=new Ca;envelopeListeners=new Set;ring=new Cs;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let n=this.inner.emit(e,t);try{this.publish($a(e,t))}catch{}return n}publish(e){let t=vs(),n=e.id??Ss(),r={id:n,rootId:e.rootId??t?.rootId??n,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Bt(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>Aa&&this.seen.delete(this.seen.keys().next().value);let n={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Bt(e.summary??"")};e.parentId&&(n.parentId=e.parentId),e.agentId&&(n.agentId=e.agentId),e.ref&&(n.ref=e.ref),this.ring.push(n);for(let r of this.envelopeListeners)try{r(n)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function $a(s,e){let t=e,n={type:s,at:t.at,agentId:t.agentId,ref:t.taskId};switch(s){case"message:matched":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:queued":return{...n,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...n,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...n,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...n,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...n,kind:"agent",summary:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...n,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...n,kind:"agent",summary:String(s)}}}var sn;function X(){return sn||(sn=new rn),sn}Dt();Dt();var Fr=["manual","notify","auto"];function Ma(s){return typeof s=="string"&&Fr.includes(s)}var on={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Ra=7*24*60*6e4,Ge=class{constructor(e={},t){this.store=t;this.opts={...on,...e};let n={};try{n=t?.load()??{}}catch{n={}}let r=Date.now()-Ra;for(let[o,i]of Object.entries(n))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,n),i}touch(e,t=Date.now()){let n=this.sessions.get(e);return n?(n.lastSeenAt=t,n):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r.watch=void 0,this.remember(r),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],t||(n.watch=void 0),this.remember(n),n}watch(e,t,n=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,n,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:n},this.remember(r,n),r}advanceWatch(e,t){let n=this.sessions.get(e);n?.watch&&(n.watch.cursor.id===t.id&&n.watch.cursor.at===t.at||(n.watch.cursor=t,this.remember(n)))}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,this.remember(n),n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),n={}){this.sessions.delete(e),n.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,n){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,n)}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:we(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:Pa(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let n={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(n.watch={...e.watch}),this.saved.set(e.sessionId,n)}for(let[n,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(n);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Pa(s,e){return s.length<=e?s:`${s.slice(0,e)}
|
|
86
|
+
\u2026[truncated ${s.length-e} chars]`}ai();import{z as _a}from"zod";var jr=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Ea(s){if(s==null)return{ok:!0,subscriptions:jr};let e=_a.array(Zn).min(1).safeParse(s);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var Da=15,Oa=1500,Hr=200;function Ur(s,e=Date.now()){let t=s[s.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Na(s,e){if(e.id){let n=s.findIndex(r=>r.id===e.id);if(n>=0)return s.slice(n+1)}let t=Date.parse(e.at);return Number.isNaN(t)?s:e.id?s.filter(n=>Date.parse(n.at)>t):s.filter(n=>Date.parse(n.at)>=t)}function Iu(s,e,t={}){let n=Na(e,s.cursor),r=n.length?Ur(n):s.cursor,o=n.filter(c=>s.subscriptions.some(l=>As(l,c)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=s.cursor.id??s.cursor.at,{text:a,shown:d}=La(o,i,t);return{text:a,cursor:r,matched:o.length,shown:d}}function La(s,e,t={}){let n=Math.max(3,t.maxLines??Da),r=Math.max(200,t.maxChars??Oa),o=s.map(a=>Fa(`- ${Ms(a)}`)),i=o.length;for(let a=Math.min(i,n-1);a>=0;a--){let d=i-a,l=[d?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];d&&l.push(`+${d} more \u2014 \`agentx events --since ${e}\``);let u=l.join(`
|
|
87
|
+
`);if(l.length<=n&&u.length<=r)return{text:u,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Fa(s){return s.length<=Hr?s:`${s.slice(0,Hr-1)}\u2026`}import{existsSync as Ha,mkdirSync as ja,readFileSync as Ua,renameSync as Ba,writeFileSync as Wa}from"node:fs";import{homedir as qa}from"node:os";import{dirname as Ka,join as Ga}from"node:path";function Ja(s){return{load:()=>Ha(s)?JSON.parse(Ua(s,"utf-8")):{},save:e=>{ja(Ka(s),{recursive:!0});let t=`${s}.tmp`;Wa(t,JSON.stringify(e,null,2),{mode:384}),Ba(t,s)}}}function Qa(){if(!process.env.VITEST)return Ja(process.env.AGENTX_ATTACH_BINDINGS_FILE??Ga(qa(),".agentx","attach-bindings.json"))}var an;function Br(){return an||(an=new Ge({},Qa())),an}Ot();import{readFileSync as za}from"fs";import{homedir as Xa}from"os";import{join as Ya}from"path";var Je=null,Va=6e4;function Za(){try{let s=Ya(Xa(),".claude.json"),e=za(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function ec(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function tc(s=!1){let e=Date.now();return!s&&Je&&e-Je.checkedAt<Va||(Je=ec(Za(),e)),Je}function Wr(s){let e=tc();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var Kr={warnRatio:.8},$e={...Kr},nc=5*60*60*1e3,sc=60*60*1e3,he=[];function Gr(s){$e={...Kr,...s||{}}}function Jr(s){let e=s-nc,t=0;for(;t<he.length&&he[t]<e;)t++;t>0&&he.splice(0,t)}function Qr(s=Date.now()){Jr(s),he.push(s)}var Me=new Map,rc=15*60*1e3;function zr(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function oc(s){let e=zr(s);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function ic(s,e=Date.now()){if(!s||typeof s!="object")return null;let t=s;if(t.type!=="rate_limit_event")return null;let n=t.rate_limit_info??t.rateLimitInfo;if(!n||typeof n!="object")return null;let r=n.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(n.rateLimitType??n.rate_limit_type??"unknown"),i=oc(n.resetsAt??n.resets_at),a=zr(n.utilization),d=n.overageStatus??n.overage_status,c=r==="rejected"&&((n.isUsingOverage??n.is_using_overage)===!0||d==="allowed"||d==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...c&&{usingOverage:c},seenAt:e}}function Xr(s){return/_(opus|sonnet|haiku)$/.exec(s)?.[1]??null}function Yr(s,e){let t=Xr(s);return!t||!e||e.toLowerCase().includes(t)}function cn(s,e=Date.now(),t){let n=ic(s,e);if(!n)return null;if(n.status!=="rejected")for(let[r,o]of Me)o.status!=="rejected"||r===n.window||(!Xr(r)||t&&Yr(r,t))&&Me.delete(r);return Me.set(n.window,n),n}function Vr(s=Date.now()){return[...Me.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:(e.resetsAt??e.seenAt+rc)>s)}function ac(s=Date.now(),e){return Vr(s).find(t=>Yr(t.window,e))??null}function Lu(s=Date.now()){let e=Vr(s);for(let t of e)Me.delete(t.window);return e}function cc(){return[...Me.values()].sort((s,e)=>e.seenAt-s.seenAt)}function qr(s){return typeof s=="number"&&s>0}function Zr(s=Date.now()){Jr(s);let e=s-sc,t=0;for(let o=he.length-1;o>=0&&he[o]>=e;o--)t++;let n=he.length,r={lastHour:t,last5h:n,maxPerHour:qr($e.maxPerHour)?$e.maxPerHour:void 0,maxPer5h:qr($e.maxPer5h)?$e.maxPer5h:void 0,provider:cc()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=n/r.maxPer5h),r}function eo(s){return s.replace(/_/g," ")}function to(s,e){return s?`in about ${Math.max(1,Math.round((s-e)/6e4))} min (${new Date(s).toISOString()})`:"shortly"}function no(s,e=Date.now(),t){let n=Zr(e);if(s)return null;let r=ac(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${eo(r.window)} window as rejected. Cold dispatches are held until it resets ${to(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:n}:n.maxPerHour&&n.lastHour>=n.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${n.lastHour}/${n.maxPerHour} claude-code runs in the last hour. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPerHour in agentx.json (applies on save).`,usage:n}:n.maxPer5h&&n.last5h>=n.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${n.last5h}/${n.maxPer5h} claude-code runs in the last 5h. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPer5h in agentx.json (applies on save).`,usage:n}:null}function so(s=Date.now()){let e=Zr(s),t=e.provider.find(r=>r.status==="allowed_warning");if(t){let r=t.utilization!==void 0?` (${Math.round(t.utilization*100)}% used)`:"";return`claude plan ${eo(t.window)} window nearing its limit${r}, resets ${to(t.resetsAt,s)}`}let n=$e.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=n&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of local cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=n&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}var dn=new Map;function ro(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function oo(s,e,t,n=Date.now()){let r=dn.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},dn.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function io(s){let e=dn.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as te,mkdirSync as Fc,readdirSync as ie,readFileSync as Xe,rmSync as Hc,writeFileSync as jc}from"fs";import{resolve as G}from"path";import{existsSync as ye,mkdirSync as un,readFileSync as dc,readdirSync as uc,renameSync as lc,unlinkSync as gc,writeFileSync as kt}from"fs";import{resolve as ge,relative as It}from"path";import{z as J}from"zod";var fe=J.object({id:J.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:J.string().min(1),trigger:J.string().min(1,"procedures must describe when they apply"),inputs:J.array(J.string()).default([]),expected:J.string().optional(),kpis:J.array(J.string()).default([]),owner:J.string().optional(),tags:J.array(J.string()).default([]),status:J.enum(["draft","active","deprecated"]).default("active"),source:J.string().optional(),evidence:J.array(J.string()).default([]),created:J.string().optional(),updated:J.string().optional(),related:J.array(J.string()).default([])});function pc(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
|
|
88
88
|
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function St(s){let e=["---"];return e.push(`id: ${s.id}`),e.push(`title: "${s.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${s.trigger.replace(/"/g,'\\"')}"`),s.inputs?.length&&e.push(`inputs: ${JSON.stringify(s.inputs)}`),s.expected&&e.push(`expected: "${s.expected.replace(/"/g,'\\"')}"`),s.kpis?.length&&e.push(`kpis: ${JSON.stringify(s.kpis)}`),s.owner&&e.push(`owner: ${s.owner}`),s.tags?.length&&e.push(`tags: ${JSON.stringify(s.tags)}`),e.push(`status: ${s.status}`),s.source&&e.push(`source: "${s.source.replace(/"/g,'\\"')}"`),s.evidence?.length&&e.push(`evidence: ${JSON.stringify(s.evidence)}`),s.related?.length&&e.push(`related: ${JSON.stringify(s.related)}`),s.created&&e.push(`created: ${s.created}`),s.updated&&e.push(`updated: ${s.updated}`),e.push("---"),e.join(`
|
|
89
|
-
`)}var Qe=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ge(process.cwd(),".agentx/procedures"),un(this.baseDir,{recursive:!0})}pathFor(e){return ge(this.baseDir,`${e}.md`)}get draftsDir(){return ge(this.baseDir,"_drafts")}draftPathFor(e){return ge(this.draftsDir,`${e}.md`)}parseFile(e){let t=
|
|
89
|
+
`)}var Qe=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ge(process.cwd(),".agentx/procedures"),un(this.baseDir,{recursive:!0})}pathFor(e){return ge(this.baseDir,`${e}.md`)}get draftsDir(){return ge(this.baseDir,"_drafts")}draftPathFor(e){return ge(this.draftsDir,`${e}.md`)}parseFile(e){let t=dc(e,"utf-8"),{meta:n,body:r}=pc(t),o=fe.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:It(this.baseDir,e)}:null}listDir(e){if(!ye(e))return[];let t=[];for(let n of uc(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(ge(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return ye(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return ye(t)?this.parseFile(t):null}add(e,t){let n=fe.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(ye(r))throw new Error(`Procedure already exists: ${n.id}`);return kt(r,St(n)+`
|
|
90
90
|
|
|
91
91
|
`+t.trim()+`
|
|
92
92
|
`),{meta:n,body:t.trim(),path:It(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=fe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return kt(this.pathFor(e),St(o)+`
|
|
@@ -98,15 +98,15 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ia,maxTokens:512})).content.trim().match(/\[[
|
|
|
98
98
|
`),{meta:n,body:t.trim(),path:It(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=fe.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return kt(this.pathFor(e),St(n)+`
|
|
99
99
|
|
|
100
100
|
`+t.body+`
|
|
101
|
-
`),
|
|
102
|
-
`)}function
|
|
101
|
+
`),gc(this.draftPathFor(e)),{meta:n,body:t.body,path:It(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!ye(t))throw new Error(`Draft not found: ${e}`);let n=ge(this.draftsDir,"_rejected");un(n,{recursive:!0}),lc(t,ge(n,`${e}.md`))}isRejected(e){return ye(ge(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as mc,mkdirSync as hc,readFileSync as fc,writeFileSync as yc}from"fs";import{dirname as bc,resolve as wc}from"path";import{z as Z}from"zod";var xc=Z.object({key:Z.string(),count:Z.number().int().min(0).default(0),firstSeen:Z.string(),lastSeen:Z.string(),taskIds:Z.array(Z.string()).default([]),sampleMessage:Z.string().default(""),status:Z.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:Z.string().optional()}),Tc=Z.object({minedThrough:Z.string().optional(),candidates:Z.array(xc).default([])});function ao(s){return wc(s,"_candidates.json")}function kc(s){let e=ao(s);if(!mc(e))return{candidates:[]};try{let t=Tc.safeParse(JSON.parse(fc(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Ic(s,e){let t=ao(s);hc(bc(t),{recursive:!0}),yc(t,JSON.stringify(e,null,2)+`
|
|
102
|
+
`)}function Sc(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function vc(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Cc(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function ln(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function co(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function gn(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=ln(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let d=[],c=co(o,ln(a.meta.trigger));c>0&&d.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),u=co(o,ln(l));u>0&&d.push("title/tags");let p=Math.min(1,c*.7+u*.5);p>=r&&i.push({procedure:a,score:p,reasons:d})}return i.sort((a,d)=>d.score-a.score).slice(0,n)}function pn(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
|
|
103
103
|
`)})].join(`
|
|
104
104
|
|
|
105
|
-
`)}ns();Ht();var hn="turn-progress",uo={progress:it({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.")},mn=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function lo(s){return{agent:s.agent,request:mn(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:mn(e.input,300),...e.result!==void 0?{result:mn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Ht();var go="turn-handoff",po="approval-binding",mo={nextStep:it({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.")},ho={approves:Ne("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."})},
|
|
106
|
-
`).slice(-3).join(" ")):!1}var
|
|
105
|
+
`)}ns();Ht();var hn="turn-progress",uo={progress:it({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.")},mn=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function lo(s){return{agent:s.agent,request:mn(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:mn(e.input,300),...e.result!==void 0?{result:mn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}Ht();var go="turn-handoff",po="approval-binding",mo={nextStep:it({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.")},ho={approves:Ne("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."})},Ac=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,fo=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,$c=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function fn(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:$c.test(e.split(`
|
|
106
|
+
`).slice(-3).join(" ")):!1}var Mc=/^\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 yo(s){return s.trim().length<=160&&Mc.test(s)}function bo(s){return s.trim().length<=160}function wo(s){return{agent:s.agent,channel:s.channel,request:Ac(s.request,1500),agentReplyEnding:fo(s.reply,1200)}}function xo(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:fo(s.previousReply,1200)}}var Rc=5*6e4,Pc=3,_c=12,Ec=24*60*6e4,To=new Set(["cron","heartbeat","bench","a2a","business"]),Dc={observe(){},stop(){}};function ko(s){if(ts(hn)==="off")return Dc;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let p;for(let[f,m]of o)m>1&&(!p||m>p.times)&&(p={call:f,times:m});return p},l=p=>{if(d)return;d=!0,a=n.length;let f=lo({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-_c),repeated:c(),trigger:p});xe(hn,f,uo,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{d=!1})},u=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Rc);return u.unref?.(),{observe(p){let f=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let m of f){if(m?.type!=="tool_use")continue;let T=m.input?JSON.stringify(m.input):"",y={tool:m.name||"tool",input:T};n.push(y),typeof m.id=="string"&&r.set(m.id,y);let b=`${y.tool}(${T})`,I=(o.get(b)??0)+1;o.set(b,I),I>=Pc&&!i.has(b)&&(i.add(b),l("repetition"))}else if(p?.type==="user")for(let m of f){if(m?.type!=="tool_result")continue;let T=r.get(m.tool_use_id);T&&(T.result=Array.isArray(m.content)?m.content.map(y=>typeof y?.text=="string"?y.text:"").join(""):typeof m.content=="string"?m.content:"",m.is_error&&(T.error=!0))}},stop(){clearInterval(u)}}}var yn=new Map,Io=(s,e,t)=>`${s}\0${e}\0${t}`;function So(s){if(To.has(s.channel)||!fn(s.reply))return;let e=Io(s.agent,s.channel,s.chatId);xe(go,wo(s),mo,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&yn.set(e,{callId:t.callId,at:Date.now()})})}function vo(s){if(To.has(s.channel))return;let e=Io(s.agent,s.channel,s.chatId),t=yn.get(e);if(t){yn.delete(e);let n=es().store;if(n&&Date.now()-t.at<Ec)try{n.label(t.callId,"userReply",yo(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!bo(s.message)||!fn(s.previousReply)||xe(po,xo({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),ho,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}si();oi();ii();Vn();function Co(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(ze(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(d=>{a(),n(d)},d=>{a(),r(d)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function ze(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Re=class extends Error{constructor(t,n){super(`step "${t}" exceeded its ${Math.round(n/1e3)}s budget`);this.step=t;this.budgetMs=n;this.name="StepBudgetExceeded"}};function Ao(s,e,t){return e>0?new Promise((n,r)=>{let o=setTimeout(()=>r(new Re(t,e)),e);o.unref?.(),s.then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),r(i)})}):s}var Nc=250,Lc=5e3,Uc={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3};function $o(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Do;function dg(s){Do=s}function ug(){return Do}var Mo=64*1024,Bc=5*60*1e3,Wc=3e4,qc=300,Pe=".agentx/task-history",Kc=30;function Ye(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Gc(s,e){let t={};return s?.path?.length&&(t.intentPath=s.path,t.intentPathLabel=s.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Jc(s,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:n}=$s(s,e,X().recent());return Rs(t,n)}function Qc(s,e,t={}){let n;try{n=s.listArticles(e)}catch{return""}if(n.length===0)return"";let r=new Map;for(let l of n){let u=l.meta.type||"untyped",p=r.get(u)||[];p.push(l.meta.title),r.set(u,p)}let o=t.maxArticles??400,i=n.length<=o,a=Array.from(r.entries()).sort().map(([l,u])=>i?`**${l}** (${u.length}) \u2014 ${u.sort().join(" \xB7 ")}`:`**${l}** \u2014 ${u.length} article${u.length===1?"":"s"}`).join(`
|
|
107
107
|
`),d=process.argv[1]||"dist/cli.js",c=s.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
108
108
|
node ${d} wiki query "the question" --dir ${c} --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.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${d} wiki facts list --dir ${c}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,"[End Institutional Wiki]"].join(`
|
|
109
|
-
`)}var bn=8*1024;function
|
|
109
|
+
`)}var bn=8*1024;function zc(s,e){if(s)try{Ns(s)}catch{}return e}function Ro(s){if(s.length<=bn)return s;let e=s.length-bn;return s.slice(0,bn)+`\u2026[+${e}]`}function Po(s,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let r=typeof n.name=="string"?n.name:"";r&&s.set(r,(s.get(r)??0)+1)}}function Xc(s,e){if(!s||s.length===0)return null;for(let t of s)if((e.get(t)??0)===0)return t;return null}function _o(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=X();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Ro(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Ro(a):null,at:r})}return}}function Yc(){let s="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
110
110
|
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
111
111
|
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
112
112
|
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
@@ -128,25 +128,25 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ia,maxTokens:512})).content.trim().match(/\[[
|
|
|
128
128
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Ye(i,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
130
|
`:""}}var Eo=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new ws;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new ys;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new bt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new hs(void 0,void 0,"unified"),this.memoryStore=new bs,this.patternStore=new Tt,this.rateLimiter=new wt,this.tokenTracker=new Ae,this.messageQueue=new xt,Gr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ps({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new ms({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let n=Xn(this.config.people,e,t);return n?(this.log(`[${e}] refused: ${n.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:n.person.id,event:"agent-refused",detail:e}),n.note):null}logToolRefusal(e,t,n){this.log(`[${t??"?"}] blocked for ${e}: ${n} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:n})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Ds(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let d of a.def.mentions){if(t.atMentionsOnly&&!d.startsWith("@"))continue;let c=d.toLowerCase();n.includes(c)&&c.length>o&&(r=i,o=c.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,d=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=kr(p.messages,e.message??""),d=Ir(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let c={message:e.message??"",previousMessage:i,recentRequests:d,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await xe(Ls,Hs(c),Fs,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n},timeoutMs:1500});return!l||l.mode!=="active"||!js(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),X().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),d=await a(t,n);if(!d.memo){this.log(`[${e}] rotation memo skipped (${i}, ${d.reason}, ${d.durationMs}ms)`);return}let{storeRotationMemo:c}=await import("./rotation-memo-store-A4YW6FSK.js"),l=c(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:d.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${d.durationMs}ms, ${d.memo.length} chars, ${l.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
131
|
-
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().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(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(
|
|
132
|
-
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let
|
|
131
|
+
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().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(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:g.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=yt(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),h=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(l==="voice"){let g=Date.now(),h=25*6e4,S=`${e.agentId}\0${u}`;for(;this.messageQueue.isBusy(e.agentId,l,u)||this.voiceClaims.has(S);){if(Date.now()-g>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,500))}p=S,this.voiceClaims.add(S)}else{let g=c.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,l,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:l,chatId:u,originalContext:e.context,queuedAt:e.queuedAt});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let S=this.messageQueue.pendingCount(e.agentId,l,u);return X().emit("task:queued",{agentId:e.agentId,channel:l,chatId:u,at:new Date().toISOString(),sender:Ft(e.context),humanRoot:Nt(e.context)}),this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${S}) behind=${c.runningTasks.map(P=>P.id).join(",")||"-"} chat=${l}:${u} at=${new Date().toISOString()}`),{content:"",error:xs(h,S)}}}let f=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,h)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!f.ok)return this.log(`[${e.agentId}] ${f.reason}`),{content:"",error:f.reason};if(e.queuedAt!==void 0){let g=Er(e.queuedAt);g&&(e.message=`${g}
|
|
132
|
+
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let m={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};c.runningTasks.push(m),e.runningTaskId=m.id;let T=zn(this.config.people,e.context);if(e.context&&(T?e.context.person=T.id:delete e.context.person),this.runningContexts.set(m.id,e.context??{}),e.onStart)try{e.onStart(m.id)}catch{}let y=new AbortController;this.taskAborts.set(m.id,{agentId:e.agentId,channel:m.channel,chatId:typeof m.chatId=="string"?m.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(m.id,b);let I=g=>{if(g){b.buffer+=g,b.buffer.length>Mo&&(b.buffer=b.buffer.slice(b.buffer.length-Mo));for(let h of b.subscribers)try{h(g)}catch{}}},E=we();e.taskId=E;let _=new Map,C=(g,h,S)=>{try{X().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-h,at:new Date().toISOString()})}catch{}},O=0,F=!1,D=()=>{F||(F=!0,O&&C("first-event",O,"ok"))},L;if(t){let g=Yc();L=h=>{D();let S=g(h);if(S&&I(S),_o(E,e.agentId,h),Po(_,h),cn(h,void 0,e.model||c.def.model),r)try{r(h)}catch{}}}else L=g=>{if(D(),_o(E,e.agentId,g),Po(_,g),cn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,j=H?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;j?.unref?.();let K=(c.def.preSpawnTimeoutSec??qc)*1e3,A=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(K/1e3)}s in step "${m.step??"start"}"`))},K);A.unref?.();let v=()=>{A&&clearTimeout(A),A=void 0},w=()=>`task=${m.id} chat=${l}:${u} at=${new Date().toISOString()}`,x;y.signal.addEventListener("abort",()=>{let g=ze(y.signal).message;/^timed out/.test(g)&&(x=m.step??"start"),this.log(`[${e.agentId}] task ${m.id} aborted in step "${m.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let N=g=>{m.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},M=(g,h,S=0)=>{if(y.signal.aborted)return Promise.reject(ze(y.signal));N(g),(g==="agent"||g==="workflow-auto-run")&&(v(),O=Date.now());let P=Date.now(),W=Ao(h(),Uc[g]??0,g);return Co(W,y.signal,S).then(B=>(C(g,P,"ok"),B),B=>{throw C(g,P,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},V=async(g,h,S,P=0)=>{try{return await M(g,h,P)}catch(W){if(W instanceof Re)return S();throw W}},wn=!1,xn=g=>{if(wn)return;wn=!0,this.runReleases.delete(m.id),j&&clearTimeout(j),v(),c.activeTasks--;let h=c.runningTasks.findIndex(S=>S.id===m.id);h!==-1&&c.runningTasks.splice(h,1),this.runningContexts.delete(m.id),this.taskAborts.delete(m.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(
|
|
135
|
-
`).length}L`,B=`[${e.agentId}] ${
|
|
136
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&
|
|
137
|
-
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.`:"",Yo=
|
|
138
|
-
${
|
|
134
|
+
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(m.id),Bc).unref?.();try{let S=b.endedAt,P={id:m.id,agentId:e.agentId,channel:m.channel,chatId:m.chatId,sender:m.sender,message:e.message||"",startedAt:m.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-m.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${m.id} chat=${l}:${u} at=${new Date().toISOString()}`);let P=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:P,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then($=>(Fe($.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(m.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let k=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-3LA5RAKG.js"),pe=await V("request-gate",()=>Oo(e.message,e.agentId,k),()=>({active:!1,preprocess:!1}));pe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let R=u,vt=e.context?.sender||"User",ne=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,k,R),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${k}:${R}`),X().emit("session:rotated",{agentId:e.agentId,channel:k,chatId:R,reason:"stale",at:new Date().toISOString()})),e.freshSession||await V("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,k,R,e.seedHistory),()=>{});let Lo=[...this.sessions.getSession(e.agentId,k,R).messages].reverse().find(g=>g.role==="agent")?.content;vo({agent:e.agentId,channel:k,chatId:R,message:e.message,previousReply:Lo,taskId:E}),this.sessions.addUserMessage(e.agentId,k,R,vt,e.message);let Tn=Date.now();X().emit("task:started",{agentId:e.agentId,channel:k,chatId:R,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Tn).toISOString(),taskId:E,resumeOrigin:Pr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Ft(e.context),...T?{person:T}:{},humanRoot:Nt(e.context),pickup:Jn(e.context),operator:Qn(e.context)});let Y,Ct,kn=this.classifier;if(kn&&k!=="a2a"&&!ne){N("classify");let g=Date.now();Ct=kn.classify({text:e.message,channel:k,sender:e.context?.sender,chatId:R,agentId:e.agentId}).then(h=>{Y=h||void 0,Y?.path?.length&&(m.intentPath=Y.path.slice()),C("classify",g,"ok")},h=>{this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`),C("classify",g,"error")})}let In=async g=>{if(!Ct)return;let h;await Promise.race([Ct,new Promise(S=>{h=setTimeout(S,g),h.unref?.()})]),h&&clearTimeout(h)};await In(Nc);let _e=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let g=new _s({baseDir:G(process.cwd(),this.config.workflows.dir)}),h=Es({agentId:e.agentId,channel:k,message:e.message,intentPath:Y?.path},g.list());h&&h.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${_e.mode} reasons=${h.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&h.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Fo=this.wikiHub.getAgentWiki(e.agentId),Sn=this.memoryStore.findRelevant(e.message,e.agentId,ne?3:8),vn=this.memoryStore.buildContext(Sn),Cn=this.memoryStore.contextFacts(Sn),Ho=this.patternStore.findRelevant(e.message,e.agentId,5),jo=this.patternStore.buildContext(Ho),An="";if(!ne)try{let{loadLocalSkills:g,getAutoInjectSkills:h}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),P=e.personLimits?.skills??[],W=P.length?S.filter(B=>!P.some(ee=>Oe(ee,B.frontmatter.name))):S;An=h(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,k,R):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,k,R):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,k,R):void 0;if(U&&this.sessions.isSessionStale(e.agentId,k,R)&&(this.log(`[${e.agentId}] session stale for ${k}:${R}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,k,R,"stale"),this.sessions.clearClaudeSessionId(e.agentId,k,R),X().emit("session:rotated",{agentId:e.agentId,channel:k,chatId:R,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,k,R)){let g=this.sessions.getLastTurnContextTokens(e.agentId,k,R);this.log(`[${e.agentId}] tier-2 rotation for ${k}:${R} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,k,R,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,k,R),X().emit("session:rotated",{agentId:e.agentId,channel:k,chatId:R,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,k,R)){let g=this.sessions.getTurnCount(e.agentId,k,R);this.log(`[${e.agentId}] max-turns rotation for ${k}:${R} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,k,R,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,k,R),X().emit("session:rotated",{agentId:e.agentId,channel:k,chatId:R,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await V("rotate",()=>this.maybeRotateForContinuity(e,c,k,R,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,k,R,this.memoryStore));if(g.compacted){let h=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${k}:${R} (quality: ${h}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let P=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Uo=process.env.AGENTX_CONTEXT_SURGERY==="1",Bo=ne?{maxMessages:8,maxChars:2400}:Uo&&$o(k,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Wo=!U&&!ne?Qc(Fo,e.agentId):void 0,Ve=U?void 0:this.sessions.buildHistoryContext(e.agentId,k,R,Bo),qo=U?void 0:this.sessions.getRotationMemo(e.agentId,k,R)??void 0,$n,Mn=[];if(this.config.procedures?.injection?.enabled&&!U&&!ne)try{let g=new Qe({baseDir:G(process.cwd(),this.config.procedures.dir)}),h=gn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){$n=pn(h),Mn=h.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of h)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(me&&me.cat)try{let h=this.sessions.getSession(e.agentId,k,R).messages,S=h[0],P=h[h.length-1],W=Ve===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ve.length}c/${Ve.split(`
|
|
135
|
+
`).length}L`,B=`[${e.agentId}] ${k}:${R} ${W} | session.messages=${h.length}`+(h.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",B)}catch(g){me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Rn;if(c.def.contextReferences&&!U)try{let g=c.def.workspace,h=this.referencesCache.get(g);if(!h){let[P,W]=await M("references",()=>Promise.all([jt(c.def.workspace),Ut(c.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[B,ee]=await M("references",()=>Promise.all([jt(process.cwd()),Ut(process.cwd())]));h={refs:B,recipes:ee}}else h={refs:P,recipes:W};this.referencesCache.set(g,h)}let S=Is({agentId:e.agentId,intentTags:Y?.path,message:e.message},h.recipes,h.refs);S.cards.length>0&&(Rn=Ts(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Pn=this.sessions.getCrossSessionSummary(e.agentId,k,R,e.message),_n,Ze=Tr(e.message);if(Ze)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:k,chatId:R,lookbackDays:Ze.lookbackDays,limit:12});if(g.turns.length>0){let h=[`[Long-memory recall \u2014 last ${Ze.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,B=P.role==="user"?P.senderName||"User":P.senderName||"Agent";h.push(`${W} ${B}: ${P.content}`)}g.hasMore&&h.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),_n=h.join(`
|
|
136
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&k!=="voice"&&k!=="desktop"){try{let{planContext:g}=await import("./context-planner-JU7CNXCB.js"),h=await M("plan-context",()=>g({agentId:e.agentId,channel:k,chatId:R,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));h?(On=!0,En=h.sessionHistory,vn=h.memoryContext,Cn=h.memoryFacts,Pn=h.crossChatContext,Dn=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}On&&U&&(this.sessions.clearClaudeSessionId(e.agentId,k,R),U=void 0)}let At=`${e.agentId}:${k}:${R}`,et=cs(e.message);et&&(et==="default"?(this.activeSouls.delete(At),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(At,et),this.log(`[${e.agentId}] Soul switched to: ${et}`)));let Go=this.activeSouls.get(At),Jo=is(c.def.workspace,Go),Qo=as(Jo),zo=this.agentMemory.indexMarkdown(e.agentId),Xo=c.def.tier==="claude-code"||c.def.tier==="codex-cli"?`[Operating principle]
|
|
137
|
+
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.`:"",Yo=Vc(c.def.richMessages,k),Nn="";if(c.def.workspace){let g=G(c.def.workspace,"CLAUDE.md");if(te(g))try{let h=Xe(g,"utf-8");Nn=`[Project CLAUDE.md]
|
|
138
|
+
${h.length>4e3?h.slice(0,4e3)+`
|
|
139
139
|
|
|
140
|
-
[CLAUDE.md truncated to 4KB]`:
|
|
140
|
+
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let tt=e.context?.runbookPath,$t=[];if(tt&&te(tt)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,S=4e3,P=16e3;for(let W of g){if(h>=P)break;let B=G(tt,W);if(te(B))try{let ee=Xe(B,"utf-8"),$=ee.length>S?ee.slice(0,S)+`
|
|
141
141
|
|
|
142
142
|
[${W} truncated to ${S} bytes]`:ee;$t.push(`[Project Runbook \u2014 ${W} from ${tt}]
|
|
143
|
-
${$}`),
|
|
143
|
+
${$}`),h+=$.length}catch{}}}let Vo=$t.length>0?$t.join(`
|
|
144
144
|
|
|
145
145
|
`):"",Mt=[c.def.systemPrompt||"",Xo,Yo,Nn,Vo,Qo||"",zo||""].filter(g=>g.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,Rt={channel:
|
|
148
|
-
`),P=!1)},ee=
|
|
147
|
+
`)||void 0,Rt={channel:k,chatId:R,channelScope:e.context?.group?"group":k==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,k),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(k,c.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:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,k,R),rotationMemo:qo,eventDigest:U?void 0:Jc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(k,!U,c.def.richMessages);return g?zc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{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),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,k,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${k}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-HF4XVD4Y.js"),h=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:k,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,k,R),cheapModel:Hn}));h.downgraded&&(_t=h.model,this.log(`[${e.agentId}] ${h.reason}`))}catch{}let ei={...e,systemPromptAppend:Mt,..._t?{model:_t}:{}},se,jn=!1,Un=ko({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),ti=L;L=g=>{Un.observe(g),ti?.(g)};try{let g=this.workflowAutoRunner;if(be&&g){let q=be;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:k,chatId:R,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:k,chatId:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?ut():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:k,chatId:R}),ce=!!U||z,re=[Wr(ce),no(ce,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(re){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${re.reason}`);let De={content:"",error:re.message,duration:0};if(!t){b.buffer=`[error] ${re.message}`;for(let ni of b.subscribers)try{ni(b.buffer)}catch{}}return se=De,De}Qr();let Ee=so();Ee&&this.log(`[${e.agentId}] ${Ee}`)}let h=c.def.tier==="claude-code",S=h?t:(q,z)=>{q&&I(q),t&&t(q,z)},P=!1,W=h?n:q=>{q&&(P?I(q):(I(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},B=()=>{P&&(I(`
|
|
148
|
+
`),P=!1)},ee=h?S:S?(q,z)=>{B(),S(q,z)}:void 0,$=await M("agent",()=>br(c.def,ei,this.providers,ee,st,U,L,y.signal,W),Wc);if(!$.error){let q=Xc(c.def.toolUseRequired,_);if(q){let z=Array.from(_.entries()).map(([ce,ot])=>`${ce}=${ot}`).join(", ")||"none";$.error=`tool_required_not_called: ${q} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let Et=this.interruptedRuns.get(m.id);Et&&($.content="",$.error=Et,$.errorKind="interrupted"),se=$;let ae=$.usage?$r($.usage):void 0;if(jn=!0,X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:k,chatId:R,durationMs:Date.now()-Tn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:Et?!0:void 0,inputTokens:ae?.inputTokens,outputTokens:ae?.outputTokens,cacheReadTokens:ae?.cacheReadTokens,cacheCreateTokens:ae?.cacheCreateTokens,tier2InputTokens:ae?.tier2InputTokens,tier2OutputTokens:ae?.tier2OutputTokens,tier2CacheReadTokens:ae?.tier2CacheReadTokens,tier2CacheCreateTokens:ae?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:pe.arm,numTurns:$.numTurns,injectedContext:Zo,finalResponse:$.content||void 0,billedModel:$.billedModel||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let q=$.error?`[error] ${$.error}`:$.content;b.buffer=q;for(let z of b.subscribers)try{z(q)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,k,R,$.content),So({agent:e.agentId,channel:k,chatId:R,request:e.message,reply:$.content,taskId:E}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,k,R,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,k,R,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,k,R,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,k,R,$.usage,$.contextTokens),$.usage){let re=$.contextTokens,Ee=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(re??Ee)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${k}:${R}: context=${re??"n/a"} tokens (cumulative turn total=${Ee}) \u2014 next turn will rotate`)}if(ls({channel:k,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await In(Lc);try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:k,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
|
-
Agent: ${$.content}`,meta:
|
|
151
|
-
`)}export{Us as a,
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
Agent: ${$.content}`,meta:Gc(Y,e.context)})}catch{}gs(e.agentId,e.message,$.content,{channel:k,chatId:R,sender:vt},this.memoryStore).catch(()=>{}),Lr(e.agentId,e.message,$.content,{channel:k,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,ce=e.context?.channel,ot=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${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,z,ce,ot),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${w()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let h=ct(g.message);return se={content:"",error:dt(h),errorKind:h.kind},se}finally{if(Un.stop(),!jn)try{X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:l,chatId:u,durationMs:Date.now()-m.startedAt.getTime(),error:se?.error||(y.signal.aborted?ze(y.signal).message:"run ended before completion"),errorKind:se?.errorKind,interrupted:this.interruptedRuns.has(m.id)?!0:void 0,at:new Date().toISOString()})}catch{}xn(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);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=G(process.cwd(),Pe,this.safe(e.agentId),t);te(n)||Fc(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);jc(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=G(process.cwd(),Pe,this.safe(e));if(!te(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let d=new Date(n).toISOString().slice(0,10),c=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[c,d]){let p=G(a,u);if(te(p))try{for(let f of ie(p)){if(!f.endsWith(".json"))continue;let m=f.split("-")[0],T=parseInt(m,10);if(!Number.isFinite(T)||T<i||T>n)continue;let y=Math.floor((n-T)/36e5),b=t-1-y;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Pe);if(!te(e))return 0;let t=0;for(let n of ie(e)){let r=G(e,n),o;try{o=ie(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ie(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let l=JSON.parse(Xe(G(a,c),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Kc){let t=G(process.cwd(),Pe);if(!te(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ie(t)){let i=G(t,o),a;try{a=ie(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=n))try{Hc(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return[];let r=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(n,i),d;try{d=ie(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let l=JSON.parse(Xe(G(a,c),"utf-8")),{transcript:u,responseText:p,...f}=l;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return null;let r=this.safe(t),o=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(te(a))try{return JSON.parse(Xe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Ps();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||Fe(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>{let d=yt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}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}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,l=o.controller.signal.aborted,u=!1;l&&c&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,d,c)),this.messageQueue.enqueue(i,a,d,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:n}});let p=this.messageQueue.pendingCount(i,a,d),f=!1;if(r.replace){let m=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(m))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${m}`),f=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:f,edited:u,pending:p}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let l=!1,u=p=>{l||(l=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Fe(p.error)?u({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Vc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
|
+
`)}export{Us as a,id as b,Ws as c,bi as d,qs as e,lt as f,wd as g,Id as h,Sd as i,Md as j,yt as k,Hi as l,hr as m,qi as n,Ki as o,Gi as p,br as q,bt as r,wt as s,wa as t,ou as u,iu as v,rn as w,X as x,Fr as y,Ma as z,Ea as A,Ur as B,Iu as C,Br as D,Gr as E,Vr as F,Lu as G,Zr as H,Qe as I,kc as J,Ic as K,Sc as L,vc as M,Cc as N,gn as O,dg as P,ug as Q,Gc as R,Jc as S,Qc as T,bn as U,Ro as V,Po as W,Xc as X,_o as Y,Eo as Z,Vc as _};
|
|
152
|
+
//# sourceMappingURL=chunk-DEMIKEFB.js.map
|