agentix-cli 0.171.0 → 0.172.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +175 -73
  2. package/dist/{agent-2SQYGIUD.js → agent-4637FJMD.js} +2 -2
  3. package/dist/{board-dashboard-QFCOFP7F.js → board-dashboard-DJKRLABN.js} +565 -345
  4. package/dist/board-dashboard-DJKRLABN.js.map +1 -0
  5. package/dist/{chunk-BAAKV4HK.js → chunk-7FGJOVML.js} +3 -3
  6. package/dist/chunk-7FGJOVML.js.map +1 -0
  7. package/dist/{chunk-YE3MGLJF.js → chunk-7NA5VSQE.js} +311 -306
  8. package/dist/chunk-7NA5VSQE.js.map +1 -0
  9. package/dist/{chunk-74RXD676.js → chunk-I7EO2WXC.js} +2 -2
  10. package/dist/{chunk-FBNU7MMW.js → chunk-MH55YCUS.js} +80 -80
  11. package/dist/chunk-MH55YCUS.js.map +1 -0
  12. package/dist/{chunk-P3GQPEMU.js → chunk-PD5BZYBO.js} +8 -8
  13. package/dist/chunk-PD5BZYBO.js.map +1 -0
  14. package/dist/{chunk-LXRLD4VQ.js → chunk-SP7VFTXO.js} +2 -2
  15. package/dist/cli.js +1 -1
  16. package/dist/index.d.ts +9 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{program-O3BJYC47.js → program-XKQTHEQ3.js} +260 -259
  19. package/dist/program-XKQTHEQ3.js.map +1 -0
  20. package/dist/{registry-MXZBIPE5.js → registry-GROEORK6.js} +2 -2
  21. package/package.json +2 -2
  22. package/dist/board-dashboard-QFCOFP7F.js.map +0 -1
  23. package/dist/chunk-BAAKV4HK.js.map +0 -1
  24. package/dist/chunk-FBNU7MMW.js.map +0 -1
  25. package/dist/chunk-P3GQPEMU.js.map +0 -1
  26. package/dist/chunk-YE3MGLJF.js.map +0 -1
  27. package/dist/program-O3BJYC47.js.map +0 -1
  28. /package/dist/{agent-2SQYGIUD.js.map → agent-4637FJMD.js.map} +0 -0
  29. /package/dist/{chunk-74RXD676.js.map → chunk-I7EO2WXC.js.map} +0 -0
  30. /package/dist/{chunk-LXRLD4VQ.js.map → chunk-SP7VFTXO.js.map} +0 -0
  31. /package/dist/{registry-MXZBIPE5.js.map → registry-GROEORK6.js.map} +0 -0
@@ -1,65 +1,65 @@
1
- import{Aa as ro,Ca as oo,F as qr,M as Et,N as Gr,U as Dt,W as Kr,a as Cr,b as Mr,d as vn,f as Ye,ga as Jr,ha as zr,i as Hr,ia as Qr,j as jr,k as _t,ka as Xr,la as Yr,ma as Zr,n as Pt,na as Vr,q as Br,qa as eo,ra as to,u as Wr,ua as no,va as so}from"./chunk-P3GQPEMU.js";import{b as Rr}from"./chunk-MEFPXHQJ.js";import{a as Mn}from"./chunk-W4YR2RO2.js";import{a as Ar}from"./chunk-VJVXEVZ7.js";import{b as Pr,c as Cn,d as Dr,e as Rt,h as Or}from"./chunk-LB55Q3K4.js";import{h as vr,i as $r}from"./chunk-BE64IJWM.js";import{a as $n,b as _r}from"./chunk-J3SOEFRE.js";import{a as An,b as Er}from"./chunk-SIU6STB2.js";import{e as Lr,i as Nr,j as Fr,k as Ur}from"./chunk-X5C5W3E4.js";import{a as kr}from"./chunk-WO4XKOMM.js";import{g as Ir,h as Tr}from"./chunk-WVPFWUR2.js";import{c as ur,f as lr}from"./chunk-5KVTIFRY.js";import{s as dr,v as Mt,w as cr,y as be,z as kn}from"./chunk-ES236GV6.js";import{a as Xe,b as De,f as Ct}from"./chunk-72SZI2UW.js";import{a as Ee,b as bn}from"./chunk-FCPTN6NF.js";import{a as gr,c as pr}from"./chunk-MYVHVJWZ.js";import{e as Oe,h as fr,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as mr,b as hr,c as yr,d as wr,l as br}from"./chunk-AV7T3SYT.js";import{a as xr,b as Sr}from"./chunk-LE3BXIUF.js";import{c as Xs,d as Ys}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Aa as nr,Ea as Bd,Ka as sr,La as Tn,Ma as rr,Na as Qe,Oa as or,Pa as ir,Va as ar,sa as tr,va as In,vb as Wd,xa as jd}from"./chunk-NGGEGY5K.js";import{g as ze,h as Ud}from"./chunk-VJ5HC63R.js";import{j as Sn,r as Hd}from"./chunk-UEEB3UTU.js";import{a as Zs,b as pe,c as Vs,d as er,e as xn}from"./chunk-GZIHLADX.js";kn();Ct();var Ot="tool-set",io=["answer","code","full"],ao={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},qd=.1;function uo(n){return{task:co(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:co(n.agentPrompt,600)}:{}}}var lo={bundle:De({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function go(n,e=qd){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Rn(s.answer),o=Rn(s.code),i=Rn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function po(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>ao.answer.includes(t))?"answer":e.every(t=>ao.code.includes(t))?"code":"full"}function fo(n,e){return io.indexOf(n)<io.indexOf(e)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function co(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var mo=!1;function ho(n,e){let t=Mt(Ot);if(t!=="off")return t==="active"&&!mo&&(mo=!0,e(`[decisions] seat "${Ot}" is set to active, but only shadow is built: it records and changes nothing`)),be(Ot,uo(n),lo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=go(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function yo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=po(r);cr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(fo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Gd(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function wo(n,e){let t=Gd(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function _n(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}kn();Ct();var bo="session-continuity",xo={continues:Xe("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:Xe("Does the new request refer to something stated earlier in the conversation?")};function So(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Pn(n.message,1200),previousRequest:n.previousMessage?Pn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Pn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Io(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Pn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as qt}from"execa";import{spawn as Kd}from"node:child_process";import{createHash as Jd}from"node:crypto";import{createInterface as zd}from"node:readline";var xe=class extends Error{},Qd=n=>Kd("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),En=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(),zd({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 s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Dn=class{constructor(e=Qd,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}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 s=Jd("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([h],[P])=>h.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new xe("Conversation already running");r&&(r.fingerprint!==s||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 h=[...this.entries].find(([,P])=>!P.connection.busy);if(!h)throw new xe("Codex warm process capacity reached");h[1].connection.close(),this.entries.delete(h[0])}try{r={fingerprint:s,connection:new En(e,this.launchProcess)}}catch{throw new xe("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,g,m=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),C=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 h={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...h,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(C),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let D=new Promise((A,_)=>{i.failTurn=_,i.notify=(M,N)=>{if(N?.threadId!==u)return;let L=N.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:M.replace("/","."),...L?{item:{...L,type:W[L.type]||L.type}}:{}}),M==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),M==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=N.delta,e.onDelta?.(N.delta,c)),M==="thread/tokenUsage/updated"){let U=N.tokenUsage.last;g=U.inputTokens;let q=U.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(U.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(U.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(U.cacheWriteInputTokens||0)}}M==="turn/completed"&&(N.turn.status==="completed"?A():_(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return D.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await D,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:g,duration:Date.now()-t}}catch(h){if(i.close(),!a&&!e.signal?.aborted)throw new xe(h.message);return{content:c,codexSessionId:u,usage:l,contextTokens:g,error:h.message,duration:Date.now()-t}}finally{clearTimeout(C),clearTimeout(b),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())}}},To=new Dn;import{execFile as hc}from"child_process";import{StringDecoder as nt}from"string_decoder";import{mkdtempSync as jo,readFileSync as Bo,rmSync as Wo}from"fs";import{join as Bt}from"path";import{tmpdir as qo}from"os";function Lt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Nt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Ft(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var ko=null;function Ut(){return ko}function Op(n){ko=n}function Ze(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Xd(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Le=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},vo=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 s=Ze(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Xd(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${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 Le(`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 Le(`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(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ze(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=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<s&&(s=i,t=o)}if(!t)return!1;let r=Ze(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,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.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),s.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(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Yd}from"child_process";import{randomUUID as Zd}from"crypto";import{existsSync as Vd,readFileSync as ec}from"fs";import{resolve as tc}from"path";function nc(n){let e=tc(n,"CLAUDE.md");if(!Vd(e))return null;try{let t=ec(e,"utf8");return br(t)}catch{return null}}var sc=20*60*1e3,rc=5e3,Ve=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},et=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function oc(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var $o=class{constructor(e={}){this.opts=e}spawn(e,t){return new On(e,t,this.opts)}},On=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Yd(r,o,{cwd:t.workspace,env:Ce(oc({...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:nc(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),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=Zd(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
- `);let c=e.deadlineMs??sc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ve(c)),l=!1,g=null;try{for(;;){let m=d-Date.now();if(m<=0)throw u();let y=await this.nextEvent(m);if(y===null&&this.killReason)throw new et(this.killReason);if(y===null&&!this.exited)throw u();if(y===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(y.type==="user"&&y.uuid===i)l=!0,g&&(yield{type:g.type,raw:g});else if(y.type==="system"&&y.subtype==="init")g=y;else if(y.type==="result"){g=null;let b=typeof y.result=="string"?y.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:y.type,raw:y},y.type==="result"){this.onResultEvent(y);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{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 s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},rc);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),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
- `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}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 s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=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:s,state:"idle"}}};xn();Hd();bn();import{resolve as Ao,join as Co}from"path";var ic=4e3;function Ht(n){try{let e=Co(Ao(n.root),".agentx","db.sqlite"),t=Sn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,ic):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
1
+ import{Ba as oo,Da as io,G as Gr,N as Et,O as Kr,V as Dt,X as Jr,a as Cr,b as Mr,d as vn,f as Ye,ha as zr,i as Hr,ia as Qr,j as jr,ja as Xr,k as _t,la as Yr,ma as Zr,n as Pt,na as Vr,oa as eo,q as Br,r as Wr,ra as to,sa as no,v as qr,va as so,wa as ro}from"./chunk-PD5BZYBO.js";import{b as Rr}from"./chunk-MEFPXHQJ.js";import{a as Mn}from"./chunk-W4YR2RO2.js";import{a as Ar}from"./chunk-VJVXEVZ7.js";import{b as Pr,c as Cn,d as Dr,e as Rt,h as Or}from"./chunk-LB55Q3K4.js";import{h as vr,i as $r}from"./chunk-BE64IJWM.js";import{a as $n,b as _r}from"./chunk-J3SOEFRE.js";import{a as An,b as Er}from"./chunk-SIU6STB2.js";import{e as Lr,i as Nr,j as Fr,k as Ur}from"./chunk-X5C5W3E4.js";import{a as kr}from"./chunk-WO4XKOMM.js";import{g as Ir,h as Tr}from"./chunk-WVPFWUR2.js";import{c as ur,f as lr}from"./chunk-5KVTIFRY.js";import{s as dr,v as Mt,w as cr,y as be,z as kn}from"./chunk-ES236GV6.js";import{a as Xe,b as De,f as Ct}from"./chunk-72SZI2UW.js";import{a as Ee,b as bn}from"./chunk-FCPTN6NF.js";import{a as gr,c as pr}from"./chunk-MYVHVJWZ.js";import{e as Oe,h as fr,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as mr,b as hr,c as yr,d as wr,l as br}from"./chunk-AV7T3SYT.js";import{a as xr,b as Sr}from"./chunk-LE3BXIUF.js";import{c as Xs,d as Ys}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Aa as nr,Ea as Wd,Ka as sr,La as Tn,Ma as rr,Na as Qe,Oa as or,Pa as ir,Va as ar,sa as tr,va as In,vb as qd,xa as Bd}from"./chunk-NGGEGY5K.js";import{g as ze,h as Hd}from"./chunk-VJ5HC63R.js";import{j as Sn,r as jd}from"./chunk-UEEB3UTU.js";import{a as Zs,b as pe,c as Vs,d as er,e as xn}from"./chunk-GZIHLADX.js";kn();Ct();var Ot="tool-set",ao=["answer","code","full"],co={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Gd=.1;function lo(n){return{task:uo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:uo(n.agentPrompt,600)}:{}}}var go={bundle:De({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function po(n,e=Gd){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Rn(s.answer),o=Rn(s.code),i=Rn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function fo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>co.answer.includes(t))?"answer":e.every(t=>co.code.includes(t))?"code":"full"}function mo(n,e){return ao.indexOf(n)<ao.indexOf(e)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function uo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ho=!1;function yo(n,e){let t=Mt(Ot);if(t!=="off")return t==="active"&&!ho&&(ho=!0,e(`[decisions] seat "${Ot}" is set to active, but only shadow is built: it records and changes nothing`)),be(Ot,lo(n),go,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=po(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function wo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=fo(r);cr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(mo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Kd(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function bo(n,e){let t=Kd(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function _n(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}kn();Ct();var xo="session-continuity",So={continues:Xe("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:Xe("Does the new request refer to something stated earlier in the conversation?")};function Io(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Pn(n.message,1200),previousRequest:n.previousMessage?Pn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Pn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function To(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Pn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as qt}from"execa";import{spawn as Jd}from"node:child_process";import{createHash as zd}from"node:crypto";import{createInterface as Qd}from"node:readline";var xe=class extends Error{},Xd=n=>Jd("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),En=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(),Qd({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 s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Dn=class{constructor(e=Xd,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}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 s=zd("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([h],[P])=>h.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new xe("Conversation already running");r&&(r.fingerprint!==s||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 h=[...this.entries].find(([,P])=>!P.connection.busy);if(!h)throw new xe("Codex warm process capacity reached");h[1].connection.close(),this.entries.delete(h[0])}try{r={fingerprint:s,connection:new En(e,this.launchProcess)}}catch{throw new xe("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,g,m=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),C=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 h={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...h,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(C),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let D=new Promise((A,_)=>{i.failTurn=_,i.notify=(M,N)=>{if(N?.threadId!==u)return;let L=N.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:M.replace("/","."),...L?{item:{...L,type:W[L.type]||L.type}}:{}}),M==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),M==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=N.delta,e.onDelta?.(N.delta,c)),M==="thread/tokenUsage/updated"){let U=N.tokenUsage.last;g=U.inputTokens;let q=U.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(U.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(U.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(U.cacheWriteInputTokens||0)}}M==="turn/completed"&&(N.turn.status==="completed"?A():_(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return D.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await D,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:g,duration:Date.now()-t}}catch(h){if(i.close(),!a&&!e.signal?.aborted)throw new xe(h.message);return{content:c,codexSessionId:u,usage:l,contextTokens:g,error:h.message,duration:Date.now()-t}}finally{clearTimeout(C),clearTimeout(b),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())}}},ko=new Dn;import{execFile as yc}from"child_process";import{StringDecoder as nt}from"string_decoder";import{mkdtempSync as Bo,readFileSync as Wo,rmSync as qo}from"fs";import{join as Bt}from"path";import{tmpdir as Go}from"os";function Lt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Nt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Ft(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var vo=null;function Ut(){return vo}function Lp(n){vo=n}function Ze(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Yd(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Le=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},$o=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 s=Ze(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Yd(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${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 Le(`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 Le(`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(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ze(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=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<s&&(s=i,t=o)}if(!t)return!1;let r=Ze(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,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.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),s.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(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Zd}from"child_process";import{randomUUID as Vd}from"crypto";import{existsSync as ec,readFileSync as tc}from"fs";import{resolve as nc}from"path";function sc(n){let e=nc(n,"CLAUDE.md");if(!ec(e))return null;try{let t=tc(e,"utf8");return br(t)}catch{return null}}var rc=20*60*1e3,oc=5e3,Ve=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},et=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function ic(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Ao=class{constructor(e={}){this.opts=e}spawn(e,t){return new On(e,t,this.opts)}},On=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Zd(r,o,{cwd:t.workspace,env:Ce(ic({...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:sc(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),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=Vd(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
+ `);let c=e.deadlineMs??rc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ve(c)),l=!1,g=null;try{for(;;){let m=d-Date.now();if(m<=0)throw u();let y=await this.nextEvent(m);if(y===null&&this.killReason)throw new et(this.killReason);if(y===null&&!this.exited)throw u();if(y===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(y.type==="user"&&y.uuid===i)l=!0,g&&(yield{type:g.type,raw:g});else if(y.type==="system"&&y.subtype==="init")g=y;else if(y.type==="result"){g=null;let b=typeof y.result=="string"?y.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:y.type,raw:y},y.type==="result"){this.onResultEvent(y);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{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 s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},oc);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),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
+ `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}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 s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=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:s,state:"idle"}}};xn();jd();bn();import{resolve as Co,join as Mo}from"path";var ac=4e3;function Ht(n){try{let e=Mo(Co(n.root),".agentx","db.sqlite"),t=Sn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,ac):n.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:s,ts:Date.now(),agent_id:n.input.agentId??null,task_id:n.taskId??null,tool:n.input.tool,command:r,resolved_target:n.verdict.resolvedTarget,matched_rule:n.verdict.ruleId,verdict:n.verdict.action,effective_action:n.verdict.effectiveAction,mode:n.mode,severity:n.verdict.severity,approver:n.approver??null,ms:n.ms??null}),s}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
9
- `),null}}function zp(n){let e=Co(Ao(n.root),".agentx","db.sqlite"),t=Sn({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}xn();var ac=50,dc=6*60*60*1e3,jt=null,Ne=new Map;function Zp(n){jt=n===null?null:String(n)}function Ro(){return jt}function cc(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function _o(n,e,t){if(!pe(n))return{args:[]};if(!jt)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:cc(jt,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function Po(n,e){return!pe(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function uc(n){for(let[e,t]of Ne)n-t.at>dc&&Ne.delete(e)}function lc(n,e){let t=Date.now();uc(t);let s=Ne.get(n)??{at:t,blocks:[]};s.blocks.length<ac&&s.blocks.push(e),s.at=t,Ne.set(n,s)}function Eo(n){if(!n)return[];let e=Ne.get(n);return Ne.delete(n),e?.blocks??[]}function Mo(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function Vp(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0;try{let o=Zs.safeParse(e.level),i=o.success?Vs(o.data,{tool:t,command:s,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.reason??"blocked",u={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:c,reason:d},l={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return Ht({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:l,mode:"enforce",taskId:e.taskId??null}),e.taskId&&lc(e.taskId,u),{stdout:Mo(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:u}}catch(o){return{stdout:Mo(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}ir();var gc=6*60*60*1e3,tt=new Map;function pc(n){for(let[e,t]of tt)n-t.at>gc&&tt.delete(e)}function Do(n,e){let t=Date.now();pc(t),tt.set(n,{at:t,limits:e})}function Oo(n){tt.delete(n)}function fc(n,e,t){let s=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:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function Lo(n,e,t){let s=Ro();if(!s)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:fc(s,e,t),timeout:15}]},o=[...n],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 No(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function Ln(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function mc(n,e,t){if(n.tools.some(s=>Qe(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>Qe(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function rf(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?tt.get(e.taskId):void 0;if(!r)return{stdout:Ln("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=mc(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,c={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Ht({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:c,mode:"enforce",taskId:e.taskId??null}),{stdout:Ln(`[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:Ln(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var yc=5e3;function Z(n){let e=Lt(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
- `)}return{error:Nt(e),errorKind:e.kind}}function Go(){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 Wt(){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 Fo(){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 Se(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
9
+ `),null}}function Qp(n){let e=Mo(Co(n.root),".agentx","db.sqlite"),t=Sn({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}xn();var dc=50,cc=6*60*60*1e3,jt=null,Ne=new Map;function Vp(n){jt=n===null?null:String(n)}function _o(){return jt}function uc(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function Po(n,e,t){if(!pe(n))return{args:[]};if(!jt)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:uc(jt,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function Eo(n,e){return!pe(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function lc(n){for(let[e,t]of Ne)n-t.at>cc&&Ne.delete(e)}function gc(n,e){let t=Date.now();lc(t);let s=Ne.get(n)??{at:t,blocks:[]};s.blocks.length<dc&&s.blocks.push(e),s.at=t,Ne.set(n,s)}function Do(n){if(!n)return[];let e=Ne.get(n);return Ne.delete(n),e?.blocks??[]}function Ro(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function ef(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0;try{let o=Zs.safeParse(e.level),i=o.success?Vs(o.data,{tool:t,command:s,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.reason??"blocked",u={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:c,reason:d},l={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return Ht({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:l,mode:"enforce",taskId:e.taskId??null}),e.taskId&&gc(e.taskId,u),{stdout:Ro(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:u}}catch(o){return{stdout:Ro(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}ir();var pc=6*60*60*1e3,tt=new Map;function fc(n){for(let[e,t]of tt)n-t.at>pc&&tt.delete(e)}function Oo(n,e){let t=Date.now();fc(t),tt.set(n,{at:t,limits:e})}function Lo(n){tt.delete(n)}function mc(n,e,t){let s=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:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function No(n,e,t){let s=_o();if(!s)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:mc(s,e,t),timeout:15}]},o=[...n],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 Fo(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function Ln(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function hc(n,e,t){if(n.tools.some(s=>Qe(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>Qe(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function of(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?tt.get(e.taskId):void 0;if(!r)return{stdout:Ln("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=hc(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,c={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Ht({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:c,mode:"enforce",taskId:e.taskId??null}),{stdout:Ln(`[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:Ln(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var wc=5e3;function Z(n){let e=Lt(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
+ `)}return{error:Nt(e),errorKind:e.kind}}function Ko(){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 Wt(){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 Uo(){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 Se(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
11
11
  `))}return e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
12
- `)}function Ko(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let c=r||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Fn(n,e){return!e||e.trim().length===0?n:`[System]
12
+ `)}function Jo(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let c=r||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Fn(n,e){return!e||e.trim().length===0?n:`[System]
13
13
  ${e.trim()}
14
14
 
15
15
  [User]
16
- ${n}`}function wc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Fn(e,s)),o}function bc(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function Uo(n){return JSON.stringify(n)}function Jo(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Uo(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(Uo).join(",")}]`]}function zo(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Jo()),i||a.push("--color","never");let c=s||n.model;return c&&a.push("--model",c),n.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(Fn(e,r)),a}function Gt(n,e){let t=Oe(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.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(":"),st(t,e)}function st(n,e){return n.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function Qo(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),n}function Kt(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function xc(n,e){let t=Gt(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.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({...s,mcp:r}),t}function Sc(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function fe(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Un(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object"){let s=fe(t.cached_input_tokens,t.cachedInputTokens),r=fe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:fe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:fe(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:fe(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Un(s,e+1);if(r)return r}}function Xo(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function Hn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=Hn(t,e+1);if(s)return s}}}function Ic(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
17
- `))if(i.trim())try{let a=JSON.parse(i);t=Un(a)||t,s=Xo(a)||s,r=Hn(a)||r,o=Yo(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Yo(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return Ho(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return Ho(e)}}}function Ho(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function Tc(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function jn(n,e,t,s,r){let o=Tc(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
18
- `)}function kc(n){try{let e=JSON.parse(n);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 vc(n){try{let e=JSON.parse(n),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,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||Ft(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function Zo(n,e,t,s,r){let o=Date.now(),i=Se(n,e,t),a=ei(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=Ko(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(jn(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:l,stderr:g,exitCode:m,killed:y}=await new Promise(h=>{let P=Ce(Qo(st(Oe(n.workspace),e),e),n.billing),D=!1,A=hc("claude",c,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...P,HOME:P.HOME||"/home/"+(P.USER||"user")}},(_,M,N)=>{h({stdout:M||"",stderr:N||"",exitCode:_?_.code??1:0,killed:D})});if(A.stdin?.end(),r){let _=()=>{D=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.killed||A.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?_():r.addEventListener("abort",_,{once:!0})}});if(y)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&m!==0){let h,P=Date.now()-o;return m===143&&P<u-yc?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(P/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:P}:(m===143?h=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?h=Go():h=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...Z(h),duration:Date.now()-o})}let b=kc(l);if(b)return{content:"",...Z(b),duration:Date.now()-o};let C=vc(l);return{content:C.text,duration:Date.now()-o,claudeSessionId:C.sessionId,usage:C.usage,numTurns:C.numTurns,costUsd:C.costUsd,billedModel:C.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function Vo(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=Se(n,e,s),d=ei(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let u=Ko(n,c,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...d.args]);jn(e.agentId,n,e.model,r,"stream");let l="",g="",m="",y=L=>{let W=g&&!m?`
16
+ ${n}`}function bc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Fn(e,s)),o}function xc(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function Ho(n){return JSON.stringify(n)}function zo(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${Ho(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(Ho).join(",")}]`]}function Qo(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...zo()),i||a.push("--color","never");let c=s||n.model;return c&&a.push("--model",c),n.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(Fn(e,r)),a}function Gt(n,e){let t=Oe(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.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(":"),st(t,e)}function st(n,e){return n.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function Xo(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),n}function Kt(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function Sc(n,e){let t=Gt(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.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({...s,mcp:r}),t}function Ic(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function fe(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Un(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object"){let s=fe(t.cached_input_tokens,t.cachedInputTokens),r=fe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:fe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:fe(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:fe(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Un(s,e+1);if(r)return r}}function Yo(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function Hn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=Hn(t,e+1);if(s)return s}}}function Tc(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
17
+ `))if(i.trim())try{let a=JSON.parse(i);t=Un(a)||t,s=Yo(a)||s,r=Hn(a)||r,o=Zo(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Zo(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return jo(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return jo(e)}}}function jo(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function kc(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function jn(n,e,t,s,r){let o=kc(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
18
+ `)}function vc(n){try{let e=JSON.parse(n);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 $c(n){try{let e=JSON.parse(n),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,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||Ft(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function Vo(n,e,t,s,r){let o=Date.now(),i=Se(n,e,t),a=ti(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=Jo(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(jn(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:l,stderr:g,exitCode:m,killed:y}=await new Promise(h=>{let P=Ce(Xo(st(Oe(n.workspace),e),e),n.billing),D=!1,A=yc("claude",c,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...P,HOME:P.HOME||"/home/"+(P.USER||"user")}},(_,M,N)=>{h({stdout:M||"",stderr:N||"",exitCode:_?_.code??1:0,killed:D})});if(A.stdin?.end(),r){let _=()=>{D=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.killed||A.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?_():r.addEventListener("abort",_,{once:!0})}});if(y)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&m!==0){let h,P=Date.now()-o;return m===143&&P<u-wc?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(P/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:P}:(m===143?h=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?h=Ko():h=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...Z(h),duration:Date.now()-o})}let b=vc(l);if(b)return{content:"",...Z(b),duration:Date.now()-o};let C=$c(l);return{content:C.text,duration:Date.now()-o,claudeSessionId:C.sessionId,usage:C.usage,numTurns:C.numTurns,costUsd:C.costUsd,billedModel:C.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function ei(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=Se(n,e,s),d=ti(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let u=Jo(n,c,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...d.args]);jn(e.agentId,n,e.model,r,"stream");let l="",g="",m="",y=L=>{let W=g&&!m?`
19
19
 
20
20
  `:"";m+=L,l=g+(g?`
21
21
 
22
- `:"")+m,t(W+L,l)},b=new Nn,C=!1,h,P,D,A,_,M,N;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),W=Ce(Qo(st(Oe(n.workspace),e),e),n.billing),U=qt("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:W,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},X=new Promise(J=>{q=J}),v=!1,T;if(i){let J=()=>{v=!0,T=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{U.kill("SIGTERM")}catch{}setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?J():i.addEventListener("abort",J,{once:!0})}let x="",F=new nt("utf8");U.stdout&&U.stdout.on("data",J=>{x+=F.write(J);let re=x.split(`
22
+ `:"")+m,t(W+L,l)},b=new Nn,C=!1,h,P,D,A,_,M,N;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),W=Ce(Xo(st(Oe(n.workspace),e),e),n.billing),U=qt("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:W,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},X=new Promise(J=>{q=J}),v=!1,T;if(i){let J=()=>{v=!0,T=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{U.kill("SIGTERM")}catch{}setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?J():i.addEventListener("abort",J,{once:!0})}let x="",F=new nt("utf8");U.stdout&&U.stdout.on("data",J=>{x+=F.write(J);let re=x.split(`
23
23
  `);x=re.pop()||"";for(let ee of re)if(ee.trim())try{let R=JSON.parse(ee);if(o)try{o(R)}catch{}if(R.type==="assistant"&&R.message?.usage){let te=R.message.usage,ie=(te.input_tokens||0)+(te.cache_read_input_tokens||0)+(te.cache_creation_input_tokens||0);ie>0&&(A=ie)}if(R.type==="assistant"&&R.message?.content){for(let te of R.message.content)if(te.type==="text"&&te.text){let ie=te.text.slice(m.length);ie&&y(ie)}}if(R.type==="content_block_delta"&&R.delta?.text&&y(R.delta.text),b.observe(R),R.type==="result"&&R.result){if(R.is_error&&typeof R.result=="string")N=R.result;else{let te=(typeof R.result=="string",R.result);if(typeof te=="string"&&te.length>m.length){let ie=te.slice(m.length);ie&&y(ie)}}R.usage&&(P={inputTokens:R.usage.input_tokens||0,outputTokens:R.usage.output_tokens||0,cacheReadTokens:R.usage.cache_read_input_tokens||0,cacheCreateTokens:R.usage.cache_creation_input_tokens||0}),typeof R.model=="string"?h=R.model:h=Ft(R.modelUsage)||h,typeof R.session_id=="string"&&(D=R.session_id),typeof R.num_turns=="number"&&(_=R.num_turns),typeof R.total_cost_usd=="number"&&(M=R.total_cost_usd)}R.type==="result"&&(b.pending===0?q():(C||process.stderr.write(`[claude-stream] agent=${e.agentId} task=${e.taskId??"?"} turn ended with ${b.pending} background task(s) running; the task stays open until they end
24
24
  `),C=!0,m&&(g=l,m=""))),R.type==="system"&&R.subtype==="init"&&(typeof R.model=="string"&&(h=R.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${R.apiKeySource} version=${R.claude_code_version} model=${R.model} permMode=${R.permissionMode}
25
25
  `))}catch{ee.trim()&&!ee.startsWith("{")&&y(ee+`
26
- `)}});let j=await Pc(U,X),E=F.end();if(E&&(x+=E),v)return{content:"",error:T||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!l&&j.stdout&&(l=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!l){let J=typeof j.stderr=="string"?j.stderr:"",re=j,ee;return re.timedOut?ee=`Claude Code timed out after ${Math.round(L/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:re.signal?ee=J.trim()||`Claude Code killed by signal ${re.signal}`:re.code==="ENOENT"||/ENOENT|spawn claude/i.test((re.shortMessage||"")+" "+J)?ee=Go():ee=J.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...Z(ee),duration:Date.now()-a}}return N?{content:"",...Z(N),duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,billedModel:h,claudeSessionId:D}:{content:l,duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,costUsd:M,billedModel:h,claudeSessionId:D}}catch(L){return{content:l||"",...Z(L.message),duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,billedModel:h,claudeSessionId:D}}}async function $c(n,e,t,s){let r=Date.now(),o=Se(n,e,t),i=jo(Bt(qo(),"agentx-codex-")),a=Bt(i,"last-message.txt"),c=zo(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let d=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await qt("codex",c,{cwd:e.cwd??n.workspace,timeout:d,reject:!1,env:Gt(n,e),extendEnv:!1,stdin:"ignore"}),l=Ic(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,y;return m.timedOut?y=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?y=l.apiError:m.signal?y=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?y=Wt():y=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...Z(y),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let g="";try{g=Bo(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Wt():d?.message;return{content:"",...Z(u||"Codex CLI failed"),duration:Date.now()-r}}finally{Wo(i,{recursive:!0,force:!0})}}async function Ac(n,e,t,s,r,o){let i=Date.now(),a=Se(n,e,s),c=jo(Bt(qo(),"agentx-codex-")),d=Bt(c,"last-message.txt"),u=zo(n,a,!0,e.model,e.systemPromptAppend,d,r),l="",g,m,y,b;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),h=qt("codex",u,{cwd:e.cwd??n.workspace,timeout:C,reject:!1,env:Gt(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let P="",D="",A=!1,_=new nt("utf8"),M=new nt("utf8"),N=Math.min(C,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,W=()=>{L&&clearTimeout(L),L=setTimeout(()=>{A=!0,h.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};W(),h.stderr?.on("data",T=>{W(),D+=M.write(T),D.length>16e3&&(D=D.slice(-16e3))}),h.stdout?.on("data",T=>{W(),P+=_.write(T);let x=P.split(`
27
- `);P=x.pop()||"";for(let F of x)if(F.trim())try{let j=JSON.parse(F);if(o)try{o(j)}catch{}g=Un(j)||g,m=Xo(j)||m,y=Hn(j)||y,b=Yo(j)||b;let E=Sc(j);if(E&&E!==l){let J=E.startsWith(l)?E.slice(l.length):E;l=E.startsWith(l)?E:l+E,J&&t(J,l)}}catch{l+=F+`
26
+ `)}});let j=await Ec(U,X),E=F.end();if(E&&(x+=E),v)return{content:"",error:T||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!l&&j.stdout&&(l=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!l){let J=typeof j.stderr=="string"?j.stderr:"",re=j,ee;return re.timedOut?ee=`Claude Code timed out after ${Math.round(L/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:re.signal?ee=J.trim()||`Claude Code killed by signal ${re.signal}`:re.code==="ENOENT"||/ENOENT|spawn claude/i.test((re.shortMessage||"")+" "+J)?ee=Ko():ee=J.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...Z(ee),duration:Date.now()-a}}return N?{content:"",...Z(N),duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,billedModel:h,claudeSessionId:D}:{content:l,duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,costUsd:M,billedModel:h,claudeSessionId:D}}catch(L){return{content:l||"",...Z(L.message),duration:Date.now()-a,usage:P,contextTokens:A,numTurns:_,billedModel:h,claudeSessionId:D}}}async function Ac(n,e,t,s){let r=Date.now(),o=Se(n,e,t),i=Bo(Bt(Go(),"agentx-codex-")),a=Bt(i,"last-message.txt"),c=Qo(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let d=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await qt("codex",c,{cwd:e.cwd??n.workspace,timeout:d,reject:!1,env:Gt(n,e),extendEnv:!1,stdin:"ignore"}),l=Tc(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,y;return m.timedOut?y=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?y=l.apiError:m.signal?y=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?y=Wt():y=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...Z(y),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let g="";try{g=Wo(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Wt():d?.message;return{content:"",...Z(u||"Codex CLI failed"),duration:Date.now()-r}}finally{qo(i,{recursive:!0,force:!0})}}async function Cc(n,e,t,s,r,o){let i=Date.now(),a=Se(n,e,s),c=Bo(Bt(Go(),"agentx-codex-")),d=Bt(c,"last-message.txt"),u=Qo(n,a,!0,e.model,e.systemPromptAppend,d,r),l="",g,m,y,b;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),h=qt("codex",u,{cwd:e.cwd??n.workspace,timeout:C,reject:!1,env:Gt(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let P="",D="",A=!1,_=new nt("utf8"),M=new nt("utf8"),N=Math.min(C,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,W=()=>{L&&clearTimeout(L),L=setTimeout(()=>{A=!0,h.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};W(),h.stderr?.on("data",T=>{W(),D+=M.write(T),D.length>16e3&&(D=D.slice(-16e3))}),h.stdout?.on("data",T=>{W(),P+=_.write(T);let x=P.split(`
27
+ `);P=x.pop()||"";for(let F of x)if(F.trim())try{let j=JSON.parse(F);if(o)try{o(j)}catch{}g=Un(j)||g,m=Yo(j)||m,y=Hn(j)||y,b=Zo(j)||b;let E=Ic(j);if(E&&E!==l){let J=E.startsWith(l)?E.slice(l.length):E;l=E.startsWith(l)?E:l+E,J&&t(J,l)}}catch{l+=F+`
28
28
  `,t(F+`
29
- `,l)}});let U=await h;L&&clearTimeout(L);let q=_.end();q&&(P+=q);let X=M.end();if(X&&(D+=X),U.exitCode!==0&&!l||b){let T=D||(typeof U.stderr=="string"?U.stderr:""),x=U,F;return A?F=`Codex CLI produced no output for ${Math.round(N/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.`:x.timedOut?F=`Codex CLI timed out after ${Math.round(C/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:b?F=b:x.signal?F=T.trim()||`Codex CLI killed by signal ${x.signal}`:x.code==="ENOENT"||/ENOENT|spawn codex/i.test((x.shortMessage||"")+" "+T)?F=Wt():F=T.trim()||`Codex CLI exited with code ${x.exitCode??"unknown"}`,{content:"",...Z(F),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}let v="";try{v=Bo(d,"utf8").trim()}catch{}if(v&&v!==l){let T=v.startsWith(l)?v.slice(l.length):v;l=v,T&&t(T,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}catch(C){let h=/ENOENT|spawn codex/i.test(C?.message||"")?Wt():C?.message;return{content:l,...Z(h||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}finally{Wo(c,{recursive:!0,force:!0})}}async function Cc(n,e,t,s,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=Se(n,e,s),u=wc(n,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",g,m=e.freshSession?void 0:r,y,b,C=!0,h;try{let P=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),D=xc(n,e);if(n.persistentProcess)try{b=await pr.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:D,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",b.url),D=b.env,o?.({type:"opencode.ready",reused:b.reused,startupMs:Date.now()-c})}catch(T){if(!(T instanceof gr))throw T;T.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:T.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=qt("opencode",u,{cwd:e.cwd??n.workspace,timeout:P,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let _=!1,M,N=()=>{b?.invalidate(),_=!0,M=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),h=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let L="",W="",U=new nt("utf8"),q=new nt("utf8"),X=T=>{if(T.trim())try{let x=JSON.parse(T);try{o?.(x)}catch{}typeof x.sessionID=="string"&&(m=x.sessionID);let F=x.type==="text"&&typeof x.part?.text=="string"?x.part.text:void 0;F&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:b?.reused??!1}),l+=F,t?.(F,l));let j=x.type==="reasoning"&&typeof x.part?.text=="string"?x.part.text:void 0;j&&a?.(j);let E=x.type==="step_finish"?x.part?.tokens:void 0;E&&(g={inputTokens:fe(E.input),outputTokens:fe(E.output),cacheReadTokens:fe(E.cache?.read),cacheCreateTokens:fe(E.cache?.write)}),y=bc(x)||y}catch{l+=T+`
29
+ `,l)}});let U=await h;L&&clearTimeout(L);let q=_.end();q&&(P+=q);let X=M.end();if(X&&(D+=X),U.exitCode!==0&&!l||b){let T=D||(typeof U.stderr=="string"?U.stderr:""),x=U,F;return A?F=`Codex CLI produced no output for ${Math.round(N/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.`:x.timedOut?F=`Codex CLI timed out after ${Math.round(C/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:b?F=b:x.signal?F=T.trim()||`Codex CLI killed by signal ${x.signal}`:x.code==="ENOENT"||/ENOENT|spawn codex/i.test((x.shortMessage||"")+" "+T)?F=Wt():F=T.trim()||`Codex CLI exited with code ${x.exitCode??"unknown"}`,{content:"",...Z(F),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}let v="";try{v=Wo(d,"utf8").trim()}catch{}if(v&&v!==l){let T=v.startsWith(l)?v.slice(l.length):v;l=v,T&&t(T,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}catch(C){let h=/ENOENT|spawn codex/i.test(C?.message||"")?Wt():C?.message;return{content:l,...Z(h||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:y||r}}finally{qo(c,{recursive:!0,force:!0})}}async function Mc(n,e,t,s,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=Se(n,e,s),u=bc(n,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",g,m=e.freshSession?void 0:r,y,b,C=!0,h;try{let P=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),D=Sc(n,e);if(n.persistentProcess)try{b=await pr.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:D,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",b.url),D=b.env,o?.({type:"opencode.ready",reused:b.reused,startupMs:Date.now()-c})}catch(T){if(!(T instanceof gr))throw T;T.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:T.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=qt("opencode",u,{cwd:e.cwd??n.workspace,timeout:P,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let _=!1,M,N=()=>{b?.invalidate(),_=!0,M=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),h=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let L="",W="",U=new nt("utf8"),q=new nt("utf8"),X=T=>{if(T.trim())try{let x=JSON.parse(T);try{o?.(x)}catch{}typeof x.sessionID=="string"&&(m=x.sessionID);let F=x.type==="text"&&typeof x.part?.text=="string"?x.part.text:void 0;F&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:b?.reused??!1}),l+=F,t?.(F,l));let j=x.type==="reasoning"&&typeof x.part?.text=="string"?x.part.text:void 0;j&&a?.(j);let E=x.type==="step_finish"?x.part?.tokens:void 0;E&&(g={inputTokens:fe(E.input),outputTokens:fe(E.output),cacheReadTokens:fe(E.cache?.read),cacheCreateTokens:fe(E.cache?.write)}),y=xc(x)||y}catch{l+=T+`
30
30
  `,t?.(T+`
31
31
  `,l)}};A.stdout?.on("data",T=>{L+=U.write(T);let x=L.split(`
32
- `);L=x.pop()||"";for(let F of x)X(F)}),A.stderr?.on("data",T=>{W+=q.write(T)});let v=await A;if(i&&i.removeEventListener("abort",N),L+=U.end(),L.trim()&&X(L),W+=q.end(),_)return{content:"",error:M||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(v.exitCode!==0||y){let T=v,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?x=y:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=Fo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return C=!1,{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||n.model,opencodeSessionId:m}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(P?.message||"")?Fo():P?.message;return{content:l,...Z(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{h?.(),b?.release(C)}}async function Mc(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Rc(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let C=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(C))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let y=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);y.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let C=n.provider||"claude-code",h=s?`${s}
32
+ `);L=x.pop()||"";for(let F of x)X(F)}),A.stderr?.on("data",T=>{W+=q.write(T)});let v=await A;if(i&&i.removeEventListener("abort",N),L+=U.end(),L.trim()&&X(L),W+=q.end(),_)return{content:"",error:M||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(v.exitCode!==0||y){let T=v,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?x=y:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=Uo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return C=!1,{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||n.model,opencodeSessionId:m}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(P?.message||"")?Uo():P?.message;return{content:l,...Z(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{h?.(),b?.release(C)}}async function Rc(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function _c(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let C=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(C))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let y=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);y.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let C=n.provider||"claude-code",h=s?`${s}
33
33
 
34
- ${e.message}`:e.message,P=e.context?.sender,D=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&D?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=wr(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-2SQYGIUD.js"),v="",T,x,F,j;for await(let E of X(N)){if(c)try{c(E)}catch{}if(E.type==="text_delta")v+=E.text,r(E.text,v);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}T=E.result.tokensUsed,E.result.inputTokens!=null&&(x=E.result.inputTokens),E.result.outputTokens!=null&&(F=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}E.result.tokensUsed!=null&&(T=E.result.tokensUsed)}else E.type==="error"&&(j=E.error)}return j&&!v?g?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-d}:((x===void 0||F===void 0)&&T&&(x=Math.round(T*.7),F=T-x),{content:v||"Done.",tokensUsed:T,usage:x!==void 0||F!==void 0?{inputTokens:x||0,outputTokens:F||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-2SQYGIUD.js"),W=await L(N),U=W.inputTokens,q=W.outputTokens;if((U===void 0||q===void 0)&&W.tokensUsed){let X=W.tokensUsed;U=Math.round(X*.7),q=X-U}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:U!==void 0||q!==void 0?{inputTokens:U||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(C){return g?b():C?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${C.message}`),duration:Date.now()-d}}finally{clearTimeout(y),a&&a.removeEventListener("abort",m)}}var Nn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},_c=1e3;async function Pc(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),_c),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ec(n,e,t,s,r,o,i){let a=Ut();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let v=a.list().length;g=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>v}catch(v){return v instanceof Le,null}m&&jn(e.agentId,n,e.model,s,"persistent");let y=Se(n,e,t),b="",C,h,P,D,A,_,M,N="",L="",W=v=>{if(!i||!v)return;let T;if(L&&v.startsWith(L)?T=v.slice(L.length):T=N&&!N.endsWith(`
34
+ ${e.message}`:e.message,P=e.context?.sender,D=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&D?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=wr(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-4637FJMD.js"),v="",T,x,F,j;for await(let E of X(N)){if(c)try{c(E)}catch{}if(E.type==="text_delta")v+=E.text,r(E.text,v);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}T=E.result.tokensUsed,E.result.inputTokens!=null&&(x=E.result.inputTokens),E.result.outputTokens!=null&&(F=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}E.result.tokensUsed!=null&&(T=E.result.tokensUsed)}else E.type==="error"&&(j=E.error)}return j&&!v?g?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-d}:((x===void 0||F===void 0)&&T&&(x=Math.round(T*.7),F=T-x),{content:v||"Done.",tokensUsed:T,usage:x!==void 0||F!==void 0?{inputTokens:x||0,outputTokens:F||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-4637FJMD.js"),W=await L(N),U=W.inputTokens,q=W.outputTokens;if((U===void 0||q===void 0)&&W.tokensUsed){let X=W.tokensUsed;U=Math.round(X*.7),q=X-U}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:U!==void 0||q!==void 0?{inputTokens:U||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(C){return g?b():C?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${C.message}`),duration:Date.now()-d}}finally{clearTimeout(y),a&&a.removeEventListener("abort",m)}}var Nn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},Pc=1e3;async function Ec(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Pc),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Dc(n,e,t,s,r,o,i){let a=Ut();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let v=a.list().length;g=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>v}catch(v){return v instanceof Le,null}m&&jn(e.agentId,n,e.model,s,"persistent");let y=Se(n,e,t),b="",C,h,P,D,A,_,M,N="",L="",W=v=>{if(!i||!v)return;let T;if(L&&v.startsWith(L)?T=v.slice(L.length):T=N&&!N.endsWith(`
35
35
  `)?`
36
36
 
37
- ${v}`:v,L=v,!!T){N+=T;try{i(T,N)}catch{}}},U=!1,q=()=>{U=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let X=!1;try{let v=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of g.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:v})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(L="");let F=T.raw.message?.usage;if(F){let j=(F.input_tokens||0)+(F.cache_read_input_tokens||0)+(F.cache_creation_input_tokens||0);j>0&&(D=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let F=Z(typeof x.result=="string"?x.result:"claude error");C=F.error,h=F.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,N||W(x.result));typeof x.session_id=="string"&&(M=x.session_id),x.usage&&(P={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.num_turns=="number"&&(A=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=Ft(x.modelUsage)||_}}}catch(v){if(U)C="task cancelled by operator",h="cancelled";else if(X)if(v instanceof et)C=`Claude Code was stopped mid-turn (${v.reason}), before its time limit`,h="interrupted";else if(v instanceof Ve){let T=Z(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);C=T.error,h=T.errorKind}else{let T=Z(`persistent claude process error: ${v?.message||String(v)}`);C=T.error,h=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return U&&!C&&(C="task cancelled by operator",h="cancelled"),{content:U?"":b,error:C,errorKind:h,duration:Date.now()-c,usage:P,contextTokens:D,numTurns:A,billedModel:_,claudeSessionId:M}}function ei(n){let e=pe(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?_o(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Lo(t.args,n.taskId,n.agentId)}function Dc(n){return pe(n.autonomy)||!!n.personLimits}async function Oc(n,e,t,s,r,o,i){let a=pe(e.autonomy)?e.autonomy:void 0,c=a&&Po(a,n.tier)||e.personLimits&&No(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${er(a)}
37
+ ${v}`:v,L=v,!!T){N+=T;try{i(T,N)}catch{}}},U=!1,q=()=>{U=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let X=!1;try{let v=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of g.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:v})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(L="");let F=T.raw.message?.usage;if(F){let j=(F.input_tokens||0)+(F.cache_read_input_tokens||0)+(F.cache_creation_input_tokens||0);j>0&&(D=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let F=Z(typeof x.result=="string"?x.result:"claude error");C=F.error,h=F.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,N||W(x.result));typeof x.session_id=="string"&&(M=x.session_id),x.usage&&(P={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.num_turns=="number"&&(A=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=Ft(x.modelUsage)||_}}}catch(v){if(U)C="task cancelled by operator",h="cancelled";else if(X)if(v instanceof et)C=`Claude Code was stopped mid-turn (${v.reason}), before its time limit`,h="interrupted";else if(v instanceof Ve){let T=Z(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);C=T.error,h=T.errorKind}else{let T=Z(`persistent claude process error: ${v?.message||String(v)}`);C=T.error,h=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return U&&!C&&(C="task cancelled by operator",h="cancelled"),{content:U?"":b,error:C,errorKind:h,duration:Date.now()-c,usage:P,contextTokens:D,numTurns:A,billedModel:_,claudeSessionId:M}}function ti(n){let e=pe(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Po(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:No(t.args,n.taskId,n.agentId)}function Oc(n){return pe(n.autonomy)||!!n.personLimits}async function Lc(n,e,t,s,r,o,i){let a=pe(e.autonomy)?e.autonomy:void 0,c=a&&Eo(a,n.tier)||e.personLimits&&Fo(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${er(a)}
38
38
 
39
39
  ${e.message}`:e.message},l=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${l} task=${d} via=spawn (persistent process bypassed)
40
- `),e.personLimits&&Do(d,e.personLimits);try{let g=t?await Vo(n,u,t,s,r,o,i):await Zo(n,u,s,r,i);if(!a)return g;let m=Eo(d);return{...g,autonomy:a,...m.length?{autonomyBlocks:m}:{}}}finally{e.personLimits&&Oo(d)}}async function ti(n,e,t,s,r,o,i,a,c){if(Dc(e))return Oc(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let d=await Ec(n,e,r,o,i,a,s);if(d!==null)return d}return s?Vo(n,e,s,r,o,i,a):Zo(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let d=await To.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:Gt(n,e),args:Jo(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Fn(Se(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...d,...d.error?Z(d.error):{}}}catch(d){if(!(d instanceof xe))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Ac(n,e,s,r,o,i):$c(n,e,r,o);case"opencode":return Cc(n,e,s,r,o,i,a,c);case"sdk":{let d=n.provider||"claude",u=t[d]?.apiKey;return u?Mc(n,e,u,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=n.provider||"claude-code",u=t[d],l=u?.apiKey;return Rc(n,e,l,r,s,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Fe,writeFileSync as ni,mkdirSync as Lc,existsSync as Jt,readdirSync as Bn}from"fs";import{resolve as Ue}from"path";var Wn=12e3,rt=30,Nc=720,Fc=40,Uc=18e4,Hc="[Compacted conversation summary",jc=7*864e5,Bc=[/\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 Wc(n){return n?Bc.some(e=>e.test(n)):!1}var qc=[{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 ri(n){if(!n)return null;let e=0;for(let t of qc)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function si(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function oi(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function ii(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function Gc(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var zt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ue(e,".agentx/sessions"),Jt(this.sessionsDir)||Lc(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Nc),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Fc),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Uc),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let u=await c.seedHistory(s,{maxMessages:rt,maxChars:Wn});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.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,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ue(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(Jt(o))try{let d=JSON.parse(Fe(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!Jt(i))return null;try{return JSON.parse(Fe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);si(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,s,r){let o=this.getSession(e,t,s),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,s,r){let o=this.getSession(e,t,s);si(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,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}continueFrom(e,t,s){if(t.channel===s.channel&&t.chatId===s.chatId)return!1;let r=this.sessionKey(e,t.channel,t.chatId);if(!(this.cache.has(r)||Jt(this.sessionFile(r))||this.loadPreviousDaySession(e,t.channel,t.chatId)!==null))return!1;let i=this.getSession(e,t.channel,t.chatId);if(!i.claudeSessionId&&!i.codexSessionId&&!i.opencodeSessionId)return!1;let a=this.getSession(e,s.channel,s.chatId);return a.claudeSessionId=i.claudeSessionId,a.codexSessionId=i.codexSessionId,a.opencodeSessionId=i.opencodeSessionId,a.turnCount=i.turnCount,a.lastTurnInputTokens=i.lastTurnInputTokens,a.lastTurnContextTokens=i.lastTurnContextTokens,a.updatedAt=i.updatedAt,this.save(a),!0}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??rt),a=Math.max(200,r.maxChars??Wn),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let m=Gc(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let y=g.name||(g.role==="user"?"User":"Agent");u.push(`${y}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
- `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.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():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Bn(this.sessionsDir).filter(A=>A.startsWith(`${a}:`)&&A.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(A=>{let _=A.match(l);if(!_)return!1;let M=_[1];return M>=d&&M<=u}),m=[],y=0,b=e.query?.toLowerCase(),C=e.participants?.length?new Set(e.participants):void 0;for(let A of g){let _;try{_=JSON.parse(Fe(Ue(this.sessionsDir,A),"utf-8"))}catch{continue}if(_.agentId===e.agentId&&!(e.channel&&_.channel!==e.channel)&&!(e.chatId&&_.chatId!==e.chatId))for(let M of _.messages)y++,!(!M.timestamp||M.timestamp<o||M.timestamp>=i)&&(C&&M.role==="user"&&!C.has(M.name??"")||b&&!M.content.toLowerCase().includes(b)||m.push({ts:M.timestamp,role:M.role,senderName:M.name??"",content:M.content,channel:_.channel,chatId:_.chatId,day:_.day,sessionFile:A}))}m.sort((A,_)=>_.ts.localeCompare(A.ts));let h=m.slice(0,t),P=h.length>0?h[h.length-1].ts:null,D=m.length>t;return{turns:h,oldestTs:P,hasMore:D,totalScanned:y}}recentByChatId(e){let t=Math.min(Math.max(e.limit??rt,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Bn(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(Fe(Ue(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<s||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!Wc(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Bn(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(Fe(Ue(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,y=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);c.push(`From ${m} (${u.channel}):
40
+ `),e.personLimits&&Oo(d,e.personLimits);try{let g=t?await ei(n,u,t,s,r,o,i):await Vo(n,u,s,r,i);if(!a)return g;let m=Do(d);return{...g,autonomy:a,...m.length?{autonomyBlocks:m}:{}}}finally{e.personLimits&&Lo(d)}}async function ni(n,e,t,s,r,o,i,a,c){if(Oc(e))return Lc(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let d=await Dc(n,e,r,o,i,a,s);if(d!==null)return d}return s?ei(n,e,s,r,o,i,a):Vo(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let d=await ko.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:Gt(n,e),args:zo(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Fn(Se(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...d,...d.error?Z(d.error):{}}}catch(d){if(!(d instanceof xe))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Cc(n,e,s,r,o,i):Ac(n,e,r,o);case"opencode":return Mc(n,e,s,r,o,i,a,c);case"sdk":{let d=n.provider||"claude",u=t[d]?.apiKey;return u?Rc(n,e,u,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=n.provider||"claude-code",u=t[d],l=u?.apiKey;return _c(n,e,l,r,s,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Fe,writeFileSync as si,mkdirSync as Nc,existsSync as Jt,readdirSync as Bn}from"fs";import{resolve as Ue}from"path";var Wn=12e3,rt=30,Fc=720,Uc=40,Hc=18e4,jc="[Compacted conversation summary",Bc=7*864e5,Wc=[/\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 qc(n){return n?Wc.some(e=>e.test(n)):!1}var Gc=[{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 oi(n){if(!n)return null;let e=0;for(let t of Gc)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function ri(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function ii(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function ai(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function Kc(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var zt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ue(e,".agentx/sessions"),Jt(this.sessionsDir)||Nc(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Fc),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Uc),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Hc),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let u=await c.seedHistory(s,{maxMessages:rt,maxChars:Wn});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.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,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ue(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(Jt(o))try{let d=JSON.parse(Fe(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!Jt(i))return null;try{return JSON.parse(Fe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);ri(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,s,r){let o=this.getSession(e,t,s),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,s,r){let o=this.getSession(e,t,s);ri(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,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}continueFrom(e,t,s){if(t.channel===s.channel&&t.chatId===s.chatId)return!1;let r=this.sessionKey(e,t.channel,t.chatId);if(!(this.cache.has(r)||Jt(this.sessionFile(r))||this.loadPreviousDaySession(e,t.channel,t.chatId)!==null))return!1;let i=this.getSession(e,t.channel,t.chatId);if(!i.claudeSessionId&&!i.codexSessionId&&!i.opencodeSessionId)return!1;let a=this.getSession(e,s.channel,s.chatId);return a.claudeSessionId=i.claudeSessionId,a.codexSessionId=i.codexSessionId,a.opencodeSessionId=i.opencodeSessionId,a.turnCount=i.turnCount,a.lastTurnInputTokens=i.lastTurnInputTokens,a.lastTurnContextTokens=i.lastTurnContextTokens,a.updatedAt=i.updatedAt,this.save(a),!0}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??rt),a=Math.max(200,r.maxChars??Wn),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let m=Kc(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let y=g.name||(g.role==="user"?"User":"Agent");u.push(`${y}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
+ `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.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():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Bn(this.sessionsDir).filter(A=>A.startsWith(`${a}:`)&&A.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(A=>{let _=A.match(l);if(!_)return!1;let M=_[1];return M>=d&&M<=u}),m=[],y=0,b=e.query?.toLowerCase(),C=e.participants?.length?new Set(e.participants):void 0;for(let A of g){let _;try{_=JSON.parse(Fe(Ue(this.sessionsDir,A),"utf-8"))}catch{continue}if(_.agentId===e.agentId&&!(e.channel&&_.channel!==e.channel)&&!(e.chatId&&_.chatId!==e.chatId))for(let M of _.messages)y++,!(!M.timestamp||M.timestamp<o||M.timestamp>=i)&&(C&&M.role==="user"&&!C.has(M.name??"")||b&&!M.content.toLowerCase().includes(b)||m.push({ts:M.timestamp,role:M.role,senderName:M.name??"",content:M.content,channel:_.channel,chatId:_.chatId,day:_.day,sessionFile:A}))}m.sort((A,_)=>_.ts.localeCompare(A.ts));let h=m.slice(0,t),P=h.length>0?h[h.length-1].ts:null,D=m.length>t;return{turns:h,oldestTs:P,hasMore:D,totalScanned:y}}recentByChatId(e){let t=Math.min(Math.max(e.limit??rt,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Bn(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(Fe(Ue(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<s||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!qc(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Bn(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(Fe(Ue(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,y=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);c.push(`From ${m} (${u.channel}):
42
42
  ${y.join(`
43
43
  `)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
44
- `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-26OHHULF.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:s});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(Hc)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);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,s){let r=this.getSession(e,t,s);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,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);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 Ue(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Fe(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},ni(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>jc?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>rt&&(e.messages=e.messages.slice(-rt));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>Wn&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ae.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);ni(t,JSON.stringify(e,null,2))}catch{}}};var Qt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,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(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};var Kc={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},ai=4;function li(n,e=Kc){let t=zc(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*ai;for(let i of t){if(!i.content)continue;let a=i.maxTokens*ai,c=di(i.content,a,i.keep);if(r+c.length>o){let d=o-r;d>100&&s.push(di(c,d,i.keep));break}s.push(c),r+=c.length}return s.join(`
44
+ `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-26OHHULF.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:s});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(jc)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);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,s){let r=this.getSession(e,t,s);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,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);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 Ue(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Fe(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},si(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>Bc?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>rt&&(e.messages=e.messages.slice(-rt));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>Wn&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ae.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);si(t,JSON.stringify(e,null,2))}catch{}}};var Qt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,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(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};var Jc={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},di=4;function gi(n,e=Jc){let t=Qc(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*di;for(let i of t){if(!i.content)continue;let a=i.maxTokens*di,c=ci(i.content,a,i.keep);if(r+c.length>o){let d=o-r;d>100&&s.push(ci(c,d,i.keep));break}s.push(c),r+=c.length}return s.join(`
45
45
 
46
- `)}function di(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
46
+ `)}function ci(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
47
47
  `,r=n.indexOf(`
48
- `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=ui(n,i);if(!ci.test(a.slice(0,a.indexOf(`
49
- `)+1||void 0))){let c=u=>n.slice(0,n.length-u.length).match(Jc)?.pop(),d=c(a);if(d&&d.length+1<i/2){a=ui(n,i-d.length-1);let u=ci.test(a.slice(0,a.indexOf(`
48
+ `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=li(n,i);if(!ui.test(a.slice(0,a.indexOf(`
49
+ `)+1||void 0))){let c=u=>n.slice(0,n.length-u.length).match(zc)?.pop(),d=c(a);if(d&&d.length+1<i/2){a=li(n,i-d.length-1);let u=ui.test(a.slice(0,a.indexOf(`
50
50
  `)+1||void 0))?"":c(a);u&&(a=u+`
51
- `+a)}}return o+s+a}var ci=/^— \d\d:\d\d —(\n|$)/,Jc=/^— \d\d:\d\d —$/gm;function ui(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
52
- `);return s>=0&&s<e/2?t.slice(s+1):t}function zc(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(Qc(n,t("channel",200))),s.push(Xc(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
51
+ `+a)}}return o+s+a}var ui=/^— \d\d:\d\d —(\n|$)/,zc=/^— \d\d:\d\d —$/gm;function li(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
52
+ `);return s>=0&&s<e/2?t.slice(s+1):t}function Qc(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(Xc(n,t("channel",200))),s.push(Yc(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
53
53
  `)[0],tags:["identity",n.agentId]}),n.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:n.bootstrapContext,tags:["bootstrap","identity","personality"]}),n.references&&s.push({name:"references",priority:4.7,maxTokens:t("references",500),content:n.references,tags:["references","verified","deterministic"]}),n.intent&&n.intent.path.length>0){let i=[`[Intent path: ${n.intent.pathLabel}${n.intent.status==="pending"?" (pending approval)":""}]`],a=n.intent.path[n.intent.path.length-1],c=n.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,l])=>` ${u}: ${l}`).join(`
54
54
  `);i.push(d)}n.intent.leaf?.input&&i.push(` input: ${n.intent.leaf.input}`),s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
55
- `),tags:["intent",...n.intent.path]})}else{let i=Yc(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
55
+ `),tags:["intent",...n.intent.path]})}else{let i=Zc(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
56
56
  `),tags:["artifacts",...n.mediaType?["media"]:[]]}),n.skillInjection&&s.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:n.skillInjection,tags:["skills","auto-inject"]}),n.patternContext&&s.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:n.patternContext,tags:["patterns","behavioral","self-improving"]}),n.procedureContext&&s.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:n.procedureContext,tags:["procedures","sop"]}),n.workflowRunContext&&s.push({name:"workflow-run",priority:6.55,maxTokens:t("workflow-run",200),content:n.workflowRunContext,tags:["workflow","plan"]}),n.memoryContext&&s.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:n.memoryContext,tags:["memory","persistent"]});let o=n.groupHistory||n.sessionHistory;if(o&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"],keep:"tail"}),n.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:n.crossChatContext,tags:["history","cross-chat"]}),n.contextOnDemand&&s.push({name:"on-demand",priority:7,maxTokens:t("on-demand",150),content:n.contextOnDemand,tags:["history","on-demand","lean"]}),n.longMemoryRecall&&s.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:n.longMemoryRecall,tags:["history","long-memory"]}),n.handoverNote){let i=[`[Handover] You are taking over this conversation from ${n.handoverNote.fromAgent}.`];n.handoverNote.summary&&i.push(`Operator summary: ${n.handoverNote.summary}`),i.push(`Handover time: ${n.handoverNote.at}`),s.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
57
57
  `),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.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:]`,n.rotationMemo.memo].join(`
58
- `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function Qc(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(n.channel==="a2a"?`Chat ID: ${n.chatId} (use this verbatim in /recall; /send with channel "a2a" messages the other agent in this chat)`:`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.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: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
59
- `),tags:r,rules:s}}function Xc(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.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(`
60
- `),tags:s}}function Yc(n){let e=[],t=n.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 Zc="resumeDelivery";function Ef(n){if(!n||n.kind!=="direct"||!n.context||n.context[Zc]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var Vc=32e3;function gi(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Vc?e:null}catch{return null}}function Df(n){if(!n)return null;try{let e=JSON.parse(n);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}var Gn={enabled:!0,maxContinuations:1};function Lf(n){return n?.enabled?n.maxContinuations:0}var eu=2*6e4,tu=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function nu(n,e){if(!n||e!=="timeout")return null;let t=n.match(tu);return t?Number(t[2]):null}function pi(n){let e=nu(n.error,n.errorKind);if(e===null||n.viaMesh)return{action:"none"};let t=n.settings;if(!t.enabled)return{action:"report",minutes:e,reason:"continuing after the time limit is turned off"};if(n.continuation>=t.maxContinuations)return{action:"report",minutes:e,reason:t.maxContinuations===0?"continuing after the time limit is turned off":`already continued ${n.continuation===1?"once":`${n.continuation} times`}`};if((n.channel??"").toLowerCase().split("@")[0]==="cron")return{action:"report",minutes:e,reason:"scheduled job: the next scheduled run covers it"};if(n.workflowRunId||(n.chatId??"").startsWith("workflow:"))return{action:"report",minutes:e,reason:"workflow step: the workflow engine owns retries"};if(n.callerGone)return{action:"report",minutes:e,reason:"nobody is waiting for the answer any more"};let r;if(n.timeoutMinutes&&n.timeoutMinutes>0){let o=n.timeoutMinutes*6e4-n.elapsedMs;if(o<eu)return{action:"report",minutes:e,reason:"the caller's own time limit leaves no time to continue"};r=o/6e4}return{action:"continue",minutes:e,continuation:n.continuation+1,...r?{timeoutMinutes:r}:{}}}function fi(n,e){return`${n} It was not continued (${e}).`}var qn=15,su=160;function mi(n,e,t){let s=[`[Continued after the time limit] You worked on this request for ${n} min, your time limit, and were stopped before you finished.`];return e.length===0?s.push("No tool calls were recorded for that run."):(s.push(`You had already made these tool calls (${e.length}):`),e.slice(0,qn).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,su);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>qn&&s.push(`\u2026and ${e.length-qn} more.`),s.push("Before repeating anything that changes the outside world \u2014 posting a comment or message, pushing, merging, deploying, sending \u2014 check whether it already happened.")),s.push(t?"This is your last run for it. Finish the request if you can; if you can't, say what is done, what is left and what is blocking it. Don't start long work you can't finish.":"Carry on from where you stopped and finish the request below.",""),s.join(`
61
- `)}function hi(n){return new Date(n).toISOString().slice(11,16)}function yi(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${hi(n)} UTC, running at ${hi(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,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);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,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
62
- `),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(c=>c.queuedAt??c.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,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);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}))}};var ru=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,ou=String.raw`(?=[\w.-]*[A-Za-z])(?![\w-]*\.(?:ts|js|mjs|cjs|tsx|jsx|md|py|go|rs|json|ya?ml|txt|sh|html|css)\b)[\w.-]+`,wi=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,bi=new RegExp(String.raw`(?<![\w/.-])((?:${ru}\/)+${ou})([#!])(\d+)\b`,"g");function Yt(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(wi.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${bi.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function iu(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(wi)){let s=Yt(t[0]);s&&e.add(s)}for(let t of n.matchAll(bi))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function Uf(n){let e=n.context&&typeof n.context=="object"?n.context:null;return Yt(n.home)??Yt(e?.home)}var au="[agentx:same-home]";function xi(n,e,t){if(!e.length)return null;for(let s of n){if(s.channel===t.channel&&s.chatId===t.chatId)continue;let r=s.homes?.find(i=>e.includes(i));if(!r)continue;let o=s.startedAt.toISOString().slice(11,16);return`${au} Another run of yours is already working on ${r} (started ${o}Z, chat ${s.channel}:${s.chatId??"?"}). Coordinate with it or stop: do not redo or overwrite its work. Keep what is not committed in a branch, not in a shared folder.`}return null}function Si(n){let e=Yt(n.home),t=iu(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as du,writeFileSync as Ii,appendFileSync as cu,mkdirSync as uu,existsSync as Ti}from"fs";import{resolve as Kn}from"path";var ki=50,lu="claude-haiku-4-5-20251001",gu=`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.
58
+ `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function Xc(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(n.channel==="a2a"?`Chat ID: ${n.chatId} (use this verbatim in /recall; /send with channel "a2a" messages the other agent in this chat)`:`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.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: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
59
+ `),tags:r,rules:s}}function Yc(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.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(`
60
+ `),tags:s}}function Zc(n){let e=[],t=n.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 Vc="resumeDelivery";function Df(n){if(!n||n.kind!=="direct"||!n.context||n.context[Vc]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var eu=32e3;function pi(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=eu?e:null}catch{return null}}function Of(n){if(!n)return null;try{let e=JSON.parse(n);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}var Gn={enabled:!0,maxContinuations:1};function Nf(n){return n?.enabled?n.maxContinuations:0}var tu=2*6e4,nu=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function su(n,e){if(!n||e!=="timeout")return null;let t=n.match(nu);return t?Number(t[2]):null}function fi(n){let e=su(n.error,n.errorKind);if(e===null||n.viaMesh)return{action:"none"};let t=n.settings;if(!t.enabled)return{action:"report",minutes:e,reason:"continuing after the time limit is turned off"};if(n.continuation>=t.maxContinuations)return{action:"report",minutes:e,reason:t.maxContinuations===0?"continuing after the time limit is turned off":`already continued ${n.continuation===1?"once":`${n.continuation} times`}`};if((n.channel??"").toLowerCase().split("@")[0]==="cron")return{action:"report",minutes:e,reason:"scheduled job: the next scheduled run covers it"};if(n.workflowRunId||(n.chatId??"").startsWith("workflow:"))return{action:"report",minutes:e,reason:"workflow step: the workflow engine owns retries"};if(n.callerGone)return{action:"report",minutes:e,reason:"nobody is waiting for the answer any more"};let r;if(n.timeoutMinutes&&n.timeoutMinutes>0){let o=n.timeoutMinutes*6e4-n.elapsedMs;if(o<tu)return{action:"report",minutes:e,reason:"the caller's own time limit leaves no time to continue"};r=o/6e4}return{action:"continue",minutes:e,continuation:n.continuation+1,...r?{timeoutMinutes:r}:{}}}function mi(n,e){return`${n} It was not continued (${e}).`}var qn=15,ru=160;function hi(n,e,t){let s=[`[Continued after the time limit] You worked on this request for ${n} min, your time limit, and were stopped before you finished.`];return e.length===0?s.push("No tool calls were recorded for that run."):(s.push(`You had already made these tool calls (${e.length}):`),e.slice(0,qn).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,ru);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>qn&&s.push(`\u2026and ${e.length-qn} more.`),s.push("Before repeating anything that changes the outside world \u2014 posting a comment or message, pushing, merging, deploying, sending \u2014 check whether it already happened.")),s.push(t?"This is your last run for it. Finish the request if you can; if you can't, say what is done, what is left and what is blocking it. Don't start long work you can't finish.":"Carry on from where you stopped and finish the request below.",""),s.join(`
61
+ `)}function yi(n){return new Date(n).toISOString().slice(11,16)}function wi(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${yi(n)} UTC, running at ${yi(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,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);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,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
62
+ `),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(c=>c.queuedAt??c.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,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);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}))}};var ou=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,iu=String.raw`(?=[\w.-]*[A-Za-z])(?![\w-]*\.(?:ts|js|mjs|cjs|tsx|jsx|md|py|go|rs|json|ya?ml|txt|sh|html|css)\b)[\w.-]+`,bi=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,xi=new RegExp(String.raw`(?<![\w/.-])((?:${ou}\/)+${iu})([#!])(\d+)\b`,"g");function Yt(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(bi.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${xi.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function au(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(bi)){let s=Yt(t[0]);s&&e.add(s)}for(let t of n.matchAll(xi))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function Hf(n){let e=n.context&&typeof n.context=="object"?n.context:null;return Yt(n.home)??Yt(e?.home)}var du="[agentx:same-home]";function Si(n,e,t){if(!e.length)return null;for(let s of n){if(s.channel===t.channel&&s.chatId===t.chatId)continue;let r=s.homes?.find(i=>e.includes(i));if(!r)continue;let o=s.startedAt.toISOString().slice(11,16);return`${du} Another run of yours is already working on ${r} (started ${o}Z, chat ${s.channel}:${s.chatId??"?"}). Coordinate with it or stop: do not redo or overwrite its work. Keep what is not committed in a branch, not in a shared folder.`}return null}function Ii(n){let e=Yt(n.home),t=au(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as cu,writeFileSync as Ti,appendFileSync as uu,mkdirSync as lu,existsSync as ki}from"fs";import{resolve as Kn}from"path";var vi=50,gu="claude-haiku-4-5-20251001",pu=`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.
63
63
 
64
64
  Extract patterns like:
65
65
  - "When asked about X, the approach that works is Y"
@@ -75,22 +75,22 @@ SKIP:
75
75
  Output a JSON array:
76
76
  [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
77
77
 
78
- If nothing worth extracting, output: []`,Zt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Kn(e,".agentx/patterns"),Ti(this.patternsDir)||uu(this.patternsDir,{recursive:!0})}filePath(e){return Kn(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Ti(t))return[];try{return du(t,"utf-8").split(`
79
- `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};cu(this.filePath(e),JSON.stringify(s)+`
78
+ If nothing worth extracting, output: []`,Zt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Kn(e,".agentx/patterns"),ki(this.patternsDir)||lu(this.patternsDir,{recursive:!0})}filePath(e){return Kn(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ki(t))return[];try{return cu(t,"utf-8").split(`
79
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};uu(this.filePath(e),JSON.stringify(s)+`
80
80
  `)}findRelevant(e,t,s=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(u=>`${u.context} ${u.pattern}`),i=Kn(this.patternsDir,`${t}_bm25_cache.json`),a=Ys(o,i),d=Xs(e,a).slice(0,s).map(u=>r[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
81
- `)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Ii(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
81
+ `)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Ti(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
82
82
  `)+`
83
- `)}prune(e){let t=this.getAll(e);t.length<=ki||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,ki),Ii(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
83
+ `)}prune(e){let t=this.getAll(e);t.length<=vi||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,vi),Ti(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
84
84
  `)+`
85
- `))}};async function vi(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-F5GDJSYD.js"),c=(await o("claude").generate([{role:"system",content:gu},{role:"user",content:`User: ${e.slice(0,500)}
85
+ `))}};async function $i(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-F5GDJSYD.js"),c=(await o("claude").generate([{role:"system",content:pu},{role:"user",content:`User: ${e.slice(0,500)}
86
86
 
87
- Agent: ${t.slice(0,1e3)}`}],{model:lu,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as pu}from"events";var fu=2e4,zn=class{inner=new pu;envelopeListeners=new Set;ring=new Or;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 s=this.inner.emit(e,t);try{this.publish(mu(e,t))}catch{}return s}publish(e){let t=Rt(),s=e.id??Dr(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Cn(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>fu&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Cn(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}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 mu(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"forge:commented":return{...s,kind:"message",ref:t.commentId,summary:`comment ${t.commentId} on ${t.channel} ${t.chatId}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var Jn;function V(){return Jn||(Jn=new zn),Jn}bn();bn();var $i=["manual","notify","auto"];function hu(n){return typeof n=="string"&&$i.includes(n)}var Qn={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var yu=7*24*60*6e4,ot=class{constructor(e={},t){this.store=t;this.opts={...Qn,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-yu;for(let[o,i]of Object.entries(s))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 s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,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:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):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,s){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),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:Ee(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:wu(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,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=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",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=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",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.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 s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);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 s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;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 wu(n,e){return n.length<=e?n:`${n.slice(0,e)}
88
- \u2026[truncated ${n.length-e} chars]`}Wd();import{z as bu}from"zod";var Ci=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function xu(n){if(n==null)return{ok:!0,subscriptions:Ci};let e=bu.array(ar).min(1).safeParse(n);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 Su=15,Iu=1500,Ai=200;function Mi(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Tu(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function tm(n,e,t={}){let s=Tu(e,n.cursor),r=s.length?Mi(s):n.cursor,o=s.filter(d=>n.subscriptions.some(u=>Lr(u,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:c}=ku(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function ku(n,e,t={}){let s=Math.max(3,t.maxLines??Su),r=Math.max(200,t.maxChars??Iu),o=n.map(a=>vu(`- ${Fr(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let c=i-a,u=[c?`[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)];c&&u.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let l=u.join(`
89
- `);if(u.length<=s&&l.length<=r)return{text:l,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function vu(n){return n.length<=Ai?n:`${n.slice(0,Ai-1)}\u2026`}import{existsSync as $u,mkdirSync as Au,readFileSync as Cu,renameSync as Mu,writeFileSync as Ru}from"node:fs";import{homedir as _u}from"node:os";import{dirname as Pu,join as Eu}from"node:path";function Du(n){return{load:()=>$u(n)?JSON.parse(Cu(n,"utf-8")):{},save:e=>{Au(Pu(n),{recursive:!0});let t=`${n}.tmp`;Ru(t,JSON.stringify(e,null,2),{mode:384}),Mu(t,n)}}}function Ou(){if(!process.env.VITEST)return Du(process.env.AGENTX_ATTACH_BINDINGS_FILE??Eu(_u(),".agentx","attach-bindings.json"))}var Xn;function Ri(){return Xn||(Xn=new ot({},Ou())),Xn}xn();import{readFileSync as Lu}from"fs";import{homedir as Nu}from"os";import{join as Fu}from"path";var it=null,Uu=6e4;function Hu(){try{let n=Fu(Nu(),".claude.json"),e=Lu(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function ju(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Bu(n=!1){let e=Date.now();return!n&&it&&e-it.checkedAt<Uu||(it=ju(Hu(),e)),it}function _i(n){let e=Bu();return e.available||n?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 Ei={warnRatio:.8},He={...Ei},Wu=5*60*60*1e3,qu=60*60*1e3,Me=[];function Di(n){He={...Ei,...n||{}}}function Oi(n){let e=n-Wu,t=0;for(;t<Me.length&&Me[t]<e;)t++;t>0&&Me.splice(0,t)}function Li(n=Date.now()){Oi(n),Me.push(n)}var je=new Map,Gu=15*60*1e3;function Ni(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function Ku(n){let e=Ni(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ju(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=Ku(s.resetsAt??s.resets_at),a=Ni(s.utilization),c=s.overageStatus??s.overage_status,d=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||c==="allowed"||c==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...d&&{usingOverage:d},seenAt:e}}function Fi(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Ui(n,e){let t=Fi(n);return!t||!e||e.toLowerCase().includes(t)}function Yn(n,e=Date.now(),t){let s=Ju(n,e);if(!s)return null;if(s.status!=="rejected")for(let[r,o]of je)o.status!=="rejected"||r===s.window||(!Fi(r)||t&&Ui(r,t))&&je.delete(r);return je.set(s.window,s),s}function Hi(n=Date.now()){return[...je.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:(e.resetsAt??e.seenAt+Gu)>n)}function zu(n=Date.now(),e){return Hi(n).find(t=>Ui(t.window,e))??null}function mm(n=Date.now()){let e=Hi(n);for(let t of e)je.delete(t.window);return e}function Qu(){return[...je.values()].sort((n,e)=>e.seenAt-n.seenAt)}function Pi(n){return typeof n=="number"&&n>0}function ji(n=Date.now()){Oi(n);let e=n-qu,t=0;for(let o=Me.length-1;o>=0&&Me[o]>=e;o--)t++;let s=Me.length,r={lastHour:t,last5h:s,maxPerHour:Pi(He.maxPerHour)?He.maxPerHour:void 0,maxPer5h:Pi(He.maxPer5h)?He.maxPer5h:void 0,provider:Qu()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function Bi(n){return n.replace(/_/g," ")}function Wi(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function qi(n,e=Date.now(),t){let s=ji(e);if(n)return null;let r=zu(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Bi(r.window)} window as rejected. Cold dispatches are held until it resets ${Wi(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.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:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.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:s}:null}function Gi(n=Date.now()){let e=ji(n),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 ${Bi(t.window)} window nearing its limit${r}, resets ${Wi(t.resetsAt,n)}`}let s=He.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&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>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}import{existsSync as Xu,mkdirSync as Yu,readFileSync as Zu,renameSync as Vu,writeFileSync as el}from"fs";import{dirname as tl}from"path";var Zn=200,Vt=class{constructor(e=Zn,t,s=()=>{}){this.max=e;this.file=t;this.log=s;t&&this.load(t)}held=new Map;hold(e,t){let s=this.held.get(e)??[];if(s.length>=this.max)return"full";let r=s.some(o=>o.channel===t.channel&&o.chatId===t.chatId);return s.push(t),this.held.set(e,s),this.save(),r?"held":"held-first"}count(e){return this.held.get(e)?.length??0}agents(){return[...this.held.keys()]}take(e,t=()=>!0){let s=this.held.get(e)??[],r=s.filter(t);if(!r.length)return[];let o=s.filter(i=>!r.includes(i));return o.length?this.held.set(e,o):this.held.delete(e),this.save(),r}get size(){let e=0;for(let t of this.held.values())e+=t.length;return e}load(e){if(Xu(e))try{let t=JSON.parse(Zu(e,"utf-8"));for(let[s,r]of Object.entries(t??{})){let o=(Array.isArray(r)?r:[]).filter(i=>i&&typeof i.text=="string"&&typeof i.channel=="string"&&typeof i.chatId=="string").slice(0,this.max);o.length&&this.held.set(s,o)}}catch(t){this.log(`[budget] couldn't read held messages from ${e} (${t?.message??t}); starting empty`)}}save(){if(this.file)try{Yu(tl(this.file),{recursive:!0});let e=`${this.file}.tmp`;el(e,JSON.stringify(Object.fromEntries(this.held))),Vu(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var Vn=new Map;function Ki(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function Ji(n,e,t,s=Date.now()){let r=Vn.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},Vn.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function zi(n){let e=Vn.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as al,readFileSync as dl}from"fs";import{resolve as cl}from"path";import{existsSync as nl,readFileSync as sl,unlinkSync as rl,writeFileSync as ol}from"fs";import{resolve as Xi}from"path";var Qi="_agentxManaged";function en(n=process){let e=n.argv[1]?Xi(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function Tm(n,e){return!e||n.agentx?n:{...n,agentx:e}}function km(n,e){let t=Xi(n,".mcp.json"),s=nl(t),r=s?il(t):null,o=r!==null&&r[Qi]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return rl(t),"removed";let a={[Qi]:!0,mcpServers:e};return ol(t,JSON.stringify(a,null,2)+`
90
- `),s?"updated":"installed"}function il(n){try{return JSON.parse(sl(n,"utf-8"))}catch{return null}}var ul=["github","a2a","workflow","cron"],ll=["claude-code","codex-cli"],gl={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},pl="AGENTX_MCP_TOOLS",fl=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint"],ml=["agentx_agents","agentx_recent","agentx_wiki_query"];function Zi(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function Vi(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...fl,...n.contextOnDemand?ml:[],...s];return Array.from(new Set(r))}function hl(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[pl]:e.join(",")}}}function ea(n,e,t){if(!ll.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(ul.includes(e)?"lean":"full")}function ta(n){return{...gl,...n?.lean??{}}}function na(n){return n.settingSources.includes("project")}function yl(n,e,t=en(),s){let r=sa(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=hl(o.agentx??r.agentx??t,Vi(e,s)),o}function sa(n){let e=cl(n,".mcp.json");if(!al(e))return{};try{let s=JSON.parse(dl(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function ra(n,e,t=en(),s){let r=yl(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Zi(e,s);return i.length&&o.push("--tools",ia(i).join(",")),o}function oa(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Yi="ToolSearch";function ia(n){return n.includes(Yi)?n:[...n,Yi]}function aa(n,e=en()){let t=sa(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function da(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), and stored knowledge (agentx_wiki_query).`].join(`
91
- `)}function ca(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=Zi(e,t);r.length&&s.push(`tools=${ia(r).join("+")}`);let o=Vi(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ce,mkdirSync as ep,readdirSync as me,readFileSync as lt,rmSync as tp,writeFileSync as np}from"fs";import{resolve as K}from"path";import{randomUUID as sp}from"crypto";import{existsSync as _e,mkdirSync as es,readFileSync as wl,readdirSync as bl,renameSync as xl,unlinkSync as Sl,writeFileSync as tn}from"fs";import{resolve as Ie,relative as nn}from"path";import{z as Y}from"zod";var Re=Y.object({id:Y.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:Y.string().min(1),trigger:Y.string().min(1,"procedures must describe when they apply"),inputs:Y.array(Y.string()).default([]),expected:Y.string().optional(),kpis:Y.array(Y.string()).default([]),owner:Y.string().optional(),tags:Y.array(Y.string()).default([]),status:Y.enum(["draft","active","deprecated"]).default("active"),source:Y.string().optional(),evidence:Y.array(Y.string()).default([]),created:Y.string().optional(),updated:Y.string().optional(),related:Y.array(Y.string()).default([])});function Il(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
87
+ Agent: ${t.slice(0,1e3)}`}],{model:gu,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as fu}from"events";var mu=2e4,zn=class{inner=new fu;envelopeListeners=new Set;ring=new Or;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 s=this.inner.emit(e,t);try{this.publish(hu(e,t))}catch{}return s}publish(e){let t=Rt(),s=e.id??Dr(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Cn(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>mu&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Cn(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}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 hu(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"forge:commented":return{...s,kind:"message",ref:t.commentId,summary:`comment ${t.commentId} on ${t.channel} ${t.chatId}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var Jn;function V(){return Jn||(Jn=new zn),Jn}bn();bn();var Ai=["manual","notify","auto"];function yu(n){return typeof n=="string"&&Ai.includes(n)}var Qn={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var wu=7*24*60*6e4,ot=class{constructor(e={},t){this.store=t;this.opts={...Qn,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-wu;for(let[o,i]of Object.entries(s))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 s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,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:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):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,s){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),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:Ee(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:bu(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,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=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",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=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",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.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 s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);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 s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;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 bu(n,e){return n.length<=e?n:`${n.slice(0,e)}
88
+ \u2026[truncated ${n.length-e} chars]`}qd();import{z as xu}from"zod";var Mi=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Su(n){if(n==null)return{ok:!0,subscriptions:Mi};let e=xu.array(ar).min(1).safeParse(n);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 Iu=15,Tu=1500,Ci=200;function Ri(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function ku(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function nm(n,e,t={}){let s=ku(e,n.cursor),r=s.length?Ri(s):n.cursor,o=s.filter(d=>n.subscriptions.some(u=>Lr(u,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:c}=vu(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function vu(n,e,t={}){let s=Math.max(3,t.maxLines??Iu),r=Math.max(200,t.maxChars??Tu),o=n.map(a=>$u(`- ${Fr(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let c=i-a,u=[c?`[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)];c&&u.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let l=u.join(`
89
+ `);if(u.length<=s&&l.length<=r)return{text:l,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function $u(n){return n.length<=Ci?n:`${n.slice(0,Ci-1)}\u2026`}import{existsSync as Au,mkdirSync as Cu,readFileSync as Mu,renameSync as Ru,writeFileSync as _u}from"node:fs";import{homedir as Pu}from"node:os";import{dirname as Eu,join as Du}from"node:path";function Ou(n){return{load:()=>Au(n)?JSON.parse(Mu(n,"utf-8")):{},save:e=>{Cu(Eu(n),{recursive:!0});let t=`${n}.tmp`;_u(t,JSON.stringify(e,null,2),{mode:384}),Ru(t,n)}}}function Lu(){if(!process.env.VITEST)return Ou(process.env.AGENTX_ATTACH_BINDINGS_FILE??Du(Pu(),".agentx","attach-bindings.json"))}var Xn;function _i(){return Xn||(Xn=new ot({},Lu())),Xn}xn();import{readFileSync as Nu}from"fs";import{homedir as Fu}from"os";import{join as Uu}from"path";var it=null,Hu=6e4;function ju(){try{let n=Uu(Fu(),".claude.json"),e=Nu(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function Bu(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Wu(n=!1){let e=Date.now();return!n&&it&&e-it.checkedAt<Hu||(it=Bu(ju(),e)),it}function Pi(n){let e=Wu();return e.available||n?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 Di={warnRatio:.8},He={...Di},qu=5*60*60*1e3,Gu=60*60*1e3,Me=[];function Oi(n){He={...Di,...n||{}}}function Li(n){let e=n-qu,t=0;for(;t<Me.length&&Me[t]<e;)t++;t>0&&Me.splice(0,t)}function Ni(n=Date.now()){Li(n),Me.push(n)}var je=new Map,Ku=15*60*1e3;function Fi(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function Ju(n){let e=Fi(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function zu(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=Ju(s.resetsAt??s.resets_at),a=Fi(s.utilization),c=s.overageStatus??s.overage_status,d=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||c==="allowed"||c==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...d&&{usingOverage:d},seenAt:e}}function Ui(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Hi(n,e){let t=Ui(n);return!t||!e||e.toLowerCase().includes(t)}function Yn(n,e=Date.now(),t){let s=zu(n,e);if(!s)return null;if(s.status!=="rejected")for(let[r,o]of je)o.status!=="rejected"||r===s.window||(!Ui(r)||t&&Hi(r,t))&&je.delete(r);return je.set(s.window,s),s}function ji(n=Date.now()){return[...je.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:(e.resetsAt??e.seenAt+Ku)>n)}function Qu(n=Date.now(),e){return ji(n).find(t=>Hi(t.window,e))??null}function hm(n=Date.now()){let e=ji(n);for(let t of e)je.delete(t.window);return e}function Xu(){return[...je.values()].sort((n,e)=>e.seenAt-n.seenAt)}function Ei(n){return typeof n=="number"&&n>0}function Bi(n=Date.now()){Li(n);let e=n-Gu,t=0;for(let o=Me.length-1;o>=0&&Me[o]>=e;o--)t++;let s=Me.length,r={lastHour:t,last5h:s,maxPerHour:Ei(He.maxPerHour)?He.maxPerHour:void 0,maxPer5h:Ei(He.maxPer5h)?He.maxPer5h:void 0,provider:Xu()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function Wi(n){return n.replace(/_/g," ")}function qi(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function Gi(n,e=Date.now(),t){let s=Bi(e);if(n)return null;let r=Qu(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Wi(r.window)} window as rejected. Cold dispatches are held until it resets ${qi(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.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:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.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:s}:null}function Ki(n=Date.now()){let e=Bi(n),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 ${Wi(t.window)} window nearing its limit${r}, resets ${qi(t.resetsAt,n)}`}let s=He.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&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>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}import{existsSync as Yu,mkdirSync as Zu,readFileSync as Vu,renameSync as el,writeFileSync as tl}from"fs";import{dirname as nl}from"path";var Zn=200,Vt=class{constructor(e=Zn,t,s=()=>{}){this.max=e;this.file=t;this.log=s;t&&this.load(t)}held=new Map;hold(e,t){let s=this.held.get(e)??[];if(s.length>=this.max)return"full";let r=s.some(o=>o.channel===t.channel&&o.chatId===t.chatId);return s.push(t),this.held.set(e,s),this.save(),r?"held":"held-first"}count(e){return this.held.get(e)?.length??0}agents(){return[...this.held.keys()]}take(e,t=()=>!0){let s=this.held.get(e)??[],r=s.filter(t);if(!r.length)return[];let o=s.filter(i=>!r.includes(i));return o.length?this.held.set(e,o):this.held.delete(e),this.save(),r}get size(){let e=0;for(let t of this.held.values())e+=t.length;return e}load(e){if(Yu(e))try{let t=JSON.parse(Vu(e,"utf-8"));for(let[s,r]of Object.entries(t??{})){let o=(Array.isArray(r)?r:[]).filter(i=>i&&typeof i.text=="string"&&typeof i.channel=="string"&&typeof i.chatId=="string").slice(0,this.max);o.length&&this.held.set(s,o)}}catch(t){this.log(`[budget] couldn't read held messages from ${e} (${t?.message??t}); starting empty`)}}save(){if(this.file)try{Zu(nl(this.file),{recursive:!0});let e=`${this.file}.tmp`;tl(e,JSON.stringify(Object.fromEntries(this.held))),el(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var Vn=new Map;function Ji(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function zi(n,e,t,s=Date.now()){let r=Vn.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},Vn.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function Qi(n){let e=Vn.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as dl,readFileSync as cl}from"fs";import{resolve as ul}from"path";import{existsSync as sl,readFileSync as rl,unlinkSync as ol,writeFileSync as il}from"fs";import{resolve as Yi}from"path";var Xi="_agentxManaged";function en(n=process){let e=n.argv[1]?Yi(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function km(n,e){return!e||n.agentx?n:{...n,agentx:e}}function vm(n,e){let t=Yi(n,".mcp.json"),s=sl(t),r=s?al(t):null,o=r!==null&&r[Xi]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return ol(t),"removed";let a={[Xi]:!0,mcpServers:e};return il(t,JSON.stringify(a,null,2)+`
90
+ `),s?"updated":"installed"}function al(n){try{return JSON.parse(rl(n,"utf-8"))}catch{return null}}var ll=["github","a2a","workflow","cron"],gl=["claude-code","codex-cli"],pl={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},fl="AGENTX_MCP_TOOLS",ml=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint"],hl=["agentx_agents","agentx_recent","agentx_wiki_query"];function Vi(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function ea(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...ml,...n.contextOnDemand?hl:[],...s];return Array.from(new Set(r))}function yl(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[fl]:e.join(",")}}}function ta(n,e,t){if(!gl.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(ll.includes(e)?"lean":"full")}function na(n){return{...pl,...n?.lean??{}}}function sa(n){return n.settingSources.includes("project")}function wl(n,e,t=en(),s){let r=ra(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=yl(o.agentx??r.agentx??t,ea(e,s)),o}function ra(n){let e=ul(n,".mcp.json");if(!dl(e))return{};try{let s=JSON.parse(cl(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function oa(n,e,t=en(),s){let r=wl(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Vi(e,s);return i.length&&o.push("--tools",aa(i).join(",")),o}function ia(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Zi="ToolSearch";function aa(n){return n.includes(Zi)?n:[...n,Zi]}function da(n,e=en()){let t=ra(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function ca(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), and stored knowledge (agentx_wiki_query).`].join(`
91
+ `)}function ua(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=Vi(e,t);r.length&&s.push(`tools=${aa(r).join("+")}`);let o=ea(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ce,mkdirSync as tp,readdirSync as me,readFileSync as lt,rmSync as np,writeFileSync as sp}from"fs";import{resolve as K}from"path";import{randomUUID as rp}from"crypto";import{existsSync as _e,mkdirSync as es,readFileSync as bl,readdirSync as xl,renameSync as Sl,unlinkSync as Il,writeFileSync as tn}from"fs";import{resolve as Ie,relative as nn}from"path";import{z as Y}from"zod";var Re=Y.object({id:Y.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:Y.string().min(1),trigger:Y.string().min(1,"procedures must describe when they apply"),inputs:Y.array(Y.string()).default([]),expected:Y.string().optional(),kpis:Y.array(Y.string()).default([]),owner:Y.string().optional(),tags:Y.array(Y.string()).default([]),status:Y.enum(["draft","active","deprecated"]).default("active"),source:Y.string().optional(),evidence:Y.array(Y.string()).default([]),created:Y.string().optional(),updated:Y.string().optional(),related:Y.array(Y.string()).default([])});function Tl(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
92
92
  `)){let r=s.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 sn(n){let e=["---"];return e.push(`id: ${n.id}`),e.push(`title: "${n.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${n.trigger.replace(/"/g,'\\"')}"`),n.inputs?.length&&e.push(`inputs: ${JSON.stringify(n.inputs)}`),n.expected&&e.push(`expected: "${n.expected.replace(/"/g,'\\"')}"`),n.kpis?.length&&e.push(`kpis: ${JSON.stringify(n.kpis)}`),n.owner&&e.push(`owner: ${n.owner}`),n.tags?.length&&e.push(`tags: ${JSON.stringify(n.tags)}`),e.push(`status: ${n.status}`),n.source&&e.push(`source: "${n.source.replace(/"/g,'\\"')}"`),n.evidence?.length&&e.push(`evidence: ${JSON.stringify(n.evidence)}`),n.related?.length&&e.push(`related: ${JSON.stringify(n.related)}`),n.created&&e.push(`created: ${n.created}`),n.updated&&e.push(`updated: ${n.updated}`),e.push("---"),e.join(`
93
- `)}var at=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Ie(process.cwd(),".agentx/procedures"),es(this.baseDir,{recursive:!0})}pathFor(e){return Ie(this.baseDir,`${e}.md`)}get draftsDir(){return Ie(this.baseDir,"_drafts")}draftPathFor(e){return Ie(this.draftsDir,`${e}.md`)}parseFile(e){let t=wl(e,"utf-8"),{meta:s,body:r}=Il(t),o=Re.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:nn(this.baseDir,e)}:null}listDir(e){if(!_e(e))return[];let t=[];for(let s of bl(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Ie(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.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 _e(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return _e(t)?this.parseFile(t):null}add(e,t){let s=Re.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(_e(r))throw new Error(`Procedure already exists: ${s.id}`);return tn(r,sn(s)+`
93
+ `)}var at=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Ie(process.cwd(),".agentx/procedures"),es(this.baseDir,{recursive:!0})}pathFor(e){return Ie(this.baseDir,`${e}.md`)}get draftsDir(){return Ie(this.baseDir,"_drafts")}draftPathFor(e){return Ie(this.draftsDir,`${e}.md`)}parseFile(e){let t=bl(e,"utf-8"),{meta:s,body:r}=Tl(t),o=Re.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:nn(this.baseDir,e)}:null}listDir(e){if(!_e(e))return[];let t=[];for(let s of xl(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Ie(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.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 _e(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return _e(t)?this.parseFile(t):null}add(e,t){let s=Re.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(_e(r))throw new Error(`Procedure already exists: ${s.id}`);return tn(r,sn(s)+`
94
94
 
95
95
  `+t.trim()+`
96
96
  `),{meta:s,body:t.trim(),path:nn(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=Re.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return tn(this.pathFor(e),sn(o)+`
@@ -102,38 +102,38 @@ Agent: ${t.slice(0,1e3)}`}],{model:lu,maxTokens:512})).content.trim().match(/\[[
102
102
  `),{meta:s,body:t.trim(),path:nn(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 s=Re.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return tn(this.pathFor(e),sn(s)+`
103
103
 
104
104
  `+t.body+`
105
- `),Sl(this.draftPathFor(e)),{meta:s,body:t.body,path:nn(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!_e(t))throw new Error(`Draft not found: ${e}`);let s=Ie(this.draftsDir,"_rejected");es(s,{recursive:!0}),xl(t,Ie(s,`${e}.md`))}isRejected(e){return _e(Ie(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Tl,mkdirSync as kl,readFileSync as vl,writeFileSync as $l}from"fs";import{dirname as Al,resolve as Cl}from"path";import{z as oe}from"zod";var Ml=oe.object({key:oe.string(),count:oe.number().int().min(0).default(0),firstSeen:oe.string(),lastSeen:oe.string(),taskIds:oe.array(oe.string()).default([]),sampleMessage:oe.string().default(""),status:oe.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:oe.string().optional()}),Rl=oe.object({minedThrough:oe.string().optional(),candidates:oe.array(Ml).default([])});function ua(n){return Cl(n,"_candidates.json")}function _l(n){let e=ua(n);if(!Tl(e))return{candidates:[]};try{let t=Rl.safeParse(JSON.parse(vl(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Pl(n,e){let t=ua(n);kl(Al(t),{recursive:!0}),$l(t,JSON.stringify(e,null,2)+`
106
- `)}function El(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function Dl(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function Ol(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function ts(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function la(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function ns(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=ts(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=la(o,ts(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=la(o,ts(u));l>0&&c.push("title/tags");let g=Math.min(1,d*.7+l*.5);g>=r&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,s)}function ss(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
105
+ `),Il(this.draftPathFor(e)),{meta:s,body:t.body,path:nn(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!_e(t))throw new Error(`Draft not found: ${e}`);let s=Ie(this.draftsDir,"_rejected");es(s,{recursive:!0}),Sl(t,Ie(s,`${e}.md`))}isRejected(e){return _e(Ie(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as kl,mkdirSync as vl,readFileSync as $l,writeFileSync as Al}from"fs";import{dirname as Cl,resolve as Ml}from"path";import{z as oe}from"zod";var Rl=oe.object({key:oe.string(),count:oe.number().int().min(0).default(0),firstSeen:oe.string(),lastSeen:oe.string(),taskIds:oe.array(oe.string()).default([]),sampleMessage:oe.string().default(""),status:oe.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:oe.string().optional()}),_l=oe.object({minedThrough:oe.string().optional(),candidates:oe.array(Rl).default([])});function la(n){return Ml(n,"_candidates.json")}function Pl(n){let e=la(n);if(!kl(e))return{candidates:[]};try{let t=_l.safeParse(JSON.parse($l(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function El(n,e){let t=la(n);vl(Cl(t),{recursive:!0}),Al(t,JSON.stringify(e,null,2)+`
106
+ `)}function Dl(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function Ol(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function Ll(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function ts(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function ga(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function ns(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=ts(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=ga(o,ts(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=ga(o,ts(u));l>0&&c.push("title/tags");let g=Math.min(1,d*.7+l*.5);g>=r&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,s)}function ss(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
107
107
  `)})].join(`
108
108
 
109
- `)}kn();Ct();var os="turn-progress",ga={progress:De({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.")},rs=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function pa(n){return{agent:n.agent,request:rs(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:rs(e.input,300),...e.result!==void 0?{result:rs(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}Ct();var fa="turn-handoff",ma="approval-binding",ha={nextStep:De({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.")},ya={approves:Xe("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."})},Ll=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,wa=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,Nl=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function is(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Nl.test(e.split(`
110
- `).slice(-3).join(" ")):!1}var Fl=/^\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 ba(n){return n.trim().length<=160&&Fl.test(n)}function xa(n){return n.trim().length<=160}function Sa(n){return{agent:n.agent,channel:n.channel,request:Ll(n.request,1500),agentReplyEnding:wa(n.reply,1200)}}function Ia(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:wa(n.previousReply,1200)}}var Ul=5*6e4,Hl=3,jl=12,Bl=24*60*6e4,Ta=new Set(["cron","heartbeat","bench","a2a","business"]),Wl={observe(){},stop(){}};function ka(n){if(Mt(os)==="off")return Wl;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let g;for(let[m,y]of o)y>1&&(!g||y>g.times)&&(g={call:m,times:y});return g},u=g=>{if(c)return;c=!0,a=s.length;let m=pa({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-jl),repeated:d(),trigger:g});be(os,m,ga,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:g}}).finally(()=>{c=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??Ul);return l.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let y of m){if(y?.type!=="tool_use")continue;let b=y.input?JSON.stringify(y.input):"",C={tool:y.name||"tool",input:b};s.push(C),typeof y.id=="string"&&r.set(y.id,C);let h=`${C.tool}(${b})`,P=(o.get(h)??0)+1;o.set(h,P),P>=Hl&&!i.has(h)&&(i.add(h),u("repetition"))}else if(g?.type==="user")for(let y of m){if(y?.type!=="tool_result")continue;let b=r.get(y.tool_use_id);b&&(b.result=Array.isArray(y.content)?y.content.map(C=>typeof C?.text=="string"?C.text:"").join(""):typeof y.content=="string"?y.content:"",y.is_error&&(b.error=!0))}},stop(){clearInterval(l)}}}var as=new Map,va=(n,e,t)=>`${n}\0${e}\0${t}`;function $a(n){if(Ta.has(n.channel)||!is(n.reply))return;let e=va(n.agent,n.channel,n.chatId);be(fa,Sa(n),ha,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&as.set(e,{callId:t.callId,at:Date.now()})})}function Aa(n){if(Ta.has(n.channel))return;let e=va(n.agent,n.channel,n.chatId),t=as.get(e);if(t){as.delete(e);let s=dr().store;if(s&&Date.now()-t.at<Bl)try{s.label(t.callId,"userReply",ba(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!xa(n.message)||!is(n.previousReply)||be(ma,Ia({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),ya,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Ud();jd();Bd();function Ca(n){let e=n?.dueAt;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}}function rn(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function eh(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=rn(n);return!t||rn(e)?e:{...e??{},taskType:t}}ir();function Ma(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(Pe(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(c=>{a(),s(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function Pe(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Be=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function Ra(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Be(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as ql,spawn as Gl}from"child_process";import{existsSync as Kl,mkdirSync as Jl,readFileSync as zl,renameSync as Ql,writeFileSync as Xl}from"fs";import{dirname as Yl}from"path";var an={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function Zl(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function ds(n){try{return!n||!Kl(n)?void 0:ql("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function dt(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function _a(n){let e={...an,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=dt(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??ds,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let c=Zl(r(a));if(c&&c.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var Vl=24*60*60*1e3,eg=7*Vl,on=class{constructor(e){this.file=e}sessions=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(zl(this.file,"utf8")),t=Array.isArray(e?.sessions)?e.sessions:[];this.sessions=t.filter(s=>s&&typeof s.repo=="string"&&typeof s.sessionId=="string"&&Number.isFinite(s.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<eg);try{Jl(Yl(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Xl(t,JSON.stringify({sessions:this.sessions},null,2)),Ql(t,this.file)}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},tg=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
111
- `);function ng(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var sg=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function Pa(n){return n.replace(sg,"")}function rg(n){let e=Pa(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function Ea(n){let e=n.spawn??((c,d,u)=>Gl(c,d,u)),t=n.python??"python3",s=["-c",tg,"claude",...ng(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=c=>{o+=c.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>Pa(o).trim().split(`
109
+ `)}kn();Ct();var os="turn-progress",pa={progress:De({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.")},rs=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function fa(n){return{agent:n.agent,request:rs(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:rs(e.input,300),...e.result!==void 0?{result:rs(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}Ct();var ma="turn-handoff",ha="approval-binding",ya={nextStep:De({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.")},wa={approves:Xe("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."})},Nl=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,ba=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,Fl=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function is(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Fl.test(e.split(`
110
+ `).slice(-3).join(" ")):!1}var Ul=/^\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 xa(n){return n.trim().length<=160&&Ul.test(n)}function Sa(n){return n.trim().length<=160}function Ia(n){return{agent:n.agent,channel:n.channel,request:Nl(n.request,1500),agentReplyEnding:ba(n.reply,1200)}}function Ta(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:ba(n.previousReply,1200)}}var Hl=5*6e4,jl=3,Bl=12,Wl=24*60*6e4,ka=new Set(["cron","heartbeat","bench","a2a","business"]),ql={observe(){},stop(){}};function va(n){if(Mt(os)==="off")return ql;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let g;for(let[m,y]of o)y>1&&(!g||y>g.times)&&(g={call:m,times:y});return g},u=g=>{if(c)return;c=!0,a=s.length;let m=fa({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-Bl),repeated:d(),trigger:g});be(os,m,pa,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:g}}).finally(()=>{c=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??Hl);return l.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let y of m){if(y?.type!=="tool_use")continue;let b=y.input?JSON.stringify(y.input):"",C={tool:y.name||"tool",input:b};s.push(C),typeof y.id=="string"&&r.set(y.id,C);let h=`${C.tool}(${b})`,P=(o.get(h)??0)+1;o.set(h,P),P>=jl&&!i.has(h)&&(i.add(h),u("repetition"))}else if(g?.type==="user")for(let y of m){if(y?.type!=="tool_result")continue;let b=r.get(y.tool_use_id);b&&(b.result=Array.isArray(y.content)?y.content.map(C=>typeof C?.text=="string"?C.text:"").join(""):typeof y.content=="string"?y.content:"",y.is_error&&(b.error=!0))}},stop(){clearInterval(l)}}}var as=new Map,$a=(n,e,t)=>`${n}\0${e}\0${t}`;function Aa(n){if(ka.has(n.channel)||!is(n.reply))return;let e=$a(n.agent,n.channel,n.chatId);be(ma,Ia(n),ya,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&as.set(e,{callId:t.callId,at:Date.now()})})}function Ca(n){if(ka.has(n.channel))return;let e=$a(n.agent,n.channel,n.chatId),t=as.get(e);if(t){as.delete(e);let s=dr().store;if(s&&Date.now()-t.at<Wl)try{s.label(t.callId,"userReply",xa(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!Sa(n.message)||!is(n.previousReply)||be(ha,Ta({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),wa,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Hd();Bd();Wd();function Ma(n){let e=n?.dueAt;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}}function rn(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function th(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=rn(n);return!t||rn(e)?e:{...e??{},taskType:t}}ir();function Ra(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(Pe(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(c=>{a(),s(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function Pe(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Be=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function _a(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Be(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as Gl,spawn as Kl}from"child_process";import{existsSync as Jl,mkdirSync as zl,readFileSync as Ql,renameSync as Xl,writeFileSync as Yl}from"fs";import{dirname as Zl}from"path";var an={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function Vl(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function ds(n){try{return!n||!Jl(n)?void 0:Gl("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function dt(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function Pa(n){let e={...an,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=dt(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??ds,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let c=Vl(r(a));if(c&&c.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var eg=24*60*60*1e3,tg=7*eg,on=class{constructor(e){this.file=e}sessions=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(Ql(this.file,"utf8")),t=Array.isArray(e?.sessions)?e.sessions:[];this.sessions=t.filter(s=>s&&typeof s.repo=="string"&&typeof s.sessionId=="string"&&Number.isFinite(s.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<tg);try{zl(Zl(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Yl(t,JSON.stringify({sessions:this.sessions},null,2)),Xl(t,this.file)}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},ng=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
111
+ `);function sg(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var rg=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function Ea(n){return n.replace(rg,"")}function og(n){let e=Ea(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function Da(n){let e=n.spawn??((c,d,u)=>Kl(c,d,u)),t=n.python??"python3",s=["-c",ng,"claude",...sg(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=c=>{o+=c.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>Ea(o).trim().split(`
112
112
  `).slice(-5).join(`
113
- `).slice(-600);return new Promise(c=>{let d=!1,u=y=>{d||(d=!0,c(y))},l;try{l=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(y){u({ok:!1,reason:`could not start ${t}: ${y?.message||y}`,output:o});return}let g=y=>{try{l.pid&&process.kill(-l.pid,y)}catch{try{l.kill(y)}catch{}}},m=setTimeout(()=>{g("SIGTERM"),setTimeout(()=>g("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);m.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",y=>{clearTimeout(m);let b=y?.code==="ENOENT";u({ok:!1,reason:b?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${y?.message||y}`,output:o})}),l.on("close",y=>{if(clearTimeout(m),d)return;let b=rg(o);if(n.sessionId){if(y===0){u({ok:!0,sessionId:n.sessionId,url:b.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${y??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(b.sessionId&&b.url){u({ok:!0,sessionId:b.sessionId,url:b.url,output:o});return}if(y!==0){u({ok:!1,reason:`claude --cloud exited with code ${y??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var og=1e5;function ig(n,e){let s=`
113
+ `).slice(-600);return new Promise(c=>{let d=!1,u=y=>{d||(d=!0,c(y))},l;try{l=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(y){u({ok:!1,reason:`could not start ${t}: ${y?.message||y}`,output:o});return}let g=y=>{try{l.pid&&process.kill(-l.pid,y)}catch{try{l.kill(y)}catch{}}},m=setTimeout(()=>{g("SIGTERM"),setTimeout(()=>g("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);m.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",y=>{clearTimeout(m);let b=y?.code==="ENOENT";u({ok:!1,reason:b?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${y?.message||y}`,output:o})}),l.on("close",y=>{if(clearTimeout(m),d)return;let b=og(o);if(n.sessionId){if(y===0){u({ok:!0,sessionId:n.sessionId,url:b.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${y??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(b.sessionId&&b.url){u({ok:!0,sessionId:b.sessionId,url:b.url,output:o});return}if(y!==0){u({ok:!1,reason:`claude --cloud exited with code ${y??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var ig=1e5;function ag(n,e){let s=`
114
114
 
115
115
  ---
116
- This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.number} in ${e.repo}. Work in this repository and open or update a pull request that references #${e.number}.`,r=og-s.length;return`${n.length>r?`${n.slice(0,r)}
117
- [message cut at ${r} characters]`:n}${s}`}function ag(n,e,t){return[`Started a Claude cloud session for this ${e==="pull"?"pull request":"issue"}. The result arrives as a pull request.`,`Session: \`${n.sessionId}\``,n.url,`Comments here are forwarded to that session for the next ${t} hours.`].join(`
118
- `)}function dg(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function Da(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:dg(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=ig(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:ag(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as gg}from"child_process";import{existsSync as pg,mkdirSync as fg,mkdtempSync as mg,readFileSync as Ha,renameSync as hg,rmSync as yg,writeFileSync as wg}from"fs";import{homedir as bg,tmpdir as xg}from"os";import{dirname as Sg,join as us,resolve as ls,sep as Fa}from"path";var cg=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function ug(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
116
+ This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.number} in ${e.repo}. Work in this repository and open or update a pull request that references #${e.number}.`,r=ig-s.length;return`${n.length>r?`${n.slice(0,r)}
117
+ [message cut at ${r} characters]`:n}${s}`}function dg(n,e,t){return[`Started a Claude cloud session for this ${e==="pull"?"pull request":"issue"}. The result arrives as a pull request.`,`Session: \`${n.sessionId}\``,n.url,`Comments here are forwarded to that session for the next ${t} hours.`].join(`
118
+ `)}function cg(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function Oa(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:cg(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=ag(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:dg(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as pg}from"child_process";import{existsSync as fg,mkdirSync as mg,mkdtempSync as hg,readFileSync as ja,renameSync as yg,rmSync as wg,writeFileSync as bg}from"fs";import{homedir as xg,tmpdir as Sg}from"os";import{dirname as Ig,join as us,resolve as ls,sep as Ua}from"path";var ug=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function lg(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
119
119
  `).filter(e=>!/^[ \t]*>/.test(e)).join(`
120
- `)}function Oa(n,e){return ct(n)?n:`${n}
120
+ `)}function La(n,e){return ct(n)?n:`${n}
121
121
 
122
- <!-- agentx:${e} -->`}function ct(n){if(!n)return null;let e=ug(n).match(cg);return e?e[1]:null}var La="unknown";function ah(n,e){let t=ct(n);return t&&(!e||t===e)?t:null}function dh(n){return`> \u{1F916} **${n}** (via AgentX)
122
+ <!-- agentx:${e} -->`}function ct(n){if(!n)return null;let e=lg(n).match(ug);return e?e[1]:null}var Na="unknown";function dh(n,e){let t=ct(n);return t&&(!e||t===e)?t:null}function ch(n){return`> \u{1F916} **${n}** (via AgentX)
123
123
 
124
- `}function Na(n,e){if(!e||!n)return null;let t=ct(n);return t&&t!==La?t:null}function ch(n,e){return e&&ct(n)===La}function uh(n,e,t){let s=Na(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function lh(n,e,t){let s=Na(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function gh(n,e){return e||!n?n:lg(n)}function ph(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function lg(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return ct(n)?n.replace(/</g,"&lt;"):n}var ja={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Ba(n){return`spec-tests/issue-${n}`}function Wa(n){return`test: spec tests for #${n}`}function Ig(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var Tg=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function kg(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${Tg(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function vg(n){let e=n.split(/\r?\n/),t=r=>r.match(/^\s*[-*]\s+\[[ xX]\]\s+(.+?)\s*$/)?.[1],s=e.findIndex(r=>/^\s*#{1,6}\s*acceptance criteria\b/i.test(r));if(s>=0){let r=[];for(let o of e.slice(s+1)){if(/^\s*#{1,6}\s/.test(o))break;let i=t(o);i&&r.push(i)}if(r.length)return r}return e.map(t).filter(r=>!!r)}function $g(n){let e=new Set;for(let t of n.matchAll(/`([^`\n]{2,160})`/g)){let s=t[1].trim();/\s/.test(s)&&!/^[\w.$]+\s*[(<]/.test(s)||/[A-Za-z_]/.test(s)&&e.add(s)}return[...e]}function Ag(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:vg(e),interfaces:$g(`${n.title}
125
- ${e}`)}}var cs=2e4;function Cg(n){let e=n.body.length>cs?`${n.body.slice(0,cs)}
124
+ `}function Fa(n,e){if(!e||!n)return null;let t=ct(n);return t&&t!==Na?t:null}function uh(n,e){return e&&ct(n)===Na}function lh(n,e,t){let s=Fa(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function gh(n,e,t){let s=Fa(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function ph(n,e){return e||!n?n:gg(n)}function fh(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function gg(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return ct(n)?n.replace(/</g,"&lt;"):n}var Ba={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Wa(n){return`spec-tests/issue-${n}`}function qa(n){return`test: spec tests for #${n}`}function Tg(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var kg=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function vg(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${kg(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function $g(n){let e=n.split(/\r?\n/),t=r=>r.match(/^\s*[-*]\s+\[[ xX]\]\s+(.+?)\s*$/)?.[1],s=e.findIndex(r=>/^\s*#{1,6}\s*acceptance criteria\b/i.test(r));if(s>=0){let r=[];for(let o of e.slice(s+1)){if(/^\s*#{1,6}\s/.test(o))break;let i=t(o);i&&r.push(i)}if(r.length)return r}return e.map(t).filter(r=>!!r)}function Ag(n){let e=new Set;for(let t of n.matchAll(/`([^`\n]{2,160})`/g)){let s=t[1].trim();/\s/.test(s)&&!/^[\w.$]+\s*[(<]/.test(s)||/[A-Za-z_]/.test(s)&&e.add(s)}return[...e]}function Cg(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:$g(e),interfaces:Ag(`${n.title}
125
+ ${e}`)}}var cs=2e4;function Mg(n){let e=n.body.length>cs?`${n.body.slice(0,cs)}
126
126
  [issue cut at ${cs} characters]`:n.body,t=n.acceptanceCriteria.length?n.acceptanceCriteria.map((r,o)=>`${o+1}. ${r}`).join(`
127
127
  `):"(the issue has no checklist; take the requirements from its text)",s=n.interfaces.length?n.interfaces.map(r=>`- \`${r}\``).join(`
128
128
  `):"(none named)";return[`You are the spec-test agent for issue #${n.number} in ${n.repo}.`,"Another agent is writing the code for this issue at the same time. You do not see its code, and you must not guess at it. Write tests from the issue alone.","","## Your job","- Write one test file for this issue, following the repository's existing test conventions (framework, folder, naming). Read the existing tests and the public interfaces the issue names to get imports and signatures right.","- One test or more per acceptance criterion. Name each test after the criterion it checks, so a failure points at the criterion.","- Test behaviour through public interfaces. The code under test may not exist yet: that is expected, the tests may fail now.","- Only create or edit test files. Do not change any other file. Do not commit: the daemon commits your file.","- When a criterion cannot be tested from the issue text alone, write no test for it and say so in your final reply.","- End with a short reply: the file you wrote and one line per criterion (tested, or why not).","",`## Issue #${n.number}: ${n.title}`,e,"","## Acceptance criteria",t,"","## Interfaces the issue names",s].join(`
129
- `)}function qa(n,e){let t=Ba(n);return["","## Spec tests (#992)",`A separate test agent ("${e}") is writing tests for this issue from the issue text only, without seeing your code. It pushes them as one commit, "${Wa(n)}", to the branch \`${t}\`.`,"- Do not write those tests yourself. Do not edit or delete them, except as described below.",`- Before you open the pull request, and again before you finish, run \`git fetch origin ${t}\`. When the branch exists, merge it into your branch with \`git merge --no-ff origin/${t}\` (a merge, not a cherry-pick, squash or rebase, so the commit keeps its author), then run its tests.`,'- When a spec test fails, decide which it is. A code defect: fix the code. A test that misreads the acceptance criteria: change that test in a separate commit whose message starts with "test: spec misread" and quotes the criterion it misreads. Never skip or disable a spec test.','- In the pull request description, add a "Spec tests" section that lists each failure on the first run and your call (code defect or test misread), and ends with this line, filled in:'," <!-- agentx:spec-tests written=W failed-first-run=F code-defects=D test-misreads=M -->","- If the branch has not appeared by the time you finish, say so in that section."].join(`
130
- `)}var Mg=90*24*60*60*1e3,dn=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(Ha(this.file,"utf8")),t=Array.isArray(e?.runs)?e.runs:[];this.runs=t.filter(s=>s&&typeof s.repo=="string"&&Number.isInteger(s.number)&&Number.isFinite(s.startedAt))}catch{this.runs=[]}}}save(){let e=Date.now();this.runs=this.runs.filter(t=>e-t.startedAt<Mg);try{fg(Sg(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;wg(t,JSON.stringify({runs:this.runs},null,2)),hg(t,this.file)}catch{}}get(e,t){this.load();let s=e.toLowerCase();return this.runs.find(r=>r.repo.toLowerCase()===s&&r.number===t)}record(e){this.load(),this.runs=this.runs.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.runs.push(e),this.save()}all(){return this.load(),[...this.runs]}},Rg=10*6e4;function gs(n,e,t=Date.now()){if(n){if(n.status!=="running")return`spec tests already ran for this issue (${n.status})`;if(!(t-n.startedAt>e.maxMinutes*6e4+Rg))return"spec tests are already running for this issue"}}function Ga(n){let{settings:e,issue:t}=n;if(!e.enabled)return{run:!1,reason:"spec tests are off"};if(!t)return{run:!1,reason:"the issue text could not be read"};if(!kg(`${t.title}
131
- ${t.body}`,e.paths))return{run:!1,reason:`issue names none of the pilot paths (${e.paths.join(", ")||"none set"})`};if(e.agent.trim().toLowerCase()===n.codeAgent.trim().toLowerCase())return{run:!1,reason:`the test agent "${e.agent}" is the coding agent; set quality.specTests.agent to another name`};let s=gs(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:Ag(t)}}function _g(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function Pg(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function Eg(n){let e=n.split("\0").filter(Boolean),t=[];for(let s=0;s<e.length;s++){let r=e[s],o=r.slice(0,2);t.push({status:o,path:r.slice(3)}),(o.startsWith("R")||o.startsWith("C"))&&s++}return t}function Dg(n){let e=[],t=[];for(let s of n)s.status==="??"&&_g(s.path)?e.push(s.path):t.push(s.status==="??"?`${s.path} (new, not a test file)`:`${s.path} (${s.status.trim()||"changed"}, existing file)`);return{keep:e,discard:t}}var Og=[["private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/],["GitHub token",/\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})/],["GitLab token",/\bglpat-[A-Za-z0-9_-]{20,}/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}/],["API key (sk-)",/\bsk-(?!ant-)(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/],["Stripe key",/\b[sr]k_live_[A-Za-z0-9]{20,}/],["DigitalOcean token",/\bdo[pro]_v1_[a-f0-9]{64}\b/],["Hugging Face token",/\bhf_[A-Za-z0-9]{30,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["JSON Web Token",/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/],["AWS access key",/\b(AKIA|ASIA)[0-9A-Z]{16}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{35}\b/],["Slack token",/\bxox[abposr]-[A-Za-z0-9-]{10,}/],["Telegram bot token",/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/],["password in a URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s@/]{8,}@/i]];function Lg(n){return Og.filter(([,e])=>e.test(n)).map(([e])=>e)}var Ng=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],Fg=n=>`/${ls(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function Ug(n,e){let t=ls(n),s=a=>t===a||t.startsWith(a.endsWith(Fa)?a:a+Fa),r=bg(),o=[...e,r,...Ng.map(a=>us(r,a)),"/proc"].map(a=>ls(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let c=`/${Fg(a)}/**`;i.push(`Read(${c})`,`Edit(${c})`)}return i}async function Ka(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Ba(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},c,d=(l,g,m=12e4)=>s("git",l,{cwd:g,timeoutMs:m});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let g=r(),m={...a,...l,finishedAt:g,minutes:Math.round((g-o)/6e4*10)/10};n.store.record(m);let y=m.costUsd===void 0?"cost not reported":`$${m.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${m.status} in ${m.minutes} min, ${y}${m.note?` \u2014 ${m.note}`:""}`),m.status!=="pushed"&&m.note)try{await n.noteOnIssue(Oa(`Spec tests for #${t.number} (${e.agent}): ${m.note}`,e.agent))}catch(b){n.log(`[spec-tests] ${t.repo}#${t.number}: could not leave the note on the issue: ${b?.message||b}`)}return m};try{let l=await d(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let g=await d(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),m=g.code===0&&g.stdout.trim()?g.stdout.trim():"origin/main";c=(n.makeTempDir??(()=>mg(us(xg(),`agentx-spec-${t.number}-`))))();let y=await d(["worktree","add","--detach",c,m],n.checkout);if(y.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${m}: ${y.stderr.trim().slice(0,300)}`});let b=await n.runAgent({prompt:Cg(t),dir:c,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:Ug(c,n.protectedPaths??[n.checkout,process.cwd()])});if(b.budgetStopped)return await u({status:"budget-stopped",costUsd:b.costUsd,note:`stopped at the budget of $${e.maxCostPerIssue.toFixed(2)} (quality.specTests.maxCostPerIssue). No tests were pushed; review the issue's acceptance criteria by hand.`});if(b.timedOut)return await u({status:"timed-out",costUsd:b.costUsd,note:`stopped after ${e.maxMinutes} minutes (quality.specTests.maxMinutes). No tests were pushed.`});if(!b.ok)return await u({status:"failed",costUsd:b.costUsd,note:`the test agent failed: ${(b.error||"no reason given").slice(0,300)}`});let C=await d(["status","--porcelain","-z","--untracked-files=all"],c);if(C.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not list the files the test agent wrote: ${C.stderr.trim().slice(0,300)}`});let{keep:h,discard:P}=Dg(Eg(C.stdout));if(P.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${P.join(", ")}`),!h.length)return await u({status:"no-tests",costUsd:b.costUsd,note:`the test agent wrote no new test file${P.length?` (its other changes were discarded: ${P.join(", ")})`:""}.`});let D=0,A=[];for(let v of h){let T=Ha(us(c,v),"utf8");D+=Pg(T);for(let x of Lg(T))A.push(`${x} in ${v}`)}if(A.length)return await u({status:"blocked",costUsd:b.costUsd,testFiles:h,note:`a written file looks like it holds a secret (${A.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let _=Ig(e.agent),M=["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`],N=await d(["add","--",...h],c);if(N.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not stage the tests: ${N.stderr.trim().slice(0,300)}`});let L=`Written by ${e.agent} from the text of #${t.number} and its acceptance criteria only, without the implementation (#992).`,W=await d([...M,"commit","--no-verify","-m",Wa(t.number),"-m",L],c);if(W.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:h,note:`could not commit the tests: ${W.stderr.trim().slice(0,300)}`});let U=(await d(["rev-parse","HEAD"],c)).stdout.trim(),q=await d(["push","origin",`HEAD:refs/heads/${i}`],c);if(q.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:h,commit:U,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let X=await u({status:"pushed",costUsd:b.costUsd,branch:i,commit:U,testFiles:h,testsWritten:D});if(n.tellAuthor)try{await n.tellAuthor(`The spec tests for #${t.number} are on \`${i}\` (${h.join(", ")}). Merge them with \`git fetch origin ${i} && git merge --no-ff origin/${i}\`, run them, and record the outcome in the pull request's "Spec tests" section as described in your task.`)}catch(v){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${v?.message||v}`)}return X}catch(l){return await u({status:"failed",note:`unexpected error: ${(l?.message||String(l)).slice(0,300)}`})}finally{if(c){try{await d(["worktree","remove","--force",c],n.checkout)}catch{}try{pg(c)&&yg(c,{recursive:!0,force:!0})}catch{}}}}var Hg=5e3;function Ja(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,c=[],d=(g,m)=>{if(!a){a=!0;for(let y of c)clearTimeout(y);s({code:g,stdout:r,stderr:m??o,timedOut:i})}},u;try{u=gg(n,e,{cwd:t.cwd,env:t.env,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(g){d(-1,g?.message||String(g));return}let l=t.killGraceMs??Hg;t.timeoutMs&&c.push(setTimeout(()=>{i=!0,u.kill("SIGTERM"),c.push(setTimeout(()=>{u.kill("SIGKILL"),c.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),d(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",g=>{r+=g}),u.stderr?.on("data",g=>{o+=g}),u.stdin?.on("error",()=>{}),u.on("error",g=>d(-1,g.message)),u.on("close",g=>d(g??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var We=async(n,e,t)=>{let s=await Ja(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},jg="Read,Glob,Grep,Write,Edit";function Bg(n){return["-p","-","--output-format","json","--tools",jg,"--permission-mode","acceptEdits","--max-budget-usd",String(n.maxBudgetUsd),...n.model?["--model",n.model]:[],"--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",JSON.stringify({disableAllHooks:!0,permissions:{deny:n.deny??[]}}),"--no-session-persistence"]}function Ua(n,e){let t;try{t=JSON.parse(n)}catch{t=void 0}let s=typeof t?.total_cost_usd=="number"&&Number.isFinite(t.total_cost_usd)?t.total_cost_usd:void 0;return t?.subtype==="error_max_budget_usd"?{ok:!1,budgetStopped:!0,costUsd:s}:t?t.is_error||typeof t.subtype=="string"&&t.subtype!=="success"?{ok:!1,costUsd:s,error:String(t.result??t.subtype).slice(0,300)}:{ok:!0,costUsd:s,reply:String(t.result??"")}:{ok:!1,error:`claude exited ${e??"unknown"} with no result`}}var za=async n=>{let e=await Ja("claude",Bg(n),{cwd:n.dir,env:fr(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:Ua(e.stdout,e.code).costUsd};let t=Ua(e.stdout,e.code);return!t.ok&&!t.budgetStopped&&e.stderr&&(!t.error||!e.stdout)&&(t.error=e.stderr.trim().slice(0,300)),t};async function Qa(n,e,t,s){let r=await n("gh",["issue","view",String(t),"--repo",e,"--json","title,body"],{cwd:s,timeoutMs:2e4});if(r.code===0)try{let o=JSON.parse(r.stdout);return typeof o?.title!="string"?void 0:{repo:e,number:t,title:o.title,body:typeof o.body=="string"?o.body:""}}catch{return}}async function Xa(n,e,t,s,r){let o=await n("gh",["issue","comment",String(t),"--repo",e,"--body",r],{cwd:s,timeoutMs:2e4});if(o.code!==0)throw new Error(o.stderr.trim().slice(0,300)||`gh exited ${o.code}`)}import{existsSync as fs,mkdirSync as Wg,readdirSync as qg,statSync as Gg,utimesSync as Kg}from"fs";import{basename as Jg,dirname as zg,join as ut,resolve as ps}from"path";var Za={enabled:!1,maxAgeDays:14};function Va(n,e){if(!e)return null;if(n==="github"){let t=dt(e);return t&&t.kind==="issue"?{source:"github",repo:t.repo,id:String(t.number)}:null}if(n==="gitlab"){let t=e.match(/^(.+):issue:(\d+)$/);return t?{source:"gitlab",repo:t[1],id:t[2]}:null}if(n==="linear"||n==="jira"){let t=e.match(/^(?:linear|jira):([A-Za-z][A-Za-z0-9_]*-\d+)$/);return t?{source:n,id:t[1].toUpperCase()}:null}return null}function Qg(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function Xg(n){let e=(n||"").trim();return e?(e.match(/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?[^/]+\/(.+?)(?:\.git)?\/?$/i)??e.match(/^(?:[^@/\s]+@)?[^/:\s]+:(?!\/)(.+?)(?:\.git)?\/?$/))?.[1]:void 0}function ed(n,e,t=ds){let s=[...new Set(e.filter(Boolean))];for(let o of s){let i=t(o);if(i){if(!n.repo)return{dir:o};if(Xg(i)?.toLowerCase()===n.repo.toLowerCase())return{dir:o}}}let r=s.join(", ")||"nothing";return{reason:n.repo?`no checkout of ${n.repo} (looked in ${r})`:`no git checkout (looked in ${r})`}}function td(n,e){return e.root?ps(e.root):ut(zg(ps(n)),".agentx-worktrees",Jg(ps(n)))}var ms=n=>n.trim().slice(0,300);async function nd(n,e,t,s){let r=(g,m)=>s.exec("git",g,{cwd:m,timeoutMs:12e4}),o=Qg(n),i=td(e,t),a=ut(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(fs(ut(a,".git"))){let g=await r(["rev-parse","--abbrev-ref","HEAD"],a);return g.code===0&&g.stdout.trim()===o?(Ya(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${g.code===0?` (it is on ${g.stdout.trim()})`:""}; remove it or check out ${o} there`}}let c=await r(["fetch","origin"],e);c.code!==0&&s.log?.(`[worktrees] fetch in ${e} failed, using what is there: ${ms(c.stderr)}`),await r(["worktree","prune"],e);let d=await r(["rev-parse","--verify","--quiet",`refs/heads/${o}`],e),u;if(d.code===0)u=["worktree","add",a,o];else{let g=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),m=`origin/${o}`;if(g.code!==0){let y=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);m=y.code===0&&y.stdout.trim()?y.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,m]}Wg(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${ms(l.stderr)}`}:(Ya(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function Ya(n,e){let t=new Date((e??Date.now)());try{Kg(n,t,t)}catch{}}async function sd(n,e,t){let s=td(n,e);if(!fs(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of qg(s)){let a=ut(s,i);if(a===t.keep||!fs(ut(a,".git")))continue;let c;try{c=Gg(a).mtimeMs}catch{continue}if(r-c<e.maxAgeDays*864e5)continue;let d=await t.exec("git",["status","--porcelain"],{cwd:a,timeoutMs:6e4});if(d.code!==0||d.stdout.trim()){t.log?.(`[worktrees] kept ${a}: ${d.code!==0?"git status failed":"it has uncommitted changes"}`);continue}let u=await t.exec("git",["worktree","remove",a],{cwd:n,timeoutMs:6e4});u.code===0?o.push(a):t.log?.(`[worktrees] could not remove ${a}: ${ms(u.stderr)}`)}return o}function rd(n){return[`You are working in a git worktree of your own for this issue: ${n.dir}, on the branch \`${n.branch}\`.`,`Make your changes there, commit them on \`${n.branch}\`, push that branch, and open the pull request (or merge request) from it.`,`Do not switch branches and do not edit ${n.checkout}: other tasks use it.`].join(" ")}var Zg=250,Vg=5e3,rp={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},op=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),od=`[Operating principle]
132
- 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.`,ip="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function ap(n){return n==="claude-code"?`${od}
133
- ${ip}`:n==="codex-cli"?od:""}function id(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var gd;function By(n){gd=n}function Wy(){return gd}var ad=64*1024,dp=5*60*1e3,cp=3e4,up=300,lp=25*6e4,qe=".agentx/task-history",gp=30;function gt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function pp(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.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 fp(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=Nr(n,e,V().recent());return Ur(t,s)}function mp(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function hp(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let l=u.meta.type||"untyped",g=r.get(l)||[];g.push(u.meta.title),r.set(l,g)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
129
+ `)}function Ga(n,e){let t=Wa(n);return["","## Spec tests (#992)",`A separate test agent ("${e}") is writing tests for this issue from the issue text only, without seeing your code. It pushes them as one commit, "${qa(n)}", to the branch \`${t}\`.`,"- Do not write those tests yourself. Do not edit or delete them, except as described below.",`- Before you open the pull request, and again before you finish, run \`git fetch origin ${t}\`. When the branch exists, merge it into your branch with \`git merge --no-ff origin/${t}\` (a merge, not a cherry-pick, squash or rebase, so the commit keeps its author), then run its tests.`,'- When a spec test fails, decide which it is. A code defect: fix the code. A test that misreads the acceptance criteria: change that test in a separate commit whose message starts with "test: spec misread" and quotes the criterion it misreads. Never skip or disable a spec test.','- In the pull request description, add a "Spec tests" section that lists each failure on the first run and your call (code defect or test misread), and ends with this line, filled in:'," <!-- agentx:spec-tests written=W failed-first-run=F code-defects=D test-misreads=M -->","- If the branch has not appeared by the time you finish, say so in that section."].join(`
130
+ `)}var Rg=90*24*60*60*1e3,dn=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(ja(this.file,"utf8")),t=Array.isArray(e?.runs)?e.runs:[];this.runs=t.filter(s=>s&&typeof s.repo=="string"&&Number.isInteger(s.number)&&Number.isFinite(s.startedAt))}catch{this.runs=[]}}}save(){let e=Date.now();this.runs=this.runs.filter(t=>e-t.startedAt<Rg);try{mg(Ig(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;bg(t,JSON.stringify({runs:this.runs},null,2)),yg(t,this.file)}catch{}}get(e,t){this.load();let s=e.toLowerCase();return this.runs.find(r=>r.repo.toLowerCase()===s&&r.number===t)}record(e){this.load(),this.runs=this.runs.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.runs.push(e),this.save()}all(){return this.load(),[...this.runs]}},_g=10*6e4;function gs(n,e,t=Date.now()){if(n){if(n.status!=="running")return`spec tests already ran for this issue (${n.status})`;if(!(t-n.startedAt>e.maxMinutes*6e4+_g))return"spec tests are already running for this issue"}}function Ka(n){let{settings:e,issue:t}=n;if(!e.enabled)return{run:!1,reason:"spec tests are off"};if(!t)return{run:!1,reason:"the issue text could not be read"};if(!vg(`${t.title}
131
+ ${t.body}`,e.paths))return{run:!1,reason:`issue names none of the pilot paths (${e.paths.join(", ")||"none set"})`};if(e.agent.trim().toLowerCase()===n.codeAgent.trim().toLowerCase())return{run:!1,reason:`the test agent "${e.agent}" is the coding agent; set quality.specTests.agent to another name`};let s=gs(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:Cg(t)}}function Pg(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function Eg(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function Dg(n){let e=n.split("\0").filter(Boolean),t=[];for(let s=0;s<e.length;s++){let r=e[s],o=r.slice(0,2);t.push({status:o,path:r.slice(3)}),(o.startsWith("R")||o.startsWith("C"))&&s++}return t}function Og(n){let e=[],t=[];for(let s of n)s.status==="??"&&Pg(s.path)?e.push(s.path):t.push(s.status==="??"?`${s.path} (new, not a test file)`:`${s.path} (${s.status.trim()||"changed"}, existing file)`);return{keep:e,discard:t}}var Lg=[["private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/],["GitHub token",/\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})/],["GitLab token",/\bglpat-[A-Za-z0-9_-]{20,}/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}/],["API key (sk-)",/\bsk-(?!ant-)(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/],["Stripe key",/\b[sr]k_live_[A-Za-z0-9]{20,}/],["DigitalOcean token",/\bdo[pro]_v1_[a-f0-9]{64}\b/],["Hugging Face token",/\bhf_[A-Za-z0-9]{30,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["JSON Web Token",/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/],["AWS access key",/\b(AKIA|ASIA)[0-9A-Z]{16}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{35}\b/],["Slack token",/\bxox[abposr]-[A-Za-z0-9-]{10,}/],["Telegram bot token",/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/],["password in a URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s@/]{8,}@/i]];function Ng(n){return Lg.filter(([,e])=>e.test(n)).map(([e])=>e)}var Fg=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],Ug=n=>`/${ls(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function Hg(n,e){let t=ls(n),s=a=>t===a||t.startsWith(a.endsWith(Ua)?a:a+Ua),r=xg(),o=[...e,r,...Fg.map(a=>us(r,a)),"/proc"].map(a=>ls(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let c=`/${Ug(a)}/**`;i.push(`Read(${c})`,`Edit(${c})`)}return i}async function Ja(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Wa(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},c,d=(l,g,m=12e4)=>s("git",l,{cwd:g,timeoutMs:m});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let g=r(),m={...a,...l,finishedAt:g,minutes:Math.round((g-o)/6e4*10)/10};n.store.record(m);let y=m.costUsd===void 0?"cost not reported":`$${m.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${m.status} in ${m.minutes} min, ${y}${m.note?` \u2014 ${m.note}`:""}`),m.status!=="pushed"&&m.note)try{await n.noteOnIssue(La(`Spec tests for #${t.number} (${e.agent}): ${m.note}`,e.agent))}catch(b){n.log(`[spec-tests] ${t.repo}#${t.number}: could not leave the note on the issue: ${b?.message||b}`)}return m};try{let l=await d(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let g=await d(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),m=g.code===0&&g.stdout.trim()?g.stdout.trim():"origin/main";c=(n.makeTempDir??(()=>hg(us(Sg(),`agentx-spec-${t.number}-`))))();let y=await d(["worktree","add","--detach",c,m],n.checkout);if(y.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${m}: ${y.stderr.trim().slice(0,300)}`});let b=await n.runAgent({prompt:Mg(t),dir:c,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:Hg(c,n.protectedPaths??[n.checkout,process.cwd()])});if(b.budgetStopped)return await u({status:"budget-stopped",costUsd:b.costUsd,note:`stopped at the budget of $${e.maxCostPerIssue.toFixed(2)} (quality.specTests.maxCostPerIssue). No tests were pushed; review the issue's acceptance criteria by hand.`});if(b.timedOut)return await u({status:"timed-out",costUsd:b.costUsd,note:`stopped after ${e.maxMinutes} minutes (quality.specTests.maxMinutes). No tests were pushed.`});if(!b.ok)return await u({status:"failed",costUsd:b.costUsd,note:`the test agent failed: ${(b.error||"no reason given").slice(0,300)}`});let C=await d(["status","--porcelain","-z","--untracked-files=all"],c);if(C.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not list the files the test agent wrote: ${C.stderr.trim().slice(0,300)}`});let{keep:h,discard:P}=Og(Dg(C.stdout));if(P.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${P.join(", ")}`),!h.length)return await u({status:"no-tests",costUsd:b.costUsd,note:`the test agent wrote no new test file${P.length?` (its other changes were discarded: ${P.join(", ")})`:""}.`});let D=0,A=[];for(let v of h){let T=ja(us(c,v),"utf8");D+=Eg(T);for(let x of Ng(T))A.push(`${x} in ${v}`)}if(A.length)return await u({status:"blocked",costUsd:b.costUsd,testFiles:h,note:`a written file looks like it holds a secret (${A.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let _=Tg(e.agent),M=["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`],N=await d(["add","--",...h],c);if(N.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not stage the tests: ${N.stderr.trim().slice(0,300)}`});let L=`Written by ${e.agent} from the text of #${t.number} and its acceptance criteria only, without the implementation (#992).`,W=await d([...M,"commit","--no-verify","-m",qa(t.number),"-m",L],c);if(W.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:h,note:`could not commit the tests: ${W.stderr.trim().slice(0,300)}`});let U=(await d(["rev-parse","HEAD"],c)).stdout.trim(),q=await d(["push","origin",`HEAD:refs/heads/${i}`],c);if(q.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:h,commit:U,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let X=await u({status:"pushed",costUsd:b.costUsd,branch:i,commit:U,testFiles:h,testsWritten:D});if(n.tellAuthor)try{await n.tellAuthor(`The spec tests for #${t.number} are on \`${i}\` (${h.join(", ")}). Merge them with \`git fetch origin ${i} && git merge --no-ff origin/${i}\`, run them, and record the outcome in the pull request's "Spec tests" section as described in your task.`)}catch(v){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${v?.message||v}`)}return X}catch(l){return await u({status:"failed",note:`unexpected error: ${(l?.message||String(l)).slice(0,300)}`})}finally{if(c){try{await d(["worktree","remove","--force",c],n.checkout)}catch{}try{fg(c)&&wg(c,{recursive:!0,force:!0})}catch{}}}}var jg=5e3;function za(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,c=[],d=(g,m)=>{if(!a){a=!0;for(let y of c)clearTimeout(y);s({code:g,stdout:r,stderr:m??o,timedOut:i})}},u;try{u=pg(n,e,{cwd:t.cwd,env:t.env,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(g){d(-1,g?.message||String(g));return}let l=t.killGraceMs??jg;t.timeoutMs&&c.push(setTimeout(()=>{i=!0,u.kill("SIGTERM"),c.push(setTimeout(()=>{u.kill("SIGKILL"),c.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),d(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",g=>{r+=g}),u.stderr?.on("data",g=>{o+=g}),u.stdin?.on("error",()=>{}),u.on("error",g=>d(-1,g.message)),u.on("close",g=>d(g??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var We=async(n,e,t)=>{let s=await za(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},Bg="Read,Glob,Grep,Write,Edit";function Wg(n){return["-p","-","--output-format","json","--tools",Bg,"--permission-mode","acceptEdits","--max-budget-usd",String(n.maxBudgetUsd),...n.model?["--model",n.model]:[],"--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",JSON.stringify({disableAllHooks:!0,permissions:{deny:n.deny??[]}}),"--no-session-persistence"]}function Ha(n,e){let t;try{t=JSON.parse(n)}catch{t=void 0}let s=typeof t?.total_cost_usd=="number"&&Number.isFinite(t.total_cost_usd)?t.total_cost_usd:void 0;return t?.subtype==="error_max_budget_usd"?{ok:!1,budgetStopped:!0,costUsd:s}:t?t.is_error||typeof t.subtype=="string"&&t.subtype!=="success"?{ok:!1,costUsd:s,error:String(t.result??t.subtype).slice(0,300)}:{ok:!0,costUsd:s,reply:String(t.result??"")}:{ok:!1,error:`claude exited ${e??"unknown"} with no result`}}var Qa=async n=>{let e=await za("claude",Wg(n),{cwd:n.dir,env:fr(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:Ha(e.stdout,e.code).costUsd};let t=Ha(e.stdout,e.code);return!t.ok&&!t.budgetStopped&&e.stderr&&(!t.error||!e.stdout)&&(t.error=e.stderr.trim().slice(0,300)),t};async function Xa(n,e,t,s){let r=await n("gh",["issue","view",String(t),"--repo",e,"--json","title,body"],{cwd:s,timeoutMs:2e4});if(r.code===0)try{let o=JSON.parse(r.stdout);return typeof o?.title!="string"?void 0:{repo:e,number:t,title:o.title,body:typeof o.body=="string"?o.body:""}}catch{return}}async function Ya(n,e,t,s,r){let o=await n("gh",["issue","comment",String(t),"--repo",e,"--body",r],{cwd:s,timeoutMs:2e4});if(o.code!==0)throw new Error(o.stderr.trim().slice(0,300)||`gh exited ${o.code}`)}import{existsSync as fs,mkdirSync as qg,readdirSync as Gg,statSync as Kg,utimesSync as Jg}from"fs";import{basename as zg,dirname as Qg,join as ut,resolve as ps}from"path";var Va={enabled:!1,maxAgeDays:14};function ed(n,e){if(!e)return null;if(n==="github"){let t=dt(e);return t&&t.kind==="issue"?{source:"github",repo:t.repo,id:String(t.number)}:null}if(n==="gitlab"){let t=e.match(/^(.+):issue:(\d+)$/);return t?{source:"gitlab",repo:t[1],id:t[2]}:null}if(n==="linear"||n==="jira"){let t=e.match(/^(?:linear|jira):([A-Za-z][A-Za-z0-9_]*-\d+)$/);return t?{source:n,id:t[1].toUpperCase()}:null}return null}function Xg(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function Yg(n){let e=(n||"").trim();return e?(e.match(/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?[^/]+\/(.+?)(?:\.git)?\/?$/i)??e.match(/^(?:[^@/\s]+@)?[^/:\s]+:(?!\/)(.+?)(?:\.git)?\/?$/))?.[1]:void 0}function td(n,e,t=ds){let s=[...new Set(e.filter(Boolean))];for(let o of s){let i=t(o);if(i){if(!n.repo)return{dir:o};if(Yg(i)?.toLowerCase()===n.repo.toLowerCase())return{dir:o}}}let r=s.join(", ")||"nothing";return{reason:n.repo?`no checkout of ${n.repo} (looked in ${r})`:`no git checkout (looked in ${r})`}}function nd(n,e){return e.root?ps(e.root):ut(Qg(ps(n)),".agentx-worktrees",zg(ps(n)))}var ms=n=>n.trim().slice(0,300);async function sd(n,e,t,s){let r=(g,m)=>s.exec("git",g,{cwd:m,timeoutMs:12e4}),o=Xg(n),i=nd(e,t),a=ut(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(fs(ut(a,".git"))){let g=await r(["rev-parse","--abbrev-ref","HEAD"],a);return g.code===0&&g.stdout.trim()===o?(Za(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${g.code===0?` (it is on ${g.stdout.trim()})`:""}; remove it or check out ${o} there`}}let c=await r(["fetch","origin"],e);c.code!==0&&s.log?.(`[worktrees] fetch in ${e} failed, using what is there: ${ms(c.stderr)}`),await r(["worktree","prune"],e);let d=await r(["rev-parse","--verify","--quiet",`refs/heads/${o}`],e),u;if(d.code===0)u=["worktree","add",a,o];else{let g=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),m=`origin/${o}`;if(g.code!==0){let y=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);m=y.code===0&&y.stdout.trim()?y.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,m]}qg(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${ms(l.stderr)}`}:(Za(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function Za(n,e){let t=new Date((e??Date.now)());try{Jg(n,t,t)}catch{}}async function rd(n,e,t){let s=nd(n,e);if(!fs(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of Gg(s)){let a=ut(s,i);if(a===t.keep||!fs(ut(a,".git")))continue;let c;try{c=Kg(a).mtimeMs}catch{continue}if(r-c<e.maxAgeDays*864e5)continue;let d=await t.exec("git",["status","--porcelain"],{cwd:a,timeoutMs:6e4});if(d.code!==0||d.stdout.trim()){t.log?.(`[worktrees] kept ${a}: ${d.code!==0?"git status failed":"it has uncommitted changes"}`);continue}let u=await t.exec("git",["worktree","remove",a],{cwd:n,timeoutMs:6e4});u.code===0?o.push(a):t.log?.(`[worktrees] could not remove ${a}: ${ms(u.stderr)}`)}return o}function od(n){return[`You are working in a git worktree of your own for this issue: ${n.dir}, on the branch \`${n.branch}\`.`,`Make your changes there, commit them on \`${n.branch}\`, push that branch, and open the pull request (or merge request) from it.`,`Do not switch branches and do not edit ${n.checkout}: other tasks use it.`].join(" ")}var Vg=250,ep=5e3,op={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},ip=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),id=`[Operating principle]
132
+ 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.`,ap="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function dp(n){return n==="claude-code"?`${id}
133
+ ${ap}`:n==="codex-cli"?id:""}function ad(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var pd;function Wy(n){pd=n}function qy(){return pd}var dd=64*1024,cp=5*60*1e3,up=3e4,lp=300,gp=25*6e4,qe=".agentx/task-history",pp=30;function gt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function fp(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.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 mp(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=Nr(n,e,V().recent());return Ur(t,s)}function hp(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function yp(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let l=u.meta.type||"untyped",g=r.get(l)||[];g.push(u.meta.title),r.set(l,g)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
134
134
  `),c=process.argv[1]||"dist/cli.js",d=n.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${s.length} article${s.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
135
135
  node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${c} wiki facts list --dir ${d}\`. 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.`,...t.notesInbox&&t.notesInbox.inbox!==e?["",`When you learn something the wiki should know (a change, a correction, a fact that went stale), leave a short note for the wiki run: \`node ${c} wiki notes add --from ${e} --change "what changed" --source "where you saw it" --date YYYY-MM-DD --daemon ${t.notesInbox.daemonUrl}\`. The run checks it before it changes anything. Notes stay inside the fleet; never put secrets in one.`]:[],"[End Institutional Wiki]"].join(`
136
- `)}var hs=8*1024;function yp(n,e){if(n)try{oo(n)}catch{}return e}function dd(n){if(n.length<=hs)return n;let e=n.length-hs;return n.slice(0,hs)+`\u2026[+${e}]`}function cd(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function wp(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function ud(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=V();if(s==="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:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?dd(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?dd(a):null,at:r})}return}}function bp(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
136
+ `)}var hs=8*1024;function wp(n,e){if(n)try{io(n)}catch{}return e}function cd(n){if(n.length<=hs)return n;let e=n.length-hs;return n.slice(0,hs)+`\u2026[+${e}]`}function ud(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function bp(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function ld(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=V();if(s==="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:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?cd(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?cd(a):null,at:r})}return}}function xp(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
137
137
  `;if(s==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
138
138
  `;if(s==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
139
139
  `;if(s==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
@@ -154,32 +154,32 @@ ${ip}`:n==="codex-cli"?od:""}function id(n,e){return e!=="claude-code"&&e!=="cod
154
154
  \u2192 ${i}(${a})
155
155
  `}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${gt(i,800)}
156
156
  `}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
157
- `:""}}var ld=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Rr;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;voiceClaims=new Set;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new Cr;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;specTests;worktreesPending=new Map;worktreesPrunedAt=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 zt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new kr(void 0,void 0,"graph"),this.memoryStore=new Mr,this.patternStore=new Zt,this.rateLimiter=new Qt,this.tokenTracker=new $r,this.messageQueue=new Xt,Di({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),Hr(Br(e)),jr(qr(e)),this.budgetHolds=new Vt(Zn,K(process.cwd(),".agentx/budget-holds.json"),s=>this.log(s)),this.budgetHolds.size&&(this.log(`[budget] ${this.budgetHolds.size} held message(s) kept from before the restart`),this.armBudgetRelease()),e.graph?.enabled){this.graphStore=new Ir({baseDir:K(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Tr({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setRunNote(e){this.runNote=e}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=rr(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new so(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);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 s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,s,r);i=oi(g.messages,e.message??""),c=ii(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await be(bo,So(d),xo,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!Io(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),V().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-6RP4Z3S5.js"),c=await a(t,s);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-Z4D5KRA6.js"),u=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
158
- `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new on(K(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...an,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=dt(t.context?.chatId),a=this.cloudSessionStore();return _a({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...an,...e.cloudSessions??{}},i=Date.now(),a=Ce(st(Oe(e.workspace),t),e.billing),c=l=>Ea({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),d=await this.planSpecTests(t.agentId,s),u=await Da({route:s,agentId:t.agentId,message:d?`${t.message}
159
- ${qa(d.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:c,log:l=>this.log(l),trace:l=>{try{V().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(d&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!gs(this.specTestStore().get(d.repo,d.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,d,s.cwd,g=>c({cwd:s.cwd,prompt:g,sessionId:l}).then(m=>{if(!m.ok)throw new Error(m.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}async inTaskWorktree(e,t){let s={...Za,...e.worktrees??{}};if(!s.enabled)return{def:e,task:t};let r=Va(t.context?.channel,t.context?.chatId);if(!r)return{def:e,task:t};let o=`${r.repo?`${r.repo}#`:""}${r.id}`,i=ed(r,[t.context?.runbookPath,e.workspace].filter(g=>!!g));if("reason"in i)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${i.reason}`),{def:e,task:t};let a=`${t.agentId}:${i.dir}:${o}`,c=this.worktreesPending.get(a);c||(c=nd(r,i.dir,s,{exec:We,log:g=>this.log(g)}),this.worktreesPending.set(a,c),c.finally(()=>this.worktreesPending.delete(a)).catch(()=>{}));let d;try{d=await c}catch(g){d={error:g?.message||String(g)}}if("error"in d)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${d.error}`),{def:e,task:t};this.log(`[worktrees] ${t.agentId} ${o}: ${d.reused?"reusing":"created"} ${d.dir} on ${d.branch}`);let u=this.worktreesPrunedAt.get(i.dir)??0;Date.now()-u>36e5&&(this.worktreesPrunedAt.set(i.dir,Date.now()),sd(i.dir,s,{exec:We,log:g=>this.log(g),keep:d.dir}).then(g=>{g.length&&this.log(`[worktrees] removed ${g.length} unused worktree(s): ${g.join(", ")}`)}).catch(g=>this.log(`[worktrees] prune failed: ${g?.message||g}`)));let l=rd(d);return{fresh:!d.reused,def:{...e,persistentProcess:!1},task:{...t,cwd:d.dir,systemPromptAppend:t.systemPromptAppend?`${t.systemPromptAppend}
160
-
161
- ${l}`:l}}}specTestSettings(){return{...ja,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new dn(K(process.cwd(),".agentx/spec-tests.json"))),this.specTests}async planSpecTests(e,t){let s=this.specTestSettings();if(!s.enabled||t.route!=="cloud"||t.kind!=="issue")return null;let r=await Qa(We,t.repo,t.number,t.cwd),o=Ga({settings:s,issue:r,codeAgent:e,previous:this.specTestStore().get(t.repo,t.number)});return o.run?o.input:(this.log(`[spec-tests] ${t.repo}#${t.number}: not running: ${o.reason}`),null)}async startSpecTests(e,t,s,r){try{await Ka({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:We,runAgent:za,store:this.specTestStore(),noteOnIssue:o=>Xa(We,t.repo,t.number,s,o),tellAuthor:r,log:o=>this.log(o)})}catch(o){this.log(`[spec-tests] ${t.repo}#${t.number}: ${o?.message||o}`)}}callerGone(e,t){let s=Pe(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(l){i={content:"",error:l?.message??String(l)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&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,s,r);if(d){let l=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${l}"). Please send it again.`,errorKind:"interrupted"}}let u=pi({error:i.error,errorKind:i.errorKind,viaMesh:i.viaMesh,channel:e.context?.channel,chatId:e.context?.chatId,workflowRunId:e.workflowRunId,continuation:e.timeLimitContinuation??0,timeoutMinutes:e.timeoutMinutes,elapsedMs:Date.now()-(e.timeLimitStartedAt??o),callerGone:e.callerSignal?.aborted??!1,settings:this.config.resume?.timeLimit??Gn});if(u.action==="continue"){let l=this.config.resume?.timeLimit??Gn,g=e.taskId,m=[];try{m=g&&this.traceToolCalls?this.traceToolCalls(g):[]}catch{}let y=mi(u.minutes,m,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${g??"-"}: stopped at its ${u.minutes}m time limit; continuing (${u.continuation}/${l.maxContinuations})`);let b=e.timeLimitRequest??e.message;return this.execute({...e,message:`${y}
162
- ${b}`,timeLimitRequest:b,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:g??e.resumedFrom,runningTaskId:void 0,freshSession:!1},t,s,r)}if(u.action==="report"&&(this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${e.taskId??"-"}: stopped at its ${u.minutes}m time limit; not continued \u2014 ${u.reason}`),i={...i,error:fi(i.error,u.reason)}),e.intentRef)try{let l=i.error?Ye(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Pr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:l,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(l){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${l?.message??l}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};e.isolated&&(e.autonomy="report");let i=pe(e.autonomy),a=or(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:Ri().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(c){let p=await c;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){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 p=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(k=>k.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:p.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=Kt(e.context),g,m=Wr(process.cwd(),e.agentId);if(m)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:m,errorKind:"agent_held"};if(!i){let p=e.context?.channel,f=e.context?.chatId,k=Pt(e.agentId,void 0,_t(e.agentId,f));if(k&&p&&f&&Mn()?.getChannel(p)){let I=this.budgetHolds.hold(e.agentId,{text:e.message,channel:p,chatId:String(f),context:e.context,heldAt:e.queuedAt??Date.now()});if(I!=="full"){this.armBudgetRelease();let B=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${B} waiting) chat=${p}:${f}`),I==="held"?{content:"",error:vn("budget",B)}:{content:"",error:`${k.message} This message is kept and runs when the agent resumes.`,errorKind:"budget_cap"}}this.log(`[${e.agentId}] over budget \u2014 hold is full, message refused`)}}if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i){let p=Date.now(),f=e.slotWaitMs??lp,k=500;for(d.activeTasks>=d.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${Math.round(f/6e4)}m) behind=${d.runningTasks.map(I=>I.id).join(",")||"-"} chat=${u}:${l}`);d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-p>f)return this.log(`[${e.agentId}] slot wait timed out after ${Math.round(f/6e4)}m chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(I=>setTimeout(I,k))}Date.now()-p>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-p)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"){let p=Date.now(),f=25*6e4,k=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(k);){if(Date.now()-p>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(I=>setTimeout(I,500))}g=k,this.voiceClaims.add(k)}else{let p=d.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let k=this.messageQueue.pendingCount(e.agentId,u,l);return V().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:In(e.context),humanRoot:ze(e.context),person:Tn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${k}) behind=${d.runningTasks.map(I=>I.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:vn(f,k)}}}let y=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,f)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(g&&this.voiceClaims.delete(g),!y.ok)return this.log(`[${e.agentId}] ${y.reason}`),{content:"",error:y.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let p=yi(e.queuedAt);p&&(e.message=`${p}
163
- ${e.message}`),e.queuedAt=void 0}let b=Si({message:e.message,home:e.context?.home}),C=xi(d.runningTasks,b,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});C&&(this.log(`[${e.agentId}] ${C.slice(0,160)}`),e.message=`${C}
164
- ${e.message}`),d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let h={...b.length?{homes:b}:{},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,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(h),e.runningTaskId=h.id;let P=Tn(this.config.people,e.context);if(e.context&&(P?e.context.person=P.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let D=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:D,sender:e.context?.sender,rootId:Rt()?.rootId,workflowRunId:e.workflowRunId??(typeof h.chatId=="string"&&h.chatId.startsWith("workflow:")&&h.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let A={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,A);let _=p=>{if(p){A.buffer+=p,A.buffer.length>ad&&(A.buffer=A.buffer.slice(A.buffer.length-ad));for(let f of A.subscribers)try{f(p)}catch{}}},M=Ee();e.taskId=M,h.traceId=M;let N=this.taskAborts.get(h.id);N&&(N.traceId=M);let L=new Map,W=(p,f,k)=>{try{V().emit("task:step",{taskId:M,agentId:e.agentId,name:"pipeline",action:p,status:k,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},U=0,q=!1,X=()=>{q||(q=!0,U&&W("first-event",U,"ok"))},v;if(t){let p=bp();v=f=>{X();let k=p(f);if(k&&_(k),ud(M,e.agentId,f),cd(L,f),Yn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else v=p=>{if(X(),ud(M,e.agentId,p),cd(L,p),Yn(p,void 0,e.model||d.def.model),r)try{r(p)}catch{}};let T=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,x=T?setTimeout(()=>D.abort(new Error(`timed out after ${Math.round(T/1e3)}s`)),T):void 0;x?.unref?.();let F=(d.def.preSpawnTimeoutSec??up)*1e3,j=setTimeout(()=>{D.abort(new Error(`timed out before spawn after ${Math.round(F/1e3)}s in step "${h.step??"start"}"`))},F);j.unref?.();let E=()=>{j&&clearTimeout(j),j=void 0},J=()=>`task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`,re;D.signal.addEventListener("abort",()=>{let p=Pe(D.signal).message;/^timed out/.test(p)&&(re=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${p} ${J()}`)},{once:!0});let ee=p=>{h.step=p,this.log(`[${e.agentId}] step ${p} ${J()}`)},R=(p,f,k=0)=>{if(D.signal.aborted)return Promise.reject(Pe(D.signal));ee(p),(p==="agent"||p==="workflow-auto-run")&&(E(),U=Date.now());let I=Date.now(),B=Ra(f(),rp[p]??0,p);return Ma(B,D.signal,k).then(G=>(W(p,I,"ok"),G),G=>{throw W(p,I,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${J()}`),G})},te=async(p,f,k,I=0)=>{try{return await R(p,f,I)}catch(B){if(B instanceof Be)return k();throw B}},ie=!1,cn=!1,ys=p=>{if(!(!ie||cn)){cn=!0;try{V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-h.startedAt.getTime(),error:p?.error||(D.signal.aborted?Pe(D.signal).message:"run ended before completion"),errorKind:p?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,stopped:!this.interruptedRuns.has(h.id)&&(this.stoppedRuns.has(h.id)||p?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ws=!1,bs=p=>{if(ws)return;ws=!0,ys(p),this.runReleases.delete(h.id),x&&clearTimeout(x),E(),d.activeTasks--;let f=d.runningTasks.findIndex(I=>I.id===h.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id);let k=this.runEndWaiters.get(h.id);this.runEndWaiters.delete(h.id);for(let I of k??[])try{I()}catch{}A.done=!0,A.endedAt=new Date;for(let I of A.subscribers)try{I(`
157
+ `:""}}var gd=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Rr;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;voiceClaims=new Set;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new Cr;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;specTests;worktreesPending=new Map;worktreesPrunedAt=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 zt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new kr(void 0,void 0,"graph"),this.memoryStore=new Mr,this.patternStore=new Zt,this.rateLimiter=new Qt,this.tokenTracker=new $r,this.messageQueue=new Xt,Oi({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),Hr(Br(e)),jr(Gr(e)),this.budgetHolds=new Vt(Zn,K(process.cwd(),".agentx/budget-holds.json"),s=>this.log(s)),this.budgetHolds.size&&(this.log(`[budget] ${this.budgetHolds.size} held message(s) kept from before the restart`),this.armBudgetRelease()),e.graph?.enabled){this.graphStore=new Ir({baseDir:K(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Tr({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setRunNote(e){this.runNote=e}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=rr(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new ro(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);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 s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,s,r);i=ii(g.messages,e.message??""),c=ai(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await be(xo,Io(d),So,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!To(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),V().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-6RP4Z3S5.js"),c=await a(t,s);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-Z4D5KRA6.js"),u=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
158
+ `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new on(K(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...an,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=dt(t.context?.chatId),a=this.cloudSessionStore();return Pa({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...an,...e.cloudSessions??{}},i=Date.now(),a=Ce(st(Oe(e.workspace),t),e.billing),c=l=>Da({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),d=await this.planSpecTests(t.agentId,s),u=await Oa({route:s,agentId:t.agentId,message:d?`${t.message}
159
+ ${Ga(d.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:c,log:l=>this.log(l),trace:l=>{try{V().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(d&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!gs(this.specTestStore().get(d.repo,d.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,d,s.cwd,g=>c({cwd:s.cwd,prompt:g,sessionId:l}).then(m=>{if(!m.ok)throw new Error(m.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}async inTaskWorktree(e,t){let s={...Va,...e.worktrees??{}};if(!s.enabled)return{def:e,task:t};let r=ed(t.context?.channel,t.context?.chatId);if(!r)return{def:e,task:t};let o=`${r.repo?`${r.repo}#`:""}${r.id}`,i=td(r,[t.context?.runbookPath,e.workspace].filter(g=>!!g));if("reason"in i)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${i.reason}`),{def:e,task:t};let a=`${t.agentId}:${i.dir}:${o}`,c=this.worktreesPending.get(a);c||(c=sd(r,i.dir,s,{exec:We,log:g=>this.log(g)}),this.worktreesPending.set(a,c),c.finally(()=>this.worktreesPending.delete(a)).catch(()=>{}));let d;try{d=await c}catch(g){d={error:g?.message||String(g)}}if("error"in d)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${d.error}`),{def:e,task:t};this.log(`[worktrees] ${t.agentId} ${o}: ${d.reused?"reusing":"created"} ${d.dir} on ${d.branch}`);let u=this.worktreesPrunedAt.get(i.dir)??0;Date.now()-u>36e5&&(this.worktreesPrunedAt.set(i.dir,Date.now()),rd(i.dir,s,{exec:We,log:g=>this.log(g),keep:d.dir}).then(g=>{g.length&&this.log(`[worktrees] removed ${g.length} unused worktree(s): ${g.join(", ")}`)}).catch(g=>this.log(`[worktrees] prune failed: ${g?.message||g}`)));let l=od(d);return{fresh:!d.reused,def:{...e,persistentProcess:!1},task:{...t,cwd:d.dir,systemPromptAppend:t.systemPromptAppend?`${t.systemPromptAppend}
160
+
161
+ ${l}`:l}}}specTestSettings(){return{...Ba,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new dn(K(process.cwd(),".agentx/spec-tests.json"))),this.specTests}async planSpecTests(e,t){let s=this.specTestSettings();if(!s.enabled||t.route!=="cloud"||t.kind!=="issue")return null;let r=await Xa(We,t.repo,t.number,t.cwd),o=Ka({settings:s,issue:r,codeAgent:e,previous:this.specTestStore().get(t.repo,t.number)});return o.run?o.input:(this.log(`[spec-tests] ${t.repo}#${t.number}: not running: ${o.reason}`),null)}async startSpecTests(e,t,s,r){try{await Ja({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:We,runAgent:Qa,store:this.specTestStore(),noteOnIssue:o=>Ya(We,t.repo,t.number,s,o),tellAuthor:r,log:o=>this.log(o)})}catch(o){this.log(`[spec-tests] ${t.repo}#${t.number}: ${o?.message||o}`)}}callerGone(e,t){let s=Pe(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(l){i={content:"",error:l?.message??String(l)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&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,s,r);if(d){let l=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${l}"). Please send it again.`,errorKind:"interrupted"}}let u=fi({error:i.error,errorKind:i.errorKind,viaMesh:i.viaMesh,channel:e.context?.channel,chatId:e.context?.chatId,workflowRunId:e.workflowRunId,continuation:e.timeLimitContinuation??0,timeoutMinutes:e.timeoutMinutes,elapsedMs:Date.now()-(e.timeLimitStartedAt??o),callerGone:e.callerSignal?.aborted??!1,settings:this.config.resume?.timeLimit??Gn});if(u.action==="continue"){let l=this.config.resume?.timeLimit??Gn,g=e.taskId,m=[];try{m=g&&this.traceToolCalls?this.traceToolCalls(g):[]}catch{}let y=hi(u.minutes,m,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${g??"-"}: stopped at its ${u.minutes}m time limit; continuing (${u.continuation}/${l.maxContinuations})`);let b=e.timeLimitRequest??e.message;return this.execute({...e,message:`${y}
162
+ ${b}`,timeLimitRequest:b,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:g??e.resumedFrom,runningTaskId:void 0,freshSession:!1},t,s,r)}if(u.action==="report"&&(this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${e.taskId??"-"}: stopped at its ${u.minutes}m time limit; not continued \u2014 ${u.reason}`),i={...i,error:mi(i.error,u.reason)}),e.intentRef)try{let l=i.error?Ye(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Pr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:l,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(l){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${l?.message??l}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};e.isolated&&(e.autonomy="report");let i=pe(e.autonomy),a=or(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:_i().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(c){let p=await c;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){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 p=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(k=>k.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:p.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=Kt(e.context),g,m=qr(Wr(),e.agentId);if(m)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:m,errorKind:"agent_held"};if(!i){let p=e.context?.channel,f=e.context?.chatId,k=Pt(e.agentId,void 0,_t(e.agentId,f));if(k&&p&&f&&Mn()?.getChannel(p)){let I=this.budgetHolds.hold(e.agentId,{text:e.message,channel:p,chatId:String(f),context:e.context,heldAt:e.queuedAt??Date.now()});if(I!=="full"){this.armBudgetRelease();let B=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${B} waiting) chat=${p}:${f}`),I==="held"?{content:"",error:vn("budget",B)}:{content:"",error:`${k.message} This message is kept and runs when the agent resumes.`,errorKind:"budget_cap"}}this.log(`[${e.agentId}] over budget \u2014 hold is full, message refused`)}}if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i){let p=Date.now(),f=e.slotWaitMs??gp,k=500;for(d.activeTasks>=d.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${Math.round(f/6e4)}m) behind=${d.runningTasks.map(I=>I.id).join(",")||"-"} chat=${u}:${l}`);d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-p>f)return this.log(`[${e.agentId}] slot wait timed out after ${Math.round(f/6e4)}m chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(I=>setTimeout(I,k))}Date.now()-p>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-p)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"){let p=Date.now(),f=25*6e4,k=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(k);){if(Date.now()-p>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(I=>setTimeout(I,500))}g=k,this.voiceClaims.add(k)}else{let p=d.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let k=this.messageQueue.pendingCount(e.agentId,u,l);return V().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:In(e.context),humanRoot:ze(e.context),person:Tn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${k}) behind=${d.runningTasks.map(I=>I.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:vn(f,k)}}}let y=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,f)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(g&&this.voiceClaims.delete(g),!y.ok)return this.log(`[${e.agentId}] ${y.reason}`),{content:"",error:y.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let p=wi(e.queuedAt);p&&(e.message=`${p}
163
+ ${e.message}`),e.queuedAt=void 0}let b=Ii({message:e.message,home:e.context?.home}),C=Si(d.runningTasks,b,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});C&&(this.log(`[${e.agentId}] ${C.slice(0,160)}`),e.message=`${C}
164
+ ${e.message}`),d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let h={...b.length?{homes:b}:{},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,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(h),e.runningTaskId=h.id;let P=Tn(this.config.people,e.context);if(e.context&&(P?e.context.person=P.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let D=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:D,sender:e.context?.sender,rootId:Rt()?.rootId,workflowRunId:e.workflowRunId??(typeof h.chatId=="string"&&h.chatId.startsWith("workflow:")&&h.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let A={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,A);let _=p=>{if(p){A.buffer+=p,A.buffer.length>dd&&(A.buffer=A.buffer.slice(A.buffer.length-dd));for(let f of A.subscribers)try{f(p)}catch{}}},M=Ee();e.taskId=M,h.traceId=M;let N=this.taskAborts.get(h.id);N&&(N.traceId=M);let L=new Map,W=(p,f,k)=>{try{V().emit("task:step",{taskId:M,agentId:e.agentId,name:"pipeline",action:p,status:k,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},U=0,q=!1,X=()=>{q||(q=!0,U&&W("first-event",U,"ok"))},v;if(t){let p=xp();v=f=>{X();let k=p(f);if(k&&_(k),ld(M,e.agentId,f),ud(L,f),Yn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else v=p=>{if(X(),ld(M,e.agentId,p),ud(L,p),Yn(p,void 0,e.model||d.def.model),r)try{r(p)}catch{}};let T=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,x=T?setTimeout(()=>D.abort(new Error(`timed out after ${Math.round(T/1e3)}s`)),T):void 0;x?.unref?.();let F=(d.def.preSpawnTimeoutSec??lp)*1e3,j=setTimeout(()=>{D.abort(new Error(`timed out before spawn after ${Math.round(F/1e3)}s in step "${h.step??"start"}"`))},F);j.unref?.();let E=()=>{j&&clearTimeout(j),j=void 0},J=()=>`task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`,re;D.signal.addEventListener("abort",()=>{let p=Pe(D.signal).message;/^timed out/.test(p)&&(re=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${p} ${J()}`)},{once:!0});let ee=p=>{h.step=p,this.log(`[${e.agentId}] step ${p} ${J()}`)},R=(p,f,k=0)=>{if(D.signal.aborted)return Promise.reject(Pe(D.signal));ee(p),(p==="agent"||p==="workflow-auto-run")&&(E(),U=Date.now());let I=Date.now(),B=_a(f(),op[p]??0,p);return Ra(B,D.signal,k).then(G=>(W(p,I,"ok"),G),G=>{throw W(p,I,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${J()}`),G})},te=async(p,f,k,I=0)=>{try{return await R(p,f,I)}catch(B){if(B instanceof Be)return k();throw B}},ie=!1,cn=!1,ys=p=>{if(!(!ie||cn)){cn=!0;try{V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-h.startedAt.getTime(),error:p?.error||(D.signal.aborted?Pe(D.signal).message:"run ended before completion"),errorKind:p?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,stopped:!this.interruptedRuns.has(h.id)&&(this.stoppedRuns.has(h.id)||p?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ws=!1,bs=p=>{if(ws)return;ws=!0,ys(p),this.runReleases.delete(h.id),x&&clearTimeout(x),E(),d.activeTasks--;let f=d.runningTasks.findIndex(I=>I.id===h.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id);let k=this.runEndWaiters.get(h.id);this.runEndWaiters.delete(h.id);for(let I of k??[])try{I()}catch{}A.done=!0,A.endedAt=new Date;for(let I of A.subscribers)try{I(`
165
165
  [task finished]
166
- `)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),dp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!p?.error,error:p?.error,...this.stoppedRuns.has(h.id)||p?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:p?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,bs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:pd,selectRequestContext:fd}=await import("./request-planner-7JLFVL6Y.js"),xs=te("request-gate",()=>pd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),un=!1;xs.then(()=>{un=!0},()=>{un=!0});let S=l,ln=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Ge=ea(this.config.session,w,d.def.tier),pt=ta(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&pt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let ft=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let md=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(p=>p.role==="agent")?.content;Aa({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:md,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,ln,e.message);let Ss=Date.now(),Is={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ss).toISOString(),taskId:M,resumeOrigin:gi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:In(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:tr(e.context),operator:nr(e.context),dueAt:Ca(e.context),taskType:rn(e.context)};V().emit("task:started",Is),ie=!0;let ne,gn,Ts=this.classifier;if(Ts&&w!=="a2a"&&!ue){ee("classify");let p=Date.now();gn=Ts.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",p,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",p,"error")})}let ks=async p=>{if(!gn)return;let f;await Promise.race([gn,new Promise(k=>{f=setTimeout(k,p),f.unref?.()})]),f&&clearTimeout(f)};await ks(Zg);let Te=this.config.workflows?.matching,he,vs,$s=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&$s?.enabled&&($s.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(vs=Kr(f.workflow))}catch(p){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${p?.message||p}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ke=Jr(this.config.workflows,e.agentId)&&zr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(p){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${p?.message||p}`)}let ae=ke?sp():void 0,hd=ae?Qr(ae):void 0,yd=this.wikiHub.getAgentWiki(e.agentId),As=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Cs=this.memoryStore.buildContext(As),Ms=this.memoryStore.contextFacts(As),wd=this.patternStore.findRelevant(e.message,e.agentId,5),bd=this.patternStore.buildContext(wd),Rs="";if(!ue)try{let{loadLocalSkills:p,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>p(d.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;Rs=f(B,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,ft)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let p=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let p=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let p=this.config.session?.resumeGate;if(p&&p.mode!=="off"){let f=wo({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:ft??0},p);if(f.rotate&&p.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${_n(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else p.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${_n(f)}`)}}if(H&&d.def.tier==="claude-code"){let p=H;await te("rotate",()=>this.maybeRotateForContinuity(e,d,w,S,p),()=>!1)&&(H=void 0)}try{let p=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(p.compacted){let f=p.qualityScore??"?",k=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let I=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let xd=process.env.AGENTX_CONTEXT_SURGERY==="1",Sd=ue?{maxMessages:8,maxChars:2400}:xd&&id(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Id=!H&&!ue?hp(yd,e.agentId,{notesInbox:mp(this.config)}):void 0,mt=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,Sd):void 0,Td=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,_s,Ps=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let p=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ns(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){_s=ss(f),Ps=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=mt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${mt.length}c/${mt.split(`
167
- `).length}L`,G=`[${e.agentId}] ${w}:${S} ${B} | session.messages=${f.length}`+(f.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(p){Ae.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let Es;if(d.def.contextReferences&&!H)try{let p=d.def.workspace,f=this.referencesCache.get(p);if(!f){let[I,B]=await R("references",()=>Promise.all([$n(d.def.workspace),An(d.def.workspace)]));if(I.byId.size===0&&B.recipes.length===0){let[G,Q]=await R("references",()=>Promise.all([$n(process.cwd()),An(process.cwd())]));f={refs:G,recipes:Q}}else f={refs:I,recipes:B};this.referencesCache.set(p,f)}let k=Er({agentId:e.agentId,intentTags:ne?.path,message:e.message},f.recipes,f.refs);k.cards.length>0&&(Es=_r(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let Ds=le||Ke?"":this.sessions.getCrossSessionSummary(e.agentId,w,S,e.message),Os,ht=le?null:ri(e.message);if(ht)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:S,lookbackDays:ht.lookbackDays,limit:12});if(p.turns.length>0){let f=[`[Long-memory recall \u2014 last ${ht.lookbackDays}d on this chat (cue-triggered)]`],k=[...p.turns].sort((I,B)=>I.ts.localeCompare(B.ts));for(let I of k){let B=I.ts.slice(11,16)+" "+I.day,G=I.role==="user"?I.senderName||"User":I.senderName||"Agent";f.push(`${B} ${G}: ${I.content}`)}p.hasMore&&f.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Os=f.join(`
168
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${ht.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let kd=ue?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Ls,Ns,Fs=!1;un||ee("request-gate");let ve=await xs;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),kd==="planner"&&!le&&!ve.active&&!Ke&&w!=="voice"&&w!=="desktop"){try{let{planContext:p}=await import("./context-planner-CVCRW5TV.js"),f=await R("plan-context",()=>p({agentId:e.agentId,channel:w,chatId:S,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Fs=!0,Ls=f.sessionHistory,Cs=f.memoryContext,Ms=f.memoryFacts,Ds=f.crossChatContext,Ns=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Fs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,S),H=void 0)}let pn=`${e.agentId}:${w}:${S}`,yt=yr(e.message);yt&&(yt==="default"?(this.activeSouls.delete(pn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(pn,yt),this.log(`[${e.agentId}] Soul switched to: ${yt}`)));let vd=this.activeSouls.get(pn),$d=mr(d.def.workspace,vd),Ad=hr($d),Cd=le?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Md=ap(d.def.tier),Rd=xp(d.def.richMessages,w),_d=d.def.tier==="claude-code"&&(le||Ge!=="lean"||na(pt)),Us="";if(d.def.workspace&&!_d){let p=K(d.def.workspace,"CLAUDE.md");if(ce(p))try{let f=lt(p,"utf-8");Us=`[Project CLAUDE.md]
166
+ `)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),cp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!p?.error,error:p?.error,...this.stoppedRuns.has(h.id)||p?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:p?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,bs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:fd,selectRequestContext:md}=await import("./request-planner-7JLFVL6Y.js"),xs=te("request-gate",()=>fd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),un=!1;xs.then(()=>{un=!0},()=>{un=!0});let S=l,ln=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Ge=ta(this.config.session,w,d.def.tier),pt=na(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&pt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let ft=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let hd=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(p=>p.role==="agent")?.content;Ca({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:hd,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,ln,e.message);let Ss=Date.now(),Is={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ss).toISOString(),taskId:M,resumeOrigin:pi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:In(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:tr(e.context),operator:nr(e.context),dueAt:Ma(e.context),taskType:rn(e.context)};V().emit("task:started",Is),ie=!0;let ne,gn,Ts=this.classifier;if(Ts&&w!=="a2a"&&!ue){ee("classify");let p=Date.now();gn=Ts.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",p,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",p,"error")})}let ks=async p=>{if(!gn)return;let f;await Promise.race([gn,new Promise(k=>{f=setTimeout(k,p),f.unref?.()})]),f&&clearTimeout(f)};await ks(Vg);let Te=this.config.workflows?.matching,he,vs,$s=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&$s?.enabled&&($s.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(vs=Jr(f.workflow))}catch(p){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${p?.message||p}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ke=zr(this.config.workflows,e.agentId)&&Qr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let p=new Et({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},p.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(p){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${p?.message||p}`)}let ae=ke?rp():void 0,yd=ae?Xr(ae):void 0,wd=this.wikiHub.getAgentWiki(e.agentId),As=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Cs=this.memoryStore.buildContext(As),Ms=this.memoryStore.contextFacts(As),bd=this.patternStore.findRelevant(e.message,e.agentId,5),xd=this.patternStore.buildContext(bd),Rs="";if(!ue)try{let{loadLocalSkills:p,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>p(d.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;Rs=f(B,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,ft)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let p=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let p=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let p=this.config.session?.resumeGate;if(p&&p.mode!=="off"){let f=bo({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:ft??0},p);if(f.rotate&&p.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${_n(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else p.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${_n(f)}`)}}if(H&&d.def.tier==="claude-code"){let p=H;await te("rotate",()=>this.maybeRotateForContinuity(e,d,w,S,p),()=>!1)&&(H=void 0)}try{let p=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(p.compacted){let f=p.qualityScore??"?",k=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let I=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let Sd=process.env.AGENTX_CONTEXT_SURGERY==="1",Id=ue?{maxMessages:8,maxChars:2400}:Sd&&ad(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Td=!H&&!ue?yp(wd,e.agentId,{notesInbox:hp(this.config)}):void 0,mt=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,Id):void 0,kd=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,_s,Ps=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let p=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ns(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){_s=ss(f),Ps=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=mt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${mt.length}c/${mt.split(`
167
+ `).length}L`,G=`[${e.agentId}] ${w}:${S} ${B} | session.messages=${f.length}`+(f.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(p){Ae.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let Es;if(d.def.contextReferences&&!H)try{let p=d.def.workspace,f=this.referencesCache.get(p);if(!f){let[I,B]=await R("references",()=>Promise.all([$n(d.def.workspace),An(d.def.workspace)]));if(I.byId.size===0&&B.recipes.length===0){let[G,Q]=await R("references",()=>Promise.all([$n(process.cwd()),An(process.cwd())]));f={refs:G,recipes:Q}}else f={refs:I,recipes:B};this.referencesCache.set(p,f)}let k=Er({agentId:e.agentId,intentTags:ne?.path,message:e.message},f.recipes,f.refs);k.cards.length>0&&(Es=_r(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let Ds=le||Ke?"":this.sessions.getCrossSessionSummary(e.agentId,w,S,e.message),Os,ht=le?null:oi(e.message);if(ht)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:S,lookbackDays:ht.lookbackDays,limit:12});if(p.turns.length>0){let f=[`[Long-memory recall \u2014 last ${ht.lookbackDays}d on this chat (cue-triggered)]`],k=[...p.turns].sort((I,B)=>I.ts.localeCompare(B.ts));for(let I of k){let B=I.ts.slice(11,16)+" "+I.day,G=I.role==="user"?I.senderName||"User":I.senderName||"Agent";f.push(`${B} ${G}: ${I.content}`)}p.hasMore&&f.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Os=f.join(`
168
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${ht.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let vd=ue?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Ls,Ns,Fs=!1;un||ee("request-gate");let ve=await xs;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),vd==="planner"&&!le&&!ve.active&&!Ke&&w!=="voice"&&w!=="desktop"){try{let{planContext:p}=await import("./context-planner-CVCRW5TV.js"),f=await R("plan-context",()=>p({agentId:e.agentId,channel:w,chatId:S,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Fs=!0,Ls=f.sessionHistory,Cs=f.memoryContext,Ms=f.memoryFacts,Ds=f.crossChatContext,Ns=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Fs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,S),H=void 0)}let pn=`${e.agentId}:${w}:${S}`,yt=yr(e.message);yt&&(yt==="default"?(this.activeSouls.delete(pn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(pn,yt),this.log(`[${e.agentId}] Soul switched to: ${yt}`)));let $d=this.activeSouls.get(pn),Ad=mr(d.def.workspace,$d),Cd=hr(Ad),Md=le?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Rd=dp(d.def.tier),_d=Sp(d.def.richMessages,w),Pd=d.def.tier==="claude-code"&&(le||Ge!=="lean"||sa(pt)),Us="";if(d.def.workspace&&!Pd){let p=K(d.def.workspace,"CLAUDE.md");if(ce(p))try{let f=lt(p,"utf-8");Us=`[Project CLAUDE.md]
169
169
  ${f.length>4e3?f.slice(0,4e3)+`
170
170
 
171
171
  [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let wt=e.context?.runbookPath,fn=[];if(wt&&ce(wt)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,k=4e3,I=16e3;for(let B of p){if(f>=I)break;let G=K(wt,B);if(ce(G))try{let Q=lt(G,"utf-8"),$e=Q.length>k?Q.slice(0,k)+`
172
172
 
173
173
  [${B} truncated to ${k} bytes]`:Q;fn.push(`[Project Runbook \u2014 ${B} from ${wt}]
174
- ${$e}`),f+=$e.length}catch{}}}let Pd=fn.length>0?fn.join(`
174
+ ${$e}`),f+=$e.length}catch{}}}let Ed=fn.length>0?fn.join(`
175
175
 
176
- `):"",mn=[d.def.systemPrompt||"",Md,Rd,Us,Pd,Ad||"",Cd||""].filter(p=>p.trim().length>0).join(`
176
+ `):"",mn=[d.def.systemPrompt||"",Rd,_d,Us,Ed,Cd||"",Md||""].filter(p=>p.trim().length>0).join(`
177
177
 
178
- `)||void 0,bt={channel:w,chatId:S,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:ln,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ke||id(w,d.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:ue?void 0:bd||void 0,procedureContext:[_s,vs].filter(Boolean).join(`
178
+ `)||void 0,bt={channel:w,chatId:S,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:ln,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ke||ad(w,d.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:ue?void 0:xd||void 0,procedureContext:[_s,vs].filter(Boolean).join(`
179
179
 
180
- `)||void 0,workflowRunContext:hd,references:Es,skillInjection:Rs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ls??mt,memoryContext:Cs||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Os||void 0,contextOnDemand:Ke&&!H?da(w,S):void 0,wikiContext:Id,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Is)}catch{return}})(),rotationMemo:Td,eventDigest:H?void 0:fp(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let p=ro(w,!H,d.def.richMessages);return p?yp(d.def.workspace,p):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(bt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let xt=e.model?void 0:lr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?ft:null});xt?.downgraded&&this.log(`[${e.agentId}] ${xt.reason}`);let Hs=ur(d.def.tier,this.config.decisions.routing),js=xt?.downgraded?Promise.resolve(xt.model):!e.model&&Hs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:p}=await import("./routing-ZSGWR6ID.js"),f=await R("route-model",()=>p({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?ft:null,cheapModel:Hs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Bs=!1;js.then(()=>{Bs=!0});let St=ve.active&&ve.preprocess?await te("select-context",()=>fd(bt),()=>({input:bt,excluded:[]})):{input:bt,excluded:[]};St.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${St.excluded.join(", ")}`);let It=li(St.input,ue?{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),Ed=Ar(It,{memory:Ms,procedures:Ps,wikiContext:St.input.wikiContext}),hn=(It?.length??0)+(mn?.length??0)+(e.message?.length??0),Tt={history:It?.length??0,sysPrompt:mn?.length??0,message:e.message?.length??0},Ws=Ki(e.agentId,w,S);Ji(Ws,hn,Tt);let qs=zi(Ws);qs&&this.log(`[${e.agentId}] ${qs}`),hn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${S}: ${hn} bytes (history=${Tt.history}, sysPrompt=${Tt.sysPrompt}, message=${Tt.message})`),Bs||ee("route-model");let Gs=await js,Ks=d.def.tier!=="claude-code"?void 0:le?oa():Ge==="lean"?ra(d.def.workspace,pt,void 0,w):aa(d.def.workspace);Ge==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${ca(Ge,pt,w)}`);let Js=d.def.tier==="claude-code"&&!H?ho({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:M},p=>this.log(p)):void 0,Dd={...e,systemPromptAppend:mn,...Ks?{claudeArgs:Ks}:{},...Gs?{model:Gs}:{}},se,zs=ka({agent:e.agentId,request:e.message,taskId:M,budgetMinutes:d.def.maxExecutionMinutes??20}),Od=v,Qs=!1,yn=!0;v=p=>{if(zs.observe(p),ae&&yn)for(let f of Yr(p))Xr(f.name,f.input)||(yn=!1);Od?.(p)};try{let p=this.workflowAutoRunner;if(he&&p){let O=he;try{let z=await R("workflow-auto-run",()=>p({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:S,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:S,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${he.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:he.workflowId,workflowRunId:z.runId,workflowMatchConfidence:he.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ae&&ke)try{let O=Vr(ke,e.resumedFrom);Zr(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:S,message:e.message,taskId:M,...O?{continues:O}:{}}),Qs=!0,h.workflow={runId:ae,workflowId:Gr}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${O?.message||O}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;ee("dispatch-gate");let O=d.def.persistentProcess?Ut():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:S}),de=!!H||z,ge=[_i(de),qi(de,void 0,e.model||d.def.model)].find(At=>At&&At.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let At={content:"",error:ge.message,errorKind:"dispatch_hold",duration:0};if(!t){A.buffer=`[error] ${ge.message}`;for(let Fd of A.subscribers)try{Fd(A.buffer)}catch{}}return At}Li();let Je=Gi();return Je&&this.log(`[${e.agentId}] ${Je}`),null},k=Pt(e.agentId,void 0,_t(e.agentId,e.context?.chatId));if(k){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){A.buffer=`[error] ${k.message}`;for(let O of A.subscribers)try{O(A.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let I=this.planCloudSession(d.def,e);if(I.route==="local"){let O=f();if(O)return d.errors++,se=O,O}let B=d.def.tier==="claude-code",G=B?t:(O,z)=>{O&&_(O),t&&t(O,z)},Q=!1,$e=B?s:O=>{O&&(Q?_(O):(_(`\u{1F4AD} ${O}`),Q=!0)),s&&s(O)},ye=()=>{Q&&(_(`
181
- `),Q=!1)},Ld=B?G:G?(O,z)=>{ye(),G(O,z)}:void 0,$=await R("agent",async()=>{if(I.route!=="local"){let z=await this.runCloudSession(d.def,e,I,M);if(z)return z;let de=f();if(de)return de}let O=await this.inTaskWorktree(d.def,Dd);return ti(O.def,O.task,this.providers,Ld,It,O.fresh?void 0:H,v,D.signal,$e)},cp);if(!$.error){let O=wp(d.def.toolUseRequired,L);if(O){let z=Array.from(L.entries()).map(([de,$t])=>`${de}=${$t}`).join(", ")||"none";$.error=`tool_required_not_called: ${O} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}Js&&yo(Js,{toolUses:L,eventsSeen:q,error:$.error,agentId:e.agentId},O=>this.log(O));let kt=this.interruptedRuns.get(h.id);kt&&($.content="",$.error=kt,$.errorKind="interrupted");let wn=kt?void 0:this.stoppedRuns.get(h.id);wn&&($.content="",$.error=wn,$.errorKind="stopped"),se=$;let we=$.usage?vr($.usage):void 0,Nd=$.billedModel||e.model||d.def.model||void 0,vt=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,Nd,d.def.tier):void 0);if(cn=!0,V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:w,chatId:S,durationMs:Date.now()-Ss,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:kt?!0:void 0,stopped:wn?!0:void 0,inputTokens:we?.inputTokens,outputTokens:we?.outputTokens,cacheReadTokens:we?.cacheReadTokens,cacheCreateTokens:we?.cacheCreateTokens,tier2InputTokens:we?.tier2InputTokens,tier2OutputTokens:we?.tier2OutputTokens,tier2CacheReadTokens:we?.tier2CacheReadTokens,tier2CacheCreateTokens:we?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:$.numTurns,costUsd:vt!==void 0&&Number.isFinite(vt)&&vt>0?vt:void 0,injectedContext:Ed,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let O=$.error?`[error] ${$.error}`:$.content;A.buffer=O;for(let z of A.subscribers)try{z(O)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,S,$.content),$a({agent:e.agentId,channel:w,chatId:S,request:e.message,reply:$.content,taskId:M}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,S,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,S,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,S,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,S,$.usage,$.contextTokens),$.usage){let ge=$.contextTokens,Je=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ge??Je)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${S}: context=${ge??"n/a"} tokens (cumulative turn total=${Je}) \u2014 next turn will rotate`)}if(xr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await ks(Vg);try{let ge=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ge,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
180
+ `)||void 0,workflowRunContext:yd,references:Es,skillInjection:Rs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ls??mt,memoryContext:Cs||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Os||void 0,contextOnDemand:Ke&&!H?ca(w,S):void 0,wikiContext:Td,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Is)}catch{return}})(),rotationMemo:kd,eventDigest:H?void 0:mp(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let p=oo(w,!H,d.def.richMessages);return p?wp(d.def.workspace,p):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(bt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let xt=e.model?void 0:lr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?ft:null});xt?.downgraded&&this.log(`[${e.agentId}] ${xt.reason}`);let Hs=ur(d.def.tier,this.config.decisions.routing),js=xt?.downgraded?Promise.resolve(xt.model):!e.model&&Hs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:p}=await import("./routing-ZSGWR6ID.js"),f=await R("route-model",()=>p({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?ft:null,cheapModel:Hs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Bs=!1;js.then(()=>{Bs=!0});let St=ve.active&&ve.preprocess?await te("select-context",()=>md(bt),()=>({input:bt,excluded:[]})):{input:bt,excluded:[]};St.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${St.excluded.join(", ")}`);let It=gi(St.input,ue?{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),Dd=Ar(It,{memory:Ms,procedures:Ps,wikiContext:St.input.wikiContext}),hn=(It?.length??0)+(mn?.length??0)+(e.message?.length??0),Tt={history:It?.length??0,sysPrompt:mn?.length??0,message:e.message?.length??0},Ws=Ji(e.agentId,w,S);zi(Ws,hn,Tt);let qs=Qi(Ws);qs&&this.log(`[${e.agentId}] ${qs}`),hn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${S}: ${hn} bytes (history=${Tt.history}, sysPrompt=${Tt.sysPrompt}, message=${Tt.message})`),Bs||ee("route-model");let Gs=await js,Ks=d.def.tier!=="claude-code"?void 0:le?ia():Ge==="lean"?oa(d.def.workspace,pt,void 0,w):da(d.def.workspace);Ge==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${ua(Ge,pt,w)}`);let Js=d.def.tier==="claude-code"&&!H?yo({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:M},p=>this.log(p)):void 0,Od={...e,systemPromptAppend:mn,...Ks?{claudeArgs:Ks}:{},...Gs?{model:Gs}:{}},se,zs=va({agent:e.agentId,request:e.message,taskId:M,budgetMinutes:d.def.maxExecutionMinutes??20}),Ld=v,Qs=!1,yn=!0;v=p=>{if(zs.observe(p),ae&&yn)for(let f of Zr(p))Yr(f.name,f.input)||(yn=!1);Ld?.(p)};try{let p=this.workflowAutoRunner;if(he&&p){let O=he;try{let z=await R("workflow-auto-run",()=>p({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:S,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:S,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${he.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:he.workflowId,workflowRunId:z.runId,workflowMatchConfidence:he.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ae&&ke)try{let O=eo(ke,e.resumedFrom);Vr(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:S,message:e.message,taskId:M,...O?{continues:O}:{}}),Qs=!0,h.workflow={runId:ae,workflowId:Kr}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${O?.message||O}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;ee("dispatch-gate");let O=d.def.persistentProcess?Ut():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:S}),de=!!H||z,ge=[Pi(de),Gi(de,void 0,e.model||d.def.model)].find(At=>At&&At.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let At={content:"",error:ge.message,errorKind:"dispatch_hold",duration:0};if(!t){A.buffer=`[error] ${ge.message}`;for(let Ud of A.subscribers)try{Ud(A.buffer)}catch{}}return At}Ni();let Je=Ki();return Je&&this.log(`[${e.agentId}] ${Je}`),null},k=Pt(e.agentId,void 0,_t(e.agentId,e.context?.chatId));if(k){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){A.buffer=`[error] ${k.message}`;for(let O of A.subscribers)try{O(A.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let I=this.planCloudSession(d.def,e);if(I.route==="local"){let O=f();if(O)return d.errors++,se=O,O}let B=d.def.tier==="claude-code",G=B?t:(O,z)=>{O&&_(O),t&&t(O,z)},Q=!1,$e=B?s:O=>{O&&(Q?_(O):(_(`\u{1F4AD} ${O}`),Q=!0)),s&&s(O)},ye=()=>{Q&&(_(`
181
+ `),Q=!1)},Nd=B?G:G?(O,z)=>{ye(),G(O,z)}:void 0,$=await R("agent",async()=>{if(I.route!=="local"){let z=await this.runCloudSession(d.def,e,I,M);if(z)return z;let de=f();if(de)return de}let O=await this.inTaskWorktree(d.def,Od);return ni(O.def,O.task,this.providers,Nd,It,O.fresh?void 0:H,v,D.signal,$e)},up);if(!$.error){let O=bp(d.def.toolUseRequired,L);if(O){let z=Array.from(L.entries()).map(([de,$t])=>`${de}=${$t}`).join(", ")||"none";$.error=`tool_required_not_called: ${O} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}Js&&wo(Js,{toolUses:L,eventsSeen:q,error:$.error,agentId:e.agentId},O=>this.log(O));let kt=this.interruptedRuns.get(h.id);kt&&($.content="",$.error=kt,$.errorKind="interrupted");let wn=kt?void 0:this.stoppedRuns.get(h.id);wn&&($.content="",$.error=wn,$.errorKind="stopped"),se=$;let we=$.usage?vr($.usage):void 0,Fd=$.billedModel||e.model||d.def.model||void 0,vt=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,Fd,d.def.tier):void 0);if(cn=!0,V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:w,chatId:S,durationMs:Date.now()-Ss,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:kt?!0:void 0,stopped:wn?!0:void 0,inputTokens:we?.inputTokens,outputTokens:we?.outputTokens,cacheReadTokens:we?.cacheReadTokens,cacheCreateTokens:we?.cacheCreateTokens,tier2InputTokens:we?.tier2InputTokens,tier2OutputTokens:we?.tier2OutputTokens,tier2CacheReadTokens:we?.tier2CacheReadTokens,tier2CacheCreateTokens:we?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:$.numTurns,costUsd:vt!==void 0&&Number.isFinite(vt)&&vt>0?vt:void 0,injectedContext:Dd,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let O=$.error?`[error] ${$.error}`:$.content;A.buffer=O;for(let z of A.subscribers)try{z(O)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,S,$.content),Aa({agent:e.agentId,channel:w,chatId:S,request:e.message,reply:$.content,taskId:M}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,S,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,S,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,S,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,S,$.usage,$.contextTokens),$.usage){let ge=$.contextTokens,Je=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ge??Je)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${S}: context=${ge??"n/a"} tokens (cumulative turn total=${Je}) \u2014 next turn will rotate`)}if(xr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await ks(ep);try{let ge=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ge,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
182
182
 
183
- Agent: ${$.content}`,meta:pp(ne,e.context)})}catch{}Sr(e.agentId,e.message,$.content,{channel:w,chatId:S,sender:ln},this.memoryStore).catch(()=>{}),vi(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||d.def.model,de=e.context?.channel,$t=de&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${de}:${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,de,$t),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${J()}`)}return $}catch(p){d.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=Lt(p.message);return se={content:"",error:Nt(f),errorKind:f.kind},se}finally{if(zs.stop(),Qs&&ae&&ke)try{let p=se?.usage,f=eo(ke,ae,{error:se?se.error||void 0:D.signal.aborted?Pe(D.signal).message:"run ended before completion",canceled:to(se?.errorKind)||this.stoppedRuns.has(h.id)||this.interruptedRuns.has(h.id)||!se&&D.signal.aborted,durationMs:Date.now()-h.startedAt.getTime(),...p?{inputTokens:p.inputTokens,outputTokens:p.outputTokens}:{},readOnly:yn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(p){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${p?.message||p}`)}ys(se),bs(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:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:no(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),qe,this.safe(e.agentId),t);ce(s)||ep(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);np(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),qe,this.safe(e));if(!ce(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let g=K(a,l);if(ce(g))try{for(let m of me(g)){if(!m.endsWith(".json"))continue;let y=m.split("-")[0],b=parseInt(y,10);if(!Number.isFinite(b)||b<i||b>s)continue;let C=Math.floor((s-b)/36e5),h=t-1-C;h>=0&&h<t&&o[h]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),qe);if(!ce(e))return 0;let t=0;for(let s of me(e)){let r=K(e,s),o;try{o=me(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=me(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(lt(K(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=gp){let t=K(process.cwd(),qe);if(!ce(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of me(t)){let i=K(t,o),a;try{a=me(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{tp(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),qe,this.safe(e));if(!ce(s))return[];let r=me(s).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=K(s,i),c;try{c=me(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(lt(K(a,d),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),qe,this.safe(e));if(!ce(s))return null;let r=this.safe(t),o=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ce(a))try{return JSON.parse(lt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Pt(t,void 0,_t(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Mn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Ye(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){op.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Kt(a);return c.channel===t.channel&&c.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,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let g=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:g,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let m=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(g).toISOString(),sender:{name:s},humanRoot:!1,person:sr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:g});let y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=g=>{u||(u=!0,d(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{Ye(g.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?l({ok:!1,status:500,error:g.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>l({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function xp(n,e){return n===!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(`
184
- `)}export{To as a,Op as b,vo as c,nc as d,$o as e,Ht as f,zp as g,Zp as h,Vp as i,rf as j,Kt as k,Tc as l,Zo as m,Cc as n,Mc as o,Rc as p,ti as q,zt as r,Qt as s,Zc as t,Ef as u,Df as v,Lf as w,Yt as x,Uf as y,zn as z,V as A,$i as B,hu as C,xu as D,Mi as E,tm as F,Ri as G,Di as H,Hi as I,mm as J,ji as K,en as L,Tm as M,km as N,at as O,_l as P,Pl as Q,El as R,Dl as S,Ol as T,ns as U,rn as V,eh as W,Oa as X,ct as Y,La as Z,ah as _,dh as $,ch as aa,uh as ba,lh as ca,gh as da,ph as ea,lg as fa,ip as ga,ap as ha,By as ia,Wy as ja,lp as ka,pp as la,fp as ma,hp as na,hs as oa,dd as pa,cd as qa,wp as ra,ud as sa,ld as ta,xp as ua};
185
- //# sourceMappingURL=chunk-FBNU7MMW.js.map
183
+ Agent: ${$.content}`,meta:fp(ne,e.context)})}catch{}Sr(e.agentId,e.message,$.content,{channel:w,chatId:S,sender:ln},this.memoryStore).catch(()=>{}),$i(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||d.def.model,de=e.context?.channel,$t=de&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${de}:${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,de,$t),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${J()}`)}return $}catch(p){d.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=Lt(p.message);return se={content:"",error:Nt(f),errorKind:f.kind},se}finally{if(zs.stop(),Qs&&ae&&ke)try{let p=se?.usage,f=to(ke,ae,{error:se?se.error||void 0:D.signal.aborted?Pe(D.signal).message:"run ended before completion",canceled:no(se?.errorKind)||this.stoppedRuns.has(h.id)||this.interruptedRuns.has(h.id)||!se&&D.signal.aborted,durationMs:Date.now()-h.startedAt.getTime(),...p?{inputTokens:p.inputTokens,outputTokens:p.outputTokens}:{},readOnly:yn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(p){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${p?.message||p}`)}ys(se),bs(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:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:so(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),qe,this.safe(e.agentId),t);ce(s)||tp(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);sp(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),qe,this.safe(e));if(!ce(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let g=K(a,l);if(ce(g))try{for(let m of me(g)){if(!m.endsWith(".json"))continue;let y=m.split("-")[0],b=parseInt(y,10);if(!Number.isFinite(b)||b<i||b>s)continue;let C=Math.floor((s-b)/36e5),h=t-1-C;h>=0&&h<t&&o[h]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),qe);if(!ce(e))return 0;let t=0;for(let s of me(e)){let r=K(e,s),o;try{o=me(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=me(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(lt(K(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=pp){let t=K(process.cwd(),qe);if(!ce(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of me(t)){let i=K(t,o),a;try{a=me(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{np(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),qe,this.safe(e));if(!ce(s))return[];let r=me(s).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=K(s,i),c;try{c=me(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(lt(K(a,d),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),qe,this.safe(e));if(!ce(s))return null;let r=this.safe(t),o=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ce(a))try{return JSON.parse(lt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Pt(t,void 0,_t(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Mn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Ye(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){ip.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Kt(a);return c.channel===t.channel&&c.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,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let g=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:g,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let m=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(g).toISOString(),sender:{name:s},humanRoot:!1,person:sr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:g});let y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=g=>{u||(u=!0,d(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{Ye(g.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?l({ok:!1,status:500,error:g.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>l({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Sp(n,e){return n===!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(`
184
+ `)}export{ko as a,Lp as b,$o as c,sc as d,Ao as e,Ht as f,Qp as g,Vp as h,ef as i,of as j,Kt as k,kc as l,Vo as m,Mc as n,Rc as o,_c as p,ni as q,zt as r,Qt as s,Vc as t,Df as u,Of as v,Nf as w,Yt as x,Hf as y,zn as z,V as A,Ai as B,yu as C,Su as D,Ri as E,nm as F,_i as G,Oi as H,ji as I,hm as J,Bi as K,en as L,km as M,vm as N,at as O,Pl as P,El as Q,Dl as R,Ol as S,Ll as T,ns as U,rn as V,th as W,La as X,ct as Y,Na as Z,dh as _,ch as $,uh as aa,lh as ba,gh as ca,ph as da,fh as ea,gg as fa,ap as ga,dp as ha,Wy as ia,qy as ja,gp as ka,fp as la,mp as ma,yp as na,hs as oa,cd as pa,ud as qa,bp as ra,ld as sa,gd as ta,Sp as ua};
185
+ //# sourceMappingURL=chunk-MH55YCUS.js.map