agentix-cli 0.50.1 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +67 -14
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +20 -3
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +24 -31
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +16 -2
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +173 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +62 -15
- package/dist/{App-TDUUFVDV.js → App-QVNQ5BQK.js} +2 -2
- package/dist/{ChatApp-IOWDXM3R.js → ChatApp-CC57XC23.js} +2 -2
- package/dist/{agent-KRLAT3YJ.js → agent-ILH6ANOM.js} +2 -2
- package/dist/{board-dashboard-VA4VSCMQ.js → board-dashboard-WG4ZZV4A.js} +346 -137
- package/dist/board-dashboard-WG4ZZV4A.js.map +1 -0
- package/dist/{chunk-ZWGRRFJI.js → chunk-2KQTE4XI.js} +2 -2
- package/dist/{chunk-A6IV2VQY.js → chunk-6HAZ6YWI.js} +2 -2
- package/dist/{chunk-WUDXUY7H.js → chunk-BNVF66YL.js} +3 -3
- package/dist/chunk-BNVF66YL.js.map +1 -0
- package/dist/{chunk-HHY3MSMN.js → chunk-CAA546XN.js} +2 -2
- package/dist/{chunk-X5K3HR4V.js → chunk-F7WY24UZ.js} +2 -2
- package/dist/{chunk-7WDJW37G.js → chunk-GUJB53QU.js} +2 -2
- package/dist/{chunk-FDYGTQVW.js → chunk-H2TWRZC2.js} +2 -2
- package/dist/{chunk-F2PEUQW4.js → chunk-JQR3NTHI.js} +2 -2
- package/dist/{chunk-4BNQSUWV.js → chunk-KAFO5QZR.js} +2 -2
- package/dist/{chunk-ZQSB6IX4.js → chunk-KFALP5NO.js} +2 -2
- package/dist/{chunk-RP7GLXOA.js → chunk-NTG5ZXRI.js} +180 -179
- package/dist/chunk-NTG5ZXRI.js.map +1 -0
- package/dist/{chunk-2BRX2EMT.js → chunk-PSDCRZZM.js} +2 -2
- package/dist/{chunk-BVRUDRCM.js → chunk-QP6XNTBB.js} +2 -2
- package/dist/{chunk-AVJRATR5.js → chunk-ROCUOXCW.js} +2 -2
- package/dist/{chunk-FULEQYM6.js → chunk-S7CVSKOX.js} +2 -2
- package/dist/chunk-S7CVSKOX.js.map +1 -0
- package/dist/{chunk-XSFXAJDA.js → chunk-SRCXUZM2.js} +4 -4
- package/dist/{chunk-XSFXAJDA.js.map → chunk-SRCXUZM2.js.map} +1 -1
- package/dist/chunk-U67EG5IF.js +19 -0
- package/dist/chunk-U67EG5IF.js.map +1 -0
- package/dist/{chunk-JWLTI6NZ.js → chunk-UL4E2CV4.js} +163 -160
- package/dist/chunk-UL4E2CV4.js.map +1 -0
- package/dist/chunk-V7XZN3MQ.js +123 -0
- package/dist/chunk-V7XZN3MQ.js.map +1 -0
- package/dist/{chunk-WW6KNRIR.js → chunk-VMS3HVTT.js} +2 -2
- package/dist/{chunk-5KCOH5FQ.js → chunk-WDQ3BPFS.js} +2 -2
- package/dist/{chunk-ZN7637EF.js → chunk-XZTR5MBJ.js} +2 -2
- package/dist/chunk-YE2BUU3Z.js +28 -0
- package/dist/chunk-YE2BUU3Z.js.map +1 -0
- package/dist/{chunk-ZKDWQJVS.js → chunk-YEV6W34S.js} +55 -55
- package/dist/{chunk-ZKDWQJVS.js.map → chunk-YEV6W34S.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/client-I7GAAM3T.js +2 -0
- package/dist/{config-I4GWI22T.js → config-TVW7UCKG.js} +2 -2
- package/dist/config-mutator-JHM53P5A.js +2 -0
- package/dist/doctor-CXFMV6PT.js +2 -0
- package/dist/index.d.ts +256 -6
- package/dist/index.js +1 -1
- package/dist/processes-NNXSRQSV.js +2 -0
- package/dist/program-UXJWH5JG.js +2 -0
- package/dist/{promote-EDEG2HQR.js → promote-4T64VW5K.js} +2 -2
- package/dist/query-6IKL52WT.js +2 -0
- package/dist/registry-E4QUXHMQ.js +2 -0
- package/dist/{request-planner-JDBXFNQ4.js → request-planner-BRLDCYU5.js} +2 -2
- package/dist/{review-candidates-EBP5CFOB.js → review-candidates-QWW5PDUU.js} +2 -2
- package/dist/{routing-Q2EOZ3VW.js → routing-DP6S7OJL.js} +2 -2
- package/dist/schedule-tool-TPJ6GR47.js +2 -0
- package/dist/scheduler-7QPG6OTY.js +2 -0
- package/dist/{seat-LV3STEXI.js → seat-3KUNRM5Z.js} +2 -2
- package/dist/{select-5NHY4T5A.js → select-ILXHYJGD.js} +2 -2
- package/dist/{tool-2RKPJWDG.js → tool-SF3BCY55.js} +2 -2
- package/dist/wiki-WETANN3W.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-VA4VSCMQ.js.map +0 -1
- package/dist/chunk-FULEQYM6.js.map +0 -1
- package/dist/chunk-JUJ3TCOE.js +0 -19
- package/dist/chunk-JUJ3TCOE.js.map +0 -1
- package/dist/chunk-JWLTI6NZ.js.map +0 -1
- package/dist/chunk-JY7POTMB.js +0 -123
- package/dist/chunk-JY7POTMB.js.map +0 -1
- package/dist/chunk-KH6L7GDO.js +0 -28
- package/dist/chunk-KH6L7GDO.js.map +0 -1
- package/dist/chunk-RP7GLXOA.js.map +0 -1
- package/dist/chunk-WUDXUY7H.js.map +0 -1
- package/dist/client-PC7OEKSK.js +0 -2
- package/dist/config-mutator-3RFKH3OV.js +0 -2
- package/dist/doctor-OG6DK52Y.js +0 -2
- package/dist/processes-CMTMB7LG.js +0 -2
- package/dist/program-RFAHI4SS.js +0 -2
- package/dist/query-P5LMGXVS.js +0 -2
- package/dist/registry-GJLY5J5E.js +0 -2
- package/dist/schedule-tool-N2Z5E6AR.js +0 -2
- package/dist/scheduler-WTPERNYJ.js +0 -2
- package/dist/wiki-XQMJ2FPU.js +0 -2
- /package/dist/{App-TDUUFVDV.js.map → App-QVNQ5BQK.js.map} +0 -0
- /package/dist/{ChatApp-IOWDXM3R.js.map → ChatApp-CC57XC23.js.map} +0 -0
- /package/dist/{agent-KRLAT3YJ.js.map → agent-ILH6ANOM.js.map} +0 -0
- /package/dist/{chunk-ZWGRRFJI.js.map → chunk-2KQTE4XI.js.map} +0 -0
- /package/dist/{chunk-A6IV2VQY.js.map → chunk-6HAZ6YWI.js.map} +0 -0
- /package/dist/{chunk-HHY3MSMN.js.map → chunk-CAA546XN.js.map} +0 -0
- /package/dist/{chunk-X5K3HR4V.js.map → chunk-F7WY24UZ.js.map} +0 -0
- /package/dist/{chunk-7WDJW37G.js.map → chunk-GUJB53QU.js.map} +0 -0
- /package/dist/{chunk-FDYGTQVW.js.map → chunk-H2TWRZC2.js.map} +0 -0
- /package/dist/{chunk-F2PEUQW4.js.map → chunk-JQR3NTHI.js.map} +0 -0
- /package/dist/{chunk-4BNQSUWV.js.map → chunk-KAFO5QZR.js.map} +0 -0
- /package/dist/{chunk-ZQSB6IX4.js.map → chunk-KFALP5NO.js.map} +0 -0
- /package/dist/{chunk-2BRX2EMT.js.map → chunk-PSDCRZZM.js.map} +0 -0
- /package/dist/{chunk-BVRUDRCM.js.map → chunk-QP6XNTBB.js.map} +0 -0
- /package/dist/{chunk-AVJRATR5.js.map → chunk-ROCUOXCW.js.map} +0 -0
- /package/dist/{chunk-WW6KNRIR.js.map → chunk-VMS3HVTT.js.map} +0 -0
- /package/dist/{chunk-5KCOH5FQ.js.map → chunk-WDQ3BPFS.js.map} +0 -0
- /package/dist/{chunk-ZN7637EF.js.map → chunk-XZTR5MBJ.js.map} +0 -0
- /package/dist/{client-PC7OEKSK.js.map → client-I7GAAM3T.js.map} +0 -0
- /package/dist/{config-I4GWI22T.js.map → config-TVW7UCKG.js.map} +0 -0
- /package/dist/{config-mutator-3RFKH3OV.js.map → config-mutator-JHM53P5A.js.map} +0 -0
- /package/dist/{doctor-OG6DK52Y.js.map → doctor-CXFMV6PT.js.map} +0 -0
- /package/dist/{processes-CMTMB7LG.js.map → processes-NNXSRQSV.js.map} +0 -0
- /package/dist/{program-RFAHI4SS.js.map → program-UXJWH5JG.js.map} +0 -0
- /package/dist/{promote-EDEG2HQR.js.map → promote-4T64VW5K.js.map} +0 -0
- /package/dist/{query-P5LMGXVS.js.map → query-6IKL52WT.js.map} +0 -0
- /package/dist/{registry-GJLY5J5E.js.map → registry-E4QUXHMQ.js.map} +0 -0
- /package/dist/{request-planner-JDBXFNQ4.js.map → request-planner-BRLDCYU5.js.map} +0 -0
- /package/dist/{review-candidates-EBP5CFOB.js.map → review-candidates-QWW5PDUU.js.map} +0 -0
- /package/dist/{routing-Q2EOZ3VW.js.map → routing-DP6S7OJL.js.map} +0 -0
- /package/dist/{schedule-tool-N2Z5E6AR.js.map → schedule-tool-TPJ6GR47.js.map} +0 -0
- /package/dist/{scheduler-WTPERNYJ.js.map → scheduler-7QPG6OTY.js.map} +0 -0
- /package/dist/{seat-LV3STEXI.js.map → seat-3KUNRM5Z.js.map} +0 -0
- /package/dist/{select-5NHY4T5A.js.map → select-ILXHYJGD.js.map} +0 -0
- /package/dist/{tool-2RKPJWDG.js.map → tool-SF3BCY55.js.map} +0 -0
- /package/dist/{wiki-XQMJ2FPU.js.map → wiki-WETANN3W.js.map} +0 -0
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},St=class{constructor(e=eo,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=Vr("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[v])=>b.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new oe("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,v])=>!v.connection.busy);if(!b)throw new oe("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new It(e,this.launchProcess)}}catch{throw new oe("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="",u,l,d,g=!1,m=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let w=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((O,C)=>{i.failTurn=C,i.notify=(A,_)=>{if(_?.threadId!==l)return;let h=_.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:A.replace("/","."),...h?{item:{...h,type:D[h.type]||h.type}}:{}}),A==="item/completed"&&h?.type==="agentMessage"&&h.phase==="final_answer"&&(u=h.text),A==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),A==="thread/tokenUsage/updated"){let N=_.tokenUsage.last,L=N.cachedInputTokens||0;d={inputTokens:(d?.inputTokens||0)+Math.max(0,(N.inputTokens||0)-L),outputTokens:(d?.outputTokens||0)+(N.outputTokens||0),cacheReadTokens:(d?.cacheReadTokens||0)+L,cacheCreateTokens:(d?.cacheCreateTokens||0)+(N.cacheWriteInputTokens||0)}}A==="turn/completed"&&(_.turn.status==="completed"?O():C(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:u??c,codexSessionId:l,billedModel:e.model,usage:d,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new oe(b.message);return{content:c,codexSessionId:l,usage:d,error:b.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(w),e.signal?.removeEventListener("abort",m),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},zn=new St;import{execFile as ho}from"child_process";import{StringDecoder as Re}from"string_decoder";import{mkdtempSync as ds,readFileSync as us,rmSync as ls}from"fs";import{join as Ve}from"path";import{tmpdir as gs}from"os";function ze(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let u=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${u?` Resets ${u[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),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 Xe(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Xn=null;function Ye(){return Xn}function da(s){Xn=s}function Me(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var ye=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Yn=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Me(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 ye(`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 ye(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Me(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Me(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Me(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Me(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(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",u=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${u})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${u})`)}}}}}};import{spawn as to}from"child_process";import{existsSync as no,readFileSync as so}from"fs";import{resolve as ro}from"path";function oo(s){let e=ro(s,"CLAUDE.md");if(!no(e))return null;try{let t=so(e,"utf8");return $n(t)}catch{return null}}var io=20*60*1e3,ao=5e3,Pe=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Vn=class{constructor(e={}){this.opts=e}spawn(e,t){return new vt(e,t,this.opts)}},vt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=to(r,o,{cwd:t.workspace,env:$e({...process.env},t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:oo(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 u of c)u(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
|
-
`);let a=e.deadlineMs??
|
|
4
|
-
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};ft();import{resolve as
|
|
1
|
+
import{a as On,b as Nn,h as Gn,n as Jn}from"./chunk-U67EG5IF.js";import{a as bt}from"./chunk-N6EWZGIX.js";import{a as Dn}from"./chunk-WP6KLXTP.js";import{b as Ln}from"./chunk-DP7RTNDM.js";import{b as Hn,c as Un,d as Bn,e as Wn,h as Kn}from"./chunk-V7XZN3MQ.js";import{a as wt,b as Fn}from"./chunk-J3SOEFRE.js";import{a as xt,b as jn}from"./chunk-SIU6STB2.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as In}from"./chunk-H2TWRZC2.js";import{a as Sn,b as vn,c as Cn,d as An,f as $n}from"./chunk-DWADWDMU.js";import{a as Mn,b as Pn}from"./chunk-WKTFP3SK.js";import{a as En}from"./chunk-XZTR5MBJ.js";import{b as Rn,c as _n}from"./chunk-ROCUOXCW.js";import{a as Qe,c as $e}from"./chunk-2GIDVZ4H.js";import{q as xn,t as Tn,v as fe,w as kn}from"./chunk-JQR3NTHI.js";import{a as Ae,b as Je,f as yt}from"./chunk-72SZI2UW.js";import{a as he,b as ht}from"./chunk-FCPTN6NF.js";import{c as hn,d as fn}from"./chunk-QOYAX2FT.js";import{e as le}from"./chunk-DSYKYZMT.js";import{d as yn,e as se,f as bn,g as wn,h as ft}from"./chunk-SRCXUZM2.js";kn();yt();var Qn="session-continuity",zn={continues:Ae("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:Ae("Does the new request refer to something stated earlier in the conversation?")};function Xn(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Tt(s.message,1200),previousRequest:s.previousMessage?Tt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Tt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Yn(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Tt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as Qr,execFile as zr}from"node:child_process";import{createHash as Xr,randomBytes as Yr}from"node:crypto";import{createInterface as Vr}from"node:readline";import{promisify as Zr}from"node:util";var eo=Zr(zr),re=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},kt=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=eo("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new re("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Xr("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new re("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let g=[...this.entries].find(([,m])=>!m.busy);if(!g)throw new re("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:Yr(32).toString("hex")},l=Qr("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((g,m)=>{let w=Vr({input:l.stdout}),T=()=>I(new re("OpenCode server failed before dispatch",!0)),b=()=>I(new Error("task cancelled by operator")),v=setTimeout(T,15e3),I=D=>{clearTimeout(v),l.removeListener("exit",T),l.removeListener("error",T),e.signal?.removeEventListener("abort",b),w.close(),l.stdout.resume(),D?m(D):g()};l.once("exit",T),l.once("error",T),e.signal?.addEventListener("abort",b,{once:!0}),w.on("line",D=>{try{let C=new URL(JSON.parse(D).url);if(C.protocol!=="http:"||C.hostname!=="127.0.0.1"||!C.port||C.username||C.password)return;d.url=C.origin,I()}catch{}}),e.signal?.aborted&&b()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},Vn=new kt;import{execa as et}from"execa";import{spawn as to}from"node:child_process";import{createHash as no}from"node:crypto";import{createInterface as so}from"node:readline";var oe=class extends Error{},ro=s=>to("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),It=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),so({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
|
+
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},St=class{constructor(e=ro,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=no("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[v])=>b.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new oe("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,v])=>!v.connection.busy);if(!b)throw new oe("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new It(e,this.launchProcess)}}catch{throw new oe("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="",u,l,d,g=!1,m=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let w=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((D,C)=>{i.failTurn=C,i.notify=(A,_)=>{if(_?.threadId!==l)return;let h=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:A.replace("/","."),...h?{item:{...h,type:E[h.type]||h.type}}:{}}),A==="item/completed"&&h?.type==="agentMessage"&&h.phase==="final_answer"&&(u=h.text),A==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),A==="thread/tokenUsage/updated"){let N=_.tokenUsage.last,L=N.cachedInputTokens||0;d={inputTokens:(d?.inputTokens||0)+Math.max(0,(N.inputTokens||0)-L),outputTokens:(d?.outputTokens||0)+(N.outputTokens||0),cacheReadTokens:(d?.cacheReadTokens||0)+L,cacheCreateTokens:(d?.cacheCreateTokens||0)+(N.cacheWriteInputTokens||0)}}A==="turn/completed"&&(_.turn.status==="completed"?D():C(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:u??c,codexSessionId:l,billedModel:e.model,usage:d,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new oe(b.message);return{content:c,codexSessionId:l,usage:d,error:b.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(w),e.signal?.removeEventListener("abort",m),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Zn=new St;import{execFile as wo}from"child_process";import{StringDecoder as Re}from"string_decoder";import{mkdtempSync as ps,readFileSync as ms,rmSync as hs}from"fs";import{join as Ve}from"path";import{tmpdir as fs}from"os";function ze(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let u=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${u?` Resets ${u[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),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 Xe(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var es=null;function Ye(){return es}function ma(s){es=s}function Me(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var ye=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},ts=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Me(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 ye(`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 ye(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Me(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Me(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Me(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Me(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(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",u=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${u})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${u})`)}}}}}};import{spawn as oo}from"child_process";import{existsSync as io,readFileSync as ao}from"fs";import{resolve as co}from"path";function uo(s){let e=co(s,"CLAUDE.md");if(!io(e))return null;try{let t=ao(e,"utf8");return $n(t)}catch{return null}}var lo=20*60*1e3,go=5e3,Pe=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},ns=class{constructor(e={}){this.opts=e}spawn(e,t){return new vt(e,t,this.opts)}},vt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=oo(r,o,{cwd:t.workspace,env:$e({...process.env},t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:uo(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 u of c)u(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
|
+
`);let a=e.deadlineMs??lo,c=o+a,u=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Pe(a));try{for(;;){let l=c-Date.now();if(l<=0)throw u();let d=await this.nextEvent(l);if(d===null&&!this.exited)throw u();if(d===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:d.type,raw:d},d.type==="result"){this.onResultEvent(d);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},go);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
|
+
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};ft();import{resolve as ss,join as rs}from"path";ht();var po=4e3;function os(s){try{let e=rs(ss(s.root),".agentx","db.sqlite"),t=bt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=he(),r=s.input.command?s.input.command.slice(0,po):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
5
5
|
(id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
|
|
6
6
|
verdict, effective_action, mode, severity, approver, ms)
|
|
7
7
|
VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
|
|
8
8
|
@verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:n,ts:Date.now(),agent_id:s.input.agentId??null,task_id:s.taskId??null,tool:s.input.tool,command:r,resolved_target:s.verdict.resolvedTarget,matched_rule:s.verdict.ruleId,verdict:s.verdict.action,effective_action:s.verdict.effectiveAction,mode:s.mode,severity:s.verdict.severity,approver:s.approver??null,ms:s.ms??null}),n}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
|
|
9
|
-
`),null}}function
|
|
10
|
-
`)}return{error:Xe(e),errorKind:e.kind}}function
|
|
9
|
+
`),null}}function Ca(s){let e=rs(ss(s.root),".agentx","db.sqlite"),t=bt({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}ft();var mo=50,ho=6*60*60*1e3,Ct=null,be=new Map;function Pa(s){Ct=s===null?null:String(s)}function fo(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function as(s,e,t){if(!se(s))return{args:[]};if(!Ct)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:fo(Ct,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function cs(s,e){return!se(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function yo(s){for(let[e,t]of be)s-t.at>ho&&be.delete(e)}function bo(s,e){let t=Date.now();yo(t);let n=be.get(s)??{at:t,blocks:[]};n.blocks.length<mo&&n.blocks.push(e),n.at=t,be.set(s,n)}function ds(s){if(!s)return[];let e=be.get(s);return be.delete(s),e?.blocks??[]}function is(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Ra(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let o=yn.safeParse(e.level),i=o.success?bn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",u=i.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:c,reason:u},d={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:u,resolvedTarget:null};return os({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:d,mode:"enforce",taskId:e.taskId??null}),e.taskId&&bo(e.taskId,l),{stdout:is(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${u} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(o){return{stdout:is(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}function q(s){let e=ze(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
10
|
+
`)}return{error:Xe(e),errorKind:e.kind}}function ys(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Ze(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function us(){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 ae(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let u=c.handle?` (mention: ${c.handle})`:"",l=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${u}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
|
|
11
11
|
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
12
|
-
`)}function
|
|
12
|
+
`)}function bs(s,e,t,n,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let c=r||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function At(s,e){return!e||e.trim().length===0?s:`[System]
|
|
13
13
|
${e.trim()}
|
|
14
14
|
|
|
15
15
|
[User]
|
|
16
|
-
${s}`}function
|
|
17
|
-
`))if(i.trim())try{let a=JSON.parse(i);t=Mt(a)||t,n=
|
|
18
|
-
`)}function
|
|
16
|
+
${s}`}function xo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s.model;return i&&o.push("--model",i),r&&o.push("--session",r),s.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(At(e,n)),o}function To(s){if(!s||typeof s!="object"||s.type!=="error")return;let e=s.error?.message??s.error??s.message??s.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function ls(s){return JSON.stringify(s)}function ws(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${ls(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(ls).join(",")}]`]}function xs(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...ws()),i||a.push("--color","never");let c=n||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(At(e,r)),a}function tt(s,e){let t=Qe(s.workspace),n=t.HOME||process.env.HOME,r=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),$t(t,e)}function $t(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(s.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function ko(s,e){let t=tt(s,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...n.mcp||{}};for(let[i,a]of Object.entries(s.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:r}),t}function Io(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function ie(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Mt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ie(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ie(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ie(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ie(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Mt(n,e+1);if(r)return r}}function Ts(s){if(!(!s||typeof s!="object"))return typeof s.model=="string"&&s.model||typeof s.msg?.model=="string"&&s.msg.model||typeof s.message?.model=="string"&&s.message.model||typeof s.response?.model=="string"&&s.response.model||void 0}function Pt(s,e=0){if(!(!s||typeof s!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=s[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[s.msg,s.message,s.response,s.result,s.item]){let n=Pt(t,e+1);if(n)return n}}}function So(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
|
|
17
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=Mt(a)||t,n=Ts(a)||n,r=Pt(a)||r,o=ks(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function ks(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return gs(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return gs(e)}}}function gs(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function vo(s){let e=s.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function Rt(s,e,t,n,r){let o=vo(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${s} via=${r} model=${i} perm=${o.summary}${a}
|
|
18
|
+
`)}function Co(s){try{let e=JSON.parse(s);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function Ao(s){try{let e=JSON.parse(s),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0}}catch{return{text:s}}}async function Is(s,e,t,n,r){let o=Date.now(),i=ae(s,e,t),a=vs(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=bs(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Rt(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let u;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:d,stderr:g,exitCode:m,killed:w}=await new Promise(v=>{let I=$e($t(Qe(s.workspace),e),s.billing),D=!1,C=wo("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...I,HOME:I.HOME||"/home/"+(I.USER||"user")}},(A,_,h)=>{v({stdout:_||"",stderr:h||"",exitCode:A?A.code??1:0,killed:D})});if(C.stdin?.end(),r){let A=()=>{D=!0,u=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{C.kill("SIGTERM")}catch{}setTimeout(()=>{try{C.killed||C.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?A():r.addEventListener("abort",A,{once:!0})}});if(w)return{content:"",error:u||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!d&&m!==0){let v;return m===143?v=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?v=ys():v=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...q(v),duration:Date.now()-o}}let T=Co(d);if(T)return{content:"",...q(T),duration:Date.now()-o};let b=Ao(d);return{content:b.text,duration:Date.now()-o,claudeSessionId:b.sessionId,usage:b.usage,numTurns:b.numTurns,billedModel:b.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function Ss(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ae(s,e,n),u=vs(e);if("error"in u)return{content:"",error:u.error,duration:Date.now()-a};let l=bs(s,c,!0,r,e.model,e.systemPromptAppend,u.args);Rt(e.agentId,s,e.model,r,"stream");let d="",g,m,w,T,b,v;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),D=$e($t(Qe(s.workspace),e),s.billing),C=et("claude",l,{cwd:s.workspace,timeout:I,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"}),A=!1,_;if(i){let x=()=>{A=!0,_=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{C.kill("SIGTERM")}catch{}setTimeout(()=>{try{C.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?x():i.addEventListener("abort",x,{once:!0})}let h="",E=new Re("utf8");C.stdout&&C.stdout.on("data",x=>{h+=E.write(x);let F=h.split(`
|
|
19
19
|
`);h=F.pop()||"";for(let S of F)if(S.trim())try{let y=JSON.parse(S);if(o)try{o(y)}catch{}if(y.type==="assistant"&&y.message?.usage){let k=y.message.usage,M=(k.input_tokens||0)+(k.cache_read_input_tokens||0)+(k.cache_creation_input_tokens||0);M>0&&(T=M)}if(y.type==="assistant"&&y.message?.content){for(let k of y.message.content)if(k.type==="text"&&k.text){let M=k.text.slice(d.length);M&&(d=k.text,t(M,d))}}if(y.type==="content_block_delta"&&y.delta?.text&&(d+=y.delta.text,t(y.delta.text,d)),y.type==="result"&&y.result){if(y.is_error&&typeof y.result=="string")v=y.result;else{let k=(typeof y.result=="string",y.result);if(typeof k=="string"&&k.length>d.length){let M=k.slice(d.length);d=k,M&&t(M,d)}}y.usage&&(m={inputTokens:y.usage.input_tokens||0,outputTokens:y.usage.output_tokens||0,cacheReadTokens:y.usage.cache_read_input_tokens||0,cacheCreateTokens:y.usage.cache_creation_input_tokens||0}),typeof y.model=="string"&&(g=y.model),typeof y.session_id=="string"&&(w=y.session_id),typeof y.num_turns=="number"&&(b=y.num_turns)}y.type==="system"&&y.subtype==="init"&&(typeof y.model=="string"&&(g=y.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${y.apiKeySource} version=${y.claude_code_version} model=${y.model} permMode=${y.permissionMode}
|
|
20
20
|
`))}catch{S.trim()&&!S.startsWith("{")&&(d+=S+`
|
|
21
21
|
`,t(S+`
|
|
22
|
-
`,d))}});let N=await C,L=
|
|
23
|
-
`);I=k.pop()||"";for(let M of k)if(M.trim())try{let H=JSON.parse(M);if(o)try{o(H)}catch{}g=Mt(H)||g,m=
|
|
22
|
+
`,d))}});let N=await C,L=E.end();if(L&&(h+=L),A)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!d&&N.stdout&&(d=typeof N.stdout=="string"?N.stdout:""),N.exitCode!==0&&!d){let x=typeof N.stderr=="string"?N.stderr:"",F=N,S;return F.timedOut?S=`Claude Code timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:F.signal?S=x.trim()||`Claude Code killed by signal ${F.signal}`:F.code==="ENOENT"||/ENOENT|spawn claude/i.test((F.shortMessage||"")+" "+x)?S=ys():S=x.trim()||`Claude Code exited with code ${F.exitCode??"unknown"}`,{content:"",...q(S),duration:Date.now()-a}}return v?{content:"",...q(v),duration:Date.now()-a,usage:m,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:w}:{content:d,duration:Date.now()-a,usage:m,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:w}}catch(I){return{content:d||"",...q(I.message),duration:Date.now()-a,usage:m,contextTokens:T,numTurns:b,billedModel:g,claudeSessionId:w}}}async function $o(s,e,t,n){let r=Date.now(),o=ae(s,e,t),i=ps(Ve(fs(),"agentx-codex-")),a=Ve(i,"last-message.txt"),c=xs(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let u=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await et("codex",c,{cwd:s.workspace,timeout:u,reject:!1,env:tt(s,e),extendEnv:!1,stdin:"ignore"}),d=So(l.stdout);if(l.exitCode!==0||d.apiError){let m=l,w;return m.timedOut?w=`Codex CLI timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:d.apiError?w=d.apiError:m.signal?w=l.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+l.stderr)?w=Ze():w=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...q(w),duration:Date.now()-r,usage:d.usage,billedModel:d.billedModel,codexSessionId:d.sessionId||n}}let g="";try{g=ms(a,"utf8").trim()}catch{}return g||(g=l.stdout.trim()),{content:g,duration:Date.now()-r,usage:d.usage,billedModel:d.billedModel,codexSessionId:d.sessionId||n}}catch(u){let l=/ENOENT|spawn codex/i.test(u?.message||"")?Ze():u?.message;return{content:"",...q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{hs(i,{recursive:!0,force:!0})}}async function Mo(s,e,t,n,r,o){let i=Date.now(),a=ae(s,e,n),c=ps(Ve(fs(),"agentx-codex-")),u=Ve(c,"last-message.txt"),l=xs(s,a,!0,e.model,e.systemPromptAppend,u,r),d="",g,m,w,T;try{let b=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),v=et("codex",l,{cwd:s.workspace,timeout:b,reject:!1,env:tt(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let I="",D="",C=!1,A=new Re("utf8"),_=new Re("utf8"),h=Math.min(b,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),E,N=()=>{E&&clearTimeout(E),E=setTimeout(()=>{C=!0,v.kill("SIGTERM",{forceKillAfterTimeout:5e3})},h)};N(),v.stderr?.on("data",y=>{N(),D+=_.write(y),D.length>16e3&&(D=D.slice(-16e3))}),v.stdout?.on("data",y=>{N(),I+=A.write(y);let k=I.split(`
|
|
23
|
+
`);I=k.pop()||"";for(let M of k)if(M.trim())try{let H=JSON.parse(M);if(o)try{o(H)}catch{}g=Mt(H)||g,m=Ts(H)||m,w=Pt(H)||w,T=ks(H)||T;let R=Io(H);if(R&&R!==d){let z=R.startsWith(d)?R.slice(d.length):R;d=R.startsWith(d)?R:d+R,z&&t(z,d)}}catch{d+=M+`
|
|
24
24
|
`,t(M+`
|
|
25
|
-
`,d)}});let L=await v;
|
|
25
|
+
`,d)}});let L=await v;E&&clearTimeout(E);let x=A.end();x&&(I+=x);let F=_.end();if(F&&(D+=F),L.exitCode!==0&&!d||T){let y=D||(typeof L.stderr=="string"?L.stderr:""),k=L,M;return C?M=`Codex CLI produced no output for ${Math.round(h/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:k.timedOut?M=`Codex CLI timed out after ${Math.round(b/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?M=T:k.signal?M=y.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+y)?M=Ze():M=y.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...q(M),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:w||r}}let S="";try{S=ms(u,"utf8").trim()}catch{}if(S&&S!==d){let y=S.startsWith(d)?S.slice(d.length):S;d=S,y&&t(y,d)}return{content:d,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:w||r}}catch(b){let v=/ENOENT|spawn codex/i.test(b?.message||"")?Ze():b?.message;return{content:d,...q(v||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:w||r}}finally{hs(c,{recursive:!0,force:!0})}}async function Po(s,e,t,n,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let u=ae(s,e,n),l=xo(s,u,e.model,e.systemPromptAppend,e.freshSession?void 0:r),d="",g,m=e.freshSession?void 0:r,w,T,b=!0,v;try{let I=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),D=ko(s,e);if(s.persistentProcess)try{T=await Vn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:D,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",T.url),D=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(y){if(!(y instanceof re))throw y;y.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:y.message})}if(i?.aborted)throw new Error("task cancelled by operator");let C=et("opencode",l,{cwd:s.workspace,timeout:I,reject:!1,env:D,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let A=!1,_,h=()=>{T?.invalidate(),A=!0,_=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{C.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",h,{once:!0}),v=()=>i?.removeEventListener("abort",h),i?.aborted&&h();let E="",N="",L=new Re("utf8"),x=new Re("utf8"),F=y=>{if(y.trim())try{let k=JSON.parse(y);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(m=k.sessionID);let M=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;M&&(d||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),d+=M,t?.(M,d));let H=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;H&&a?.(H);let R=k.type==="step_finish"?k.part?.tokens:void 0;R&&(g={inputTokens:ie(R.input),outputTokens:ie(R.output),cacheReadTokens:ie(R.cache?.read),cacheCreateTokens:ie(R.cache?.write)}),w=To(k)||w}catch{d+=y+`
|
|
26
26
|
`,t?.(y+`
|
|
27
|
-
`,d)}};C.stdout?.on("data",y=>{
|
|
28
|
-
`);
|
|
27
|
+
`,d)}};C.stdout?.on("data",y=>{E+=L.write(y);let k=E.split(`
|
|
28
|
+
`);E=k.pop()||"";for(let M of k)F(M)}),C.stderr?.on("data",y=>{N+=x.write(y)});let S=await C;if(i&&i.removeEventListener("abort",h),E+=L.end(),E.trim()&&F(E),N+=x.end(),A)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(S.exitCode!==0||w){let y=S,k;return y.timedOut?k=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:w?k=w:y.code==="ENOENT"||/ENOENT|spawn opencode/i.test((y.shortMessage||"")+" "+N)?k=us():k=N.trim()||`OpenCode exited with code ${y.exitCode??"unknown"}`,{content:"",...q(k),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return b=!1,{content:d.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:m}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(I?.message||"")?us():I?.message;return{content:d,...q(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{v?.(),T?.release(b)}}async function Ro(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ae(s,e,n),c="",u=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of u)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function _o(s,e,t,n,r,o,i,a,c){let u=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),d=new AbortController,g=!1,m=()=>{let b=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{d.abort(new Error(b))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let w=setTimeout(()=>{g=!0;try{d.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);w.unref?.();let T=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-u});try{let b=s.provider||"claude-code",v=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,D=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),C=e.context?.channel==="web-chat"&&D?{userId:I,agentId:e.agentId||"acme-public"}:void 0,A=An(s),_=Object.keys(A).length>0,h={task:v,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:C,providerOpts:o,abortSignal:d.signal,mcpServers:_?A:void 0};if(r){let{generateStream:F}=await import("./agent-ILH6ANOM.js"),S="",y,k,M,H;for await(let R of F(h)){if(c)try{c(R)}catch{}if(R.type==="text_delta")S+=R.text,r(R.text,S);else if(R.type==="thinking_delta")R.text&&i&&i(R.text);else if(R.type==="generate_result"){if(R.result.content&&R.result.content!==S){let z=R.result.content.slice(S.length);z?(S=R.result.content,r(z,S)):S=R.result.content}y=R.result.tokensUsed,R.result.inputTokens!=null&&(k=R.result.inputTokens),R.result.outputTokens!=null&&(M=R.result.outputTokens)}else if(R.type==="done"){if(R.result.content&&R.result.content!==S){let z=R.result.content.slice(S.length);z?(S=R.result.content,r(z,S)):S=R.result.content}R.result.tokensUsed!=null&&(y=R.result.tokensUsed)}else R.type==="error"&&(H=R.error)}return H&&!S?g?T():H==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${H}`),duration:Date.now()-u}:((k===void 0||M===void 0)&&y&&(k=Math.round(y*.7),M=y-k),{content:S||"Done.",tokensUsed:y,usage:k!==void 0||M!==void 0?{inputTokens:k||0,outputTokens:M||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:E}=await import("./agent-ILH6ANOM.js"),N=await E(h),L=N.inputTokens,x=N.outputTokens;if((L===void 0||x===void 0)&&N.tokensUsed){let F=N.tokensUsed;L=Math.round(F*.7),x=F-L}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:L!==void 0||x!==void 0?{inputTokens:L||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(b){return g?T():b?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${b.message}`),duration:Date.now()-u}}finally{clearTimeout(w),a&&a.removeEventListener("abort",m)}}async function Eo(s,e,t,n,r,o,i){let a=Ye();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let g,m=!1;try{let S=a.list().length;g=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),m=a.list().length>S}catch(S){return S instanceof ye,null}m&&Rt(e.agentId,s,e.model,n,"persistent");let w=ae(s,e,t),T="",b,v,I,D,C,A,_,h="",E="",N=S=>{if(!i||!S)return;let y;if(E&&S.startsWith(E)?y=S.slice(E.length):y=h&&!h.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
|
-
${S}`:S,
|
|
33
|
+
${S}`:S,E=S,!!y){h+=y;try{i(y,h)}catch{}}},L=!1,x=()=>{L=!0,a.kill(d,"operator-cancel").catch(()=>{})};o&&(o.aborted?x():o.addEventListener("abort",x,{once:!0}));let F=!1;try{let S=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let y of g.runTurn({message:w,taskId:e.taskId??"unknown",deadlineMs:S})){if(F=!0,r)try{r(y.raw)}catch{}if(y.type==="assistant"){let k=y.raw.message?.content??[];for(let H of k)H.type==="text"&&typeof H.text=="string"?(T=H.text,N(H.text)):H.type==="tool_use"&&(E="");let M=y.raw.message?.usage;if(M){let H=(M.input_tokens||0)+(M.cache_read_input_tokens||0)+(M.cache_creation_input_tokens||0);H>0&&(D=H)}}if(y.type==="result"){let k=y.raw;if(k.is_error){let M=q(typeof k.result=="string"?k.result:"claude error");b=M.error,v=M.errorKind}else typeof k.result=="string"&&k.result.length>0&&(T=k.result,h||N(k.result));typeof k.session_id=="string"&&(_=k.session_id),k.usage&&(I={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(C=k.num_turns),typeof k.message?.model=="string"?A=k.message.model:typeof k.model=="string"&&(A=k.model)}}}catch(S){if(L)b="task cancelled by operator",v="cancelled";else if(F)if(S instanceof Pe){let y=q(`Claude Code timed out after ${Math.round(S.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);b=y.error,v=y.errorKind}else{let y=q(`persistent claude process error: ${S?.message||String(S)}`);b=y.error,v=y.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${S?.message||S}); falling back to spawn-per-task`),a.release(d,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",x),null}finally{o&&o.removeEventListener("abort",x)}return L&&!b&&(b="task cancelled by operator",v="cancelled"),{content:L?"":T,error:b,errorKind:v,duration:Date.now()-c,usage:I,contextTokens:D,numTurns:C,billedModel:A,claudeSessionId:_}}function vs(s){return se(s.autonomy)?s.taskId?as(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Do(s,e,t,n,r,o,i){let a=e.autonomy,c=cs(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let u=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:u,message:`${wn(a)}
|
|
34
34
|
|
|
35
35
|
${e.message}`};process.stderr.write(`[claude-autonomy] agent=${e.agentId} level=${a} task=${u} via=spawn (persistent process bypassed)
|
|
36
|
-
`);let d=t?await
|
|
37
|
-
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=
|
|
36
|
+
`);let d=t?await Ss(s,l,t,n,r,o,i):await Is(s,l,n,r,i),g=ds(u);return{...d,autonomy:a,...g.length?{autonomyBlocks:g}:{}}}async function Cs(s,e,t,n,r,o,i,a,c){if(se(e.autonomy))return Do(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let u=await Eo(s,e,r,o,i,a,n);if(u!==null)return u}return n?Ss(s,e,n,r,o,i,a):Is(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let u=await Zn.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:tt(s,e),args:ws(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:At(ae(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...u,...u.error?q(u.error):{}}}catch(u){if(!(u instanceof oe))throw u;if(i?.({type:"codex.fallback",reason:u.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?Mo(s,e,n,r,o,i):$o(s,e,r,o);case"opencode":return Po(s,e,n,r,o,i,a,c);case"sdk":{let u=s.provider||"claude",l=t[u]?.apiKey;return l?Ro(s,e,l,r):{content:"",error:`No API key for provider "${u}". Configure providers.${u}.apiKey`}}case"orchestrator":{let u=s.provider||"claude-code",l=t[u],d=l?.apiKey;return _o(s,e,d,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as we,writeFileSync as As,mkdirSync as Oo,existsSync as _t,readdirSync as Et}from"fs";import{resolve as xe}from"path";var Dt=12e3,_e=30,No=720,Lo=40,Fo=18e4,Ho="[Compacted conversation summary",jo=7*864e5,Uo=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Bo(s){return s?Uo.some(e=>e.test(s)):!1}var Wo=[{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 Ms(s){if(!s)return null;let e=0;for(let t of Wo)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function $s(s,e,t,n){if(s.length===0)return!1;let r=s[s.length-1];return r.role===e&&(r.name??"")===t&&r.content===n}function Ps(s,e){let t=(s??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function Rs(s,e,t){if(t<=0)return[];let n=(s??[]).filter(i=>i.role==="user"),r=n[n.length-1],o=(r&&r.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function Ko(s){let e=s.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let r=Math.floor(n/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var nt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=xe(e,".agentx/sessions"),_t(this.sessionsDir)||Oo(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??No),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Lo),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Fo)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let u=(async()=>{try{let l=await c.seedHistory(n,{maxMessages:_e,maxChars:Dt});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,u);try{await u}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return xe(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let r=this.sessionKey(e,t,n);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(_t(o))try{let u=JSON.parse(we(o,"utf-8"));return this.cache.set(r,u),u}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!_t(i))return null;try{return JSON.parse(we(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);$s(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,r){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,r){let o=this.getSession(e,t,n);$s(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,r={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??_e),a=Math.max(200,r.maxChars??Dt),c=[],u=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(u+=m.content.length,c.push(m),u>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],d="";for(let g of c){let m=Ko(g.timestamp);m!==d&&(l.push(`\u2014 ${m} \u2014`),d=m);let w=g.name||(g.role==="user"?"User":"Agent");l.push(`${w}: ${g.content}`)}return l.push("[End of history \u2014 respond to the latest message above]"),l.push(""),l.join(`
|
|
37
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Et(this.sessionsDir).filter(C=>C.startsWith(`${a}:`)&&C.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let u=o.slice(0,10),l=i.slice(0,10),d=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(C=>{let A=C.match(d);if(!A)return!1;let _=A[1];return _>=u&&_<=l}),m=[],w=0,T=e.query?.toLowerCase(),b=e.participants?.length?new Set(e.participants):void 0;for(let C of g){let A;try{A=JSON.parse(we(xe(this.sessionsDir,C),"utf-8"))}catch{continue}if(A.agentId===e.agentId&&!(e.channel&&A.channel!==e.channel)&&!(e.chatId&&A.chatId!==e.chatId))for(let _ of A.messages)w++,!(!_.timestamp||_.timestamp<o||_.timestamp>=i)&&(b&&_.role==="user"&&!b.has(_.name??"")||T&&!_.content.toLowerCase().includes(T)||m.push({ts:_.timestamp,role:_.role,senderName:_.name??"",content:_.content,channel:A.channel,chatId:A.chatId,day:A.day,sessionFile:C}))}m.sort((C,A)=>A.ts.localeCompare(C.ts));let v=m.slice(0,t),I=v.length>0?v[v.length-1].ts:null,D=m.length>t;return{turns:v,oldestTs:I,hasMore:D,totalScanned:w}}recentByChatId(e){let t=Math.min(Math.max(e.limit??_e,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=Et(this.sessionsDir).filter(d=>d.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(d=>{if(!d.includes(i))return!1;let g=d.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),c=[];for(let d of a){let g;try{g=JSON.parse(we(xe(this.sessionsDir,d),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:d})}let u=new Set,l=[];for(let d of c){let g=`${d.ts}|${d.role}|${d.senderName}|${d.content}`;u.has(g)||(u.add(g),l.push(d))}return l.sort((d,g)=>d.ts.localeCompare(g.ts)),l.slice(-t)}sessionIdleMs(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:Date.now()-new Date(r.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,r){if(r!==void 0&&r!==""&&!Bo(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Et(this.sessionsDir).filter(u=>u.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&u.includes(o)&&u.endsWith(".json")),c=[];for(let u of a)try{let l=JSON.parse(we(xe(this.sessionsDir,u),"utf-8"));if(l.id===i||l.messages.length===0)continue;let d=l.messages.slice(-4),m=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,w=d.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${m} (${l.channel}):
|
|
38
38
|
${w.join(`
|
|
39
39
|
`)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
40
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-NWPBPWY2.js");if(!i(o.messages))return{compacted:!1};let u=await a(o.messages,e,r,{channel:t,chatId:n});return u.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,u),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:u.qualityScore,lostEntities:u.lostEntities,drift:u.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(Eo)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return xe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(we(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Is(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>No?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>_e&&(e.messages=e.messages.slice(-_e));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Ot&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&le.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);Is(t,JSON.stringify(e,null,2))}catch{}}};var st=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],u=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:u}}if(o.length>=this.maxPerHour){let c=o[0],u=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:u}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(u=>setTimeout(u,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as De,writeFileSync as $s,appendFileSync as Uo,existsSync as Te,mkdirSync as Bo}from"fs";import{resolve as ke}from"path";var Ps={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},Rs=2e5,Wo=1.5;function Ko(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function _s(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Rs?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var Ms=500,qo=".agentx/pricing/custom.json",Ie=class{dir;cache=null;pricing;constructor(e=ke(process.cwd(),".agentx/usage")){this.dir=e,Bo(this.dir,{recursive:!0}),this.pricing=Go()}getPricing(){return this.pricing}static calculateCost(e,t,n=Ps){let r=Ko(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,u=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,d=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+u/1e6*o.cacheCreate;return l+d*Wo}cost(e,t){return Ie.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,c,u){let l=this.today(),d=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};d.tasks++,d.totalDuration+=t,a&&(d.model=a);let g=0,m=0,w=0,T=0,b=0,v=0,I=0,O=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Rs?(b=n.inputTokens,v=n.outputTokens,I=n.cacheReadTokens,O=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,w=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(g=Math.ceil(r/4),m=Math.ceil(o/4)),d.inputTokens+=g,d.outputTokens+=m,d.cacheReadTokens+=w,d.cacheCreateTokens+=T,d.tier2InputTokens=(d.tier2InputTokens||0)+b,d.tier2OutputTokens=(d.tier2OutputTokens||0)+v,d.tier2CacheReadTokens=(d.tier2CacheReadTokens||0)+I,d.tier2CacheCreateTokens=(d.tier2CacheCreateTokens||0)+O,i&&d.errors++,d.byChannel||(d.byChannel={});let C=(c||"other").toLowerCase(),A=d.byChannel[C]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};A.tasks++,A.totalDuration+=t,A.inputTokens+=g,A.outputTokens+=m,A.cacheReadTokens+=w,A.cacheCreateTokens+=T,A.tier2InputTokens+=b,A.tier2OutputTokens+=v,A.tier2CacheReadTokens+=I,A.tier2CacheCreateTokens+=O,i&&A.errors++,d.byChannel[C]=A,u&&(d.sessionKeys||(d.sessionKeys=[]),d.sessionKeys.includes(u)||(d.sessionKeys.push(u),d.sessionKeys.length>Ms&&d.sessionKeys.splice(0,d.sessionKeys.length-Ms))),l.agents[e]=d,this.save(l)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(Te(t))try{return this.cache=JSON.parse(De(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Te(t))return null;try{return JSON.parse(De(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,c=0,u=0,l="",d=0,g={},m={},w={};for(let[T,b]of Object.entries(n.agents)){let v=this.cost(b);g[T]=v,r+=b.tasks,o+=(b.inputTokens||0)+(b.tier2InputTokens||0),i+=(b.outputTokens||0)+(b.tier2OutputTokens||0),a+=(b.cacheReadTokens||0)+(b.tier2CacheReadTokens||0),c+=(b.cacheCreateTokens||0)+(b.tier2CacheCreateTokens||0),u+=v,v>d&&(d=v,l=T);let I=b.sessionKeys?.length||0;m[T]={sessions:I,avgTasksPerSession:I>0?b.tasks/I:b.tasks};for(let[O,C]of Object.entries(b.byChannel||{})){let A=this.cost(C,b.model);w[O]=(w[O]||0)+A}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:u,topAgent:l,topCost:d,agentCosts:g,agentSessionStats:m,byChannel:w}}appendToTokenCosts(e,t){let n=t||ke(process.cwd(),".agentx/TOKEN_COSTS.md"),r=u=>u<.01?u.toFixed(4):u.toFixed(2),o=u=>u>=1e6?`${(u/1e6).toFixed(1)}M`:u>=1e3?`${(u/1e3).toFixed(0)}K`:String(u),i=Object.entries(e.agentCosts).sort(([,u],[,l])=>l-u).map(([u,l])=>{let d=e.agentSessionStats[u],g=d&&d.sessions>0?` (${d.sessions}s, ${d.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${u}: $${r(l)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,u],[,l])=>l-u).map(([u,l])=>`${u}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;Te(n)?Uo(n,c+`
|
|
41
|
-
`)
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-NWPBPWY2.js");if(!i(o.messages))return{compacted:!1};let u=await a(o.messages,e,r,{channel:t,chatId:n});return u.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,u),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:u.qualityScore,lostEntities:u.lostEntities,drift:u.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(Ho)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return xe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(we(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},As(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>jo?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>_e&&(e.messages=e.messages.slice(-_e));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Dt&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&le.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);As(t,JSON.stringify(e,null,2))}catch{}}};var st=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],u=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:u}}if(o.length>=this.maxPerHour){let c=o[0],u=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:u}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(u=>setTimeout(u,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as Ee,writeFileSync as _s,appendFileSync as qo,existsSync as Te,mkdirSync as Go}from"fs";import{resolve as ke}from"path";var Ds={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},Os=2e5,Jo=1.5;function Qo(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function Ns(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Os?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var Es=500,zo=".agentx/pricing/custom.json",Ie=class{dir;cache=null;pricing;constructor(e=ke(process.cwd(),".agentx/usage")){this.dir=e,Go(this.dir,{recursive:!0}),this.pricing=Xo()}getPricing(){return this.pricing}static calculateCost(e,t,n=Ds){let r=Qo(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,u=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,d=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+u/1e6*o.cacheCreate;return l+d*Jo}cost(e,t){return Ie.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,c,u){let l=this.today(),d=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};d.tasks++,d.totalDuration+=t,a&&(d.model=a);let g=0,m=0,w=0,T=0,b=0,v=0,I=0,D=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Os?(b=n.inputTokens,v=n.outputTokens,I=n.cacheReadTokens,D=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,w=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(g=Math.ceil(r/4),m=Math.ceil(o/4)),d.inputTokens+=g,d.outputTokens+=m,d.cacheReadTokens+=w,d.cacheCreateTokens+=T,d.tier2InputTokens=(d.tier2InputTokens||0)+b,d.tier2OutputTokens=(d.tier2OutputTokens||0)+v,d.tier2CacheReadTokens=(d.tier2CacheReadTokens||0)+I,d.tier2CacheCreateTokens=(d.tier2CacheCreateTokens||0)+D,i&&d.errors++,d.byChannel||(d.byChannel={});let C=(c||"other").toLowerCase(),A=d.byChannel[C]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};A.tasks++,A.totalDuration+=t,A.inputTokens+=g,A.outputTokens+=m,A.cacheReadTokens+=w,A.cacheCreateTokens+=T,A.tier2InputTokens+=b,A.tier2OutputTokens+=v,A.tier2CacheReadTokens+=I,A.tier2CacheCreateTokens+=D,i&&A.errors++,d.byChannel[C]=A,u&&(d.sessionKeys||(d.sessionKeys=[]),d.sessionKeys.includes(u)||(d.sessionKeys.push(u),d.sessionKeys.length>Es&&d.sessionKeys.splice(0,d.sessionKeys.length-Es))),l.agents[e]=d,this.save(l)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(Te(t))try{return this.cache=JSON.parse(Ee(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Te(t))return null;try{return JSON.parse(Ee(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,c=0,u=0,l="",d=0,g={},m={},w={};for(let[T,b]of Object.entries(n.agents)){let v=this.cost(b);g[T]=v,r+=b.tasks,o+=(b.inputTokens||0)+(b.tier2InputTokens||0),i+=(b.outputTokens||0)+(b.tier2OutputTokens||0),a+=(b.cacheReadTokens||0)+(b.tier2CacheReadTokens||0),c+=(b.cacheCreateTokens||0)+(b.tier2CacheCreateTokens||0),u+=v,v>d&&(d=v,l=T);let I=b.sessionKeys?.length||0;m[T]={sessions:I,avgTasksPerSession:I>0?b.tasks/I:b.tasks};for(let[D,C]of Object.entries(b.byChannel||{})){let A=this.cost(C,b.model);w[D]=(w[D]||0)+A}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:u,topAgent:l,topCost:d,agentCosts:g,agentSessionStats:m,byChannel:w}}appendToTokenCosts(e,t){let n=t||ke(process.cwd(),".agentx/TOKEN_COSTS.md"),r=u=>u<.01?u.toFixed(4):u.toFixed(2),o=u=>u>=1e6?`${(u/1e6).toFixed(1)}M`:u>=1e3?`${(u/1e3).toFixed(0)}K`:String(u),i=Object.entries(e.agentCosts).sort(([,u],[,l])=>l-u).map(([u,l])=>{let d=e.agentSessionStats[u],g=d&&d.sessions>0?` (${d.sessions}s, ${d.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${u}: $${r(l)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,u],[,l])=>l-u).map(([u,l])=>`${u}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;Te(n)?qo(n,c+`
|
|
41
|
+
`):_s(n,`# Token Costs
|
|
42
42
|
|
|
43
43
|
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
44
44
|
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
@@ -46,18 +46,18 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
|
46
46
|
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
47
47
|
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
48
48
|
`+c+`
|
|
49
|
-
`)}hasTokenCostsEntry(e,t){let n=t||ke(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Te(n))return!1;try{let r=
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||ke(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Te(n))return!1;try{let r=Ee(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||ke(process.cwd(),".agentx/TOKEN_COSTS.md");if(!Te(t))return null;try{let r=Ee(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let u=a.toISOString().slice(0,10);if(o&&u<=o)break;i.push(u),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let u=this.generateDailyReport(c);!u||u.totalTasks===0||(this.appendToTokenCosts(u,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,c=0,u={},l={};for(let w=0;w<e;w++){let T=new Date(Date.now()-w*864e5).toISOString().slice(0,10),b=this.getDate(T);if(b)for(let[v,I]of Object.entries(b.agents)){let D=this.cost(I);t+=I.tasks;let C=(I.inputTokens||0)+(I.tier2InputTokens||0),A=(I.outputTokens||0)+(I.tier2OutputTokens||0),_=(I.cacheReadTokens||0)+(I.tier2CacheReadTokens||0),h=(I.cacheCreateTokens||0)+(I.tier2CacheCreateTokens||0);n+=C,r+=A,o+=_,i+=h,a+=I.errors,c+=D;let E=u[v]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};E.tasks+=I.tasks,E.input+=C,E.output+=A,E.cacheRead+=_,E.cacheCreate+=h,E.total=E.input+E.output+E.cacheRead+E.cacheCreate,E.totalDuration+=I.totalDuration,E.avgDuration=E.totalDuration/E.tasks,E.cost+=D,E.sessions+=I.sessionKeys?.length||0,I.model&&(E.model=I.model),u[v]=E;for(let[N,L]of Object.entries(I.byChannel||{})){let x=this.cost(L,I.model),F=l[N]||{tasks:0,cost:0};F.tasks+=L.tasks,F.cost+=x,l[N]=F}}}let d=n+r+o+i,g=o+i>0?o/(o+i):0,m={};for(let[w,T]of Object.entries(u))m[w]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:d,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:u,byChannel:l,sessionStats:m}}filePath(e){return ke(this.dir,`${e}.json`)}save(e){try{_s(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Xo(){let s=JSON.parse(JSON.stringify(Ds));try{let e=ke(process.cwd(),zo);if(!Te(e))return s;let t=JSON.parse(Ee(e,"utf-8"));for(let[n,r]of Object.entries(t))s[n]||(s[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(s[n],r)}catch{}return s}var Yo={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,memory:400,history:1200,"cross-chat":800,wiki:2500}},Ls=4;function Fs(s,e=Yo){let t=Vo(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*Ls;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Ls,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let u=o-r;u>100&&n.push(c.slice(0,u)+"...");break}n.push(c),r+=c.length}return n.join(`
|
|
50
50
|
|
|
51
|
-
`)}function
|
|
51
|
+
`)}function Vo(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(Zo(s,t("channel",200))),n.push(ei(s,t("scope",200))),s.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:s.landscape,tags:["landscape","world-model"]}),s.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:s.systemPrompt.split(`
|
|
52
52
|
`)[0],tags:["identity",s.agentId]}),s.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:s.bootstrapContext,tags:["bootstrap","identity","personality"]}),s.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:s.references,tags:["references","verified","deterministic"]}),s.intent&&s.intent.path.length>0){let i=[`[Intent path: ${s.intent.pathLabel}${s.intent.status==="pending"?" (pending approval)":""}]`],a=s.intent.path[s.intent.path.length-1],c=s.intent.axes?.[a];if(c&&Object.keys(c).length){let u=Object.entries(c).map(([l,d])=>` ${l}: ${d}`).join(`
|
|
53
53
|
`);i.push(u)}s.intent.leaf?.input&&i.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
54
|
-
`),tags:["intent",...s.intent.path]})}else{let i=
|
|
54
|
+
`),tags:["intent",...s.intent.path]})}else{let i=ti(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
55
55
|
`),tags:["artifacts",...s.mediaType?["media"]:[]]}),s.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:s.skillInjection,tags:["skills","auto-inject"]}),s.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:s.patternContext,tags:["patterns","behavioral","self-improving"]}),s.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:s.procedureContext,tags:["procedures","sop"]}),s.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:s.memoryContext,tags:["memory","persistent"]});let o=s.groupHistory||s.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),s.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:s.crossChatContext,tags:["history","cross-chat"]}),s.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:s.longMemoryRecall,tags:["history","long-memory"]}),s.handoverNote){let i=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&i.push(`Operator summary: ${s.handoverNote.summary}`),i.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
56
56
|
`),tags:["handover",s.handoverNote.fromAgent]})}return s.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${s.rotationMemo.reason}, ${s.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,s.rotationMemo.memo].join(`
|
|
57
|
-
`),tags:["continuity","rotation-memo"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function
|
|
58
|
-
`),tags:r,rules:n}}function
|
|
59
|
-
`),tags:n}}function
|
|
60
|
-
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as
|
|
57
|
+
`),tags:["continuity","rotation-memo"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function Zo(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
58
|
+
`),tags:r,rules:n}}function ei(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:n}}function ti(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}function Hs(s){if(!s)return null;try{let e=JSON.stringify(s);return e.length<=32e3?e:null}catch{return null}}function ic(s){if(!s)return null;try{let e=JSON.parse(s);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="direct")return e}catch{}return null}var rt=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
60
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as ni,writeFileSync as js,appendFileSync as si,mkdirSync as ri,existsSync as Us}from"fs";import{resolve as Ot}from"path";var Bs=50,oi="claude-haiku-4-20250514",ii=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
61
61
|
|
|
62
62
|
Extract patterns like:
|
|
63
63
|
- "When asked about X, the approach that works is Y"
|
|
@@ -73,19 +73,19 @@ SKIP:
|
|
|
73
73
|
Output a JSON array:
|
|
74
74
|
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
75
75
|
|
|
76
|
-
If nothing worth extracting, output: []`,ot=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=
|
|
77
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};
|
|
78
|
-
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=
|
|
79
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&
|
|
76
|
+
If nothing worth extracting, output: []`,ot=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ot(e,".agentx/patterns"),Us(this.patternsDir)||ri(this.patternsDir,{recursive:!0})}filePath(e){return Ot(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Us(t))return[];try{return ni(t,"utf-8").split(`
|
|
77
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};si(this.filePath(e),JSON.stringify(n)+`
|
|
78
|
+
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=Ot(this.patternsDir,`${t}_bm25_cache.json`),a=fn(o,i),u=hn(e,a).slice(0,n).map(l=>r[l.docIndex]).filter(l=>l.confidence>=.3);return u.length>0&&this.recordAccess(t,u.map(l=>l.id)),u}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
79
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&js(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
80
80
|
`)+`
|
|
81
|
-
`)}prune(e){let t=this.getAll(e);t.length<=
|
|
81
|
+
`)}prune(e){let t=this.getAll(e);t.length<=Bs||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,Bs),js(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
82
82
|
`)+`
|
|
83
|
-
`))}};async function
|
|
83
|
+
`))}};async function Ws(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-NRPX2FHP.js"),c=(await o("claude").generate([{role:"system",content:ii},{role:"user",content:`User: ${e.slice(0,500)}
|
|
84
84
|
|
|
85
|
-
Agent: ${t.slice(0,1e3)}`}],{model:
|
|
86
|
-
\u2026[truncated ${s.length-e} chars]`}var Ht;function
|
|
85
|
+
Agent: ${t.slice(0,1e3)}`}],{model:oi,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let u=JSON.parse(c[0]);if(!(!Array.isArray(u)||u.length===0)){for(let l of u)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as ai}from"events";var Lt=class{inner=new ai;envelopeListeners=new Set;ring=new Kn;node="local";constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let n=this.inner.emit(e,t);try{this.publish(ci(e,t))}catch{}return n}publish(e){let t=Wn(),n=e.id??Bn(),r={id:n,rootId:e.rootId??t?.rootId??n,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Un(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}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}};function ci(s,e){let t=e,n={type:s,at:t.at,agentId:t.agentId,ref:t.taskId};switch(s){case"message:matched":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...n,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:started":return{...n,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...n,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...n,kind:"agent",summary:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...n,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...n,kind:"agent",summary:String(s)}}}var Nt;function Z(){return Nt||(Nt=new Lt),Nt}ht();ht();var Ks=["manual","notify","auto"];function di(s){return typeof s=="string"&&Ks.includes(s)}var Ft={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var De=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...Ft,...e}}options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o={sessionId:e,cwd:t.cwd??"",agentIds:[],mode:"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return this.sessions.set(e,o),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n&&(n.lastSeenAt=t),n}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let 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));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],n}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now()){this.sessions.delete(e);for(let n of this.items.values())n.sessionId===e&&(n.state==="pending"||n.state==="claimed")&&this.settle(n,"expired",t,"session ended")}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:he(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:ui(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function ui(s,e){return s.length<=e?s:`${s.slice(0,e)}
|
|
86
|
+
\u2026[truncated ${s.length-e} chars]`}var Ht;function qs(){return Ht||(Ht=new De),Ht}ft();import{readFileSync as li}from"fs";import{homedir as gi}from"os";import{join as pi}from"path";var Oe=null,mi=6e4;function hi(){try{let s=pi(gi(),".claude.json"),e=li(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function fi(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function yi(s=!1){let e=Date.now();return!s&&Oe&&e-Oe.checkedAt<mi||(Oe=fi(hi(),e)),Oe}function Gs(s){let e=yi();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var Js={warnRatio:.8},Q={...Js},bi=5*60*60*1e3,wi=60*60*1e3,ge=[];function Qs(s){Q={...Js,...s||{}}}function zs(s){let e=s-bi,t=0;for(;t<ge.length&&ge[t]<e;)t++;t>0&&ge.splice(0,t)}function Xs(s=Date.now()){zs(s),ge.push(s)}function Ys(s=Date.now()){zs(s);let e=s-wi,t=0;for(let o=ge.length-1;o>=0&&ge[o]>=e;o--)t++;let n=ge.length,r={lastHour:t,last5h:n,maxPerHour:Q.maxPerHour,maxPer5h:Q.maxPer5h};return Q.maxPerHour&&Q.maxPerHour>0&&(r.hourlyRatio=t/Q.maxPerHour),Q.maxPer5h&&Q.maxPer5h>0&&(r.fiveHourRatio=n/Q.maxPer5h),r}function Vs(s,e=Date.now()){let t=Ys(e);return s?null:Q.maxPerHour&&t.lastHour>=Q.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${Q.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:Q.maxPer5h&&t.last5h>=Q.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${Q.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function Zs(s=Date.now()){let e=Ys(s),t=Q.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var jt=new Map;function er(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function tr(s,e,t,n=Date.now()){let r=jt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},jt.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function nr(s){let e=jt.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Y,mkdirSync as Gi,readdirSync as ee,readFileSync as Le,rmSync as Ji,writeFileSync as Qi}from"fs";import{resolve as B}from"path";import{existsSync as me,mkdirSync as Ut,readFileSync as xi,readdirSync as Ti,renameSync as ki,unlinkSync as Ii,writeFileSync as it}from"fs";import{resolve as ce,relative as at}from"path";import{z as K}from"zod";var pe=K.object({id:K.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:K.string().min(1),trigger:K.string().min(1,"procedures must describe when they apply"),inputs:K.array(K.string()).default([]),expected:K.string().optional(),kpis:K.array(K.string()).default([]),owner:K.string().optional(),tags:K.array(K.string()).default([]),status:K.enum(["draft","active","deprecated"]).default("active"),source:K.string().optional(),evidence:K.array(K.string()).default([]),created:K.string().optional(),updated:K.string().optional(),related:K.array(K.string()).default([])});function Si(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
|
|
87
87
|
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function ct(s){let e=["---"];return e.push(`id: ${s.id}`),e.push(`title: "${s.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${s.trigger.replace(/"/g,'\\"')}"`),s.inputs?.length&&e.push(`inputs: ${JSON.stringify(s.inputs)}`),s.expected&&e.push(`expected: "${s.expected.replace(/"/g,'\\"')}"`),s.kpis?.length&&e.push(`kpis: ${JSON.stringify(s.kpis)}`),s.owner&&e.push(`owner: ${s.owner}`),s.tags?.length&&e.push(`tags: ${JSON.stringify(s.tags)}`),e.push(`status: ${s.status}`),s.source&&e.push(`source: "${s.source.replace(/"/g,'\\"')}"`),s.evidence?.length&&e.push(`evidence: ${JSON.stringify(s.evidence)}`),s.related?.length&&e.push(`related: ${JSON.stringify(s.related)}`),s.created&&e.push(`created: ${s.created}`),s.updated&&e.push(`updated: ${s.updated}`),e.push("---"),e.join(`
|
|
88
|
-
`)}var Ne=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ce(process.cwd(),".agentx/procedures"),Ut(this.baseDir,{recursive:!0})}pathFor(e){return ce(this.baseDir,`${e}.md`)}get draftsDir(){return ce(this.baseDir,"_drafts")}draftPathFor(e){return ce(this.draftsDir,`${e}.md`)}parseFile(e){let t=
|
|
88
|
+
`)}var Ne=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ce(process.cwd(),".agentx/procedures"),Ut(this.baseDir,{recursive:!0})}pathFor(e){return ce(this.baseDir,`${e}.md`)}get draftsDir(){return ce(this.baseDir,"_drafts")}draftPathFor(e){return ce(this.draftsDir,`${e}.md`)}parseFile(e){let t=xi(e,"utf-8"),{meta:n,body:r}=Si(t),o=pe.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:at(this.baseDir,e)}:null}listDir(e){if(!me(e))return[];let t=[];for(let n of Ti(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(ce(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return me(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return me(t)?this.parseFile(t):null}add(e,t){let n=pe.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(me(r))throw new Error(`Procedure already exists: ${n.id}`);return it(r,ct(n)+`
|
|
89
89
|
|
|
90
90
|
`+t.trim()+`
|
|
91
91
|
`),{meta:n,body:t.trim(),path:at(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=pe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return it(this.pathFor(e),ct(o)+`
|
|
@@ -97,15 +97,15 @@ Agent: ${t.slice(0,1e3)}`}],{model:ti,maxTokens:512})).content.trim().match(/\[[
|
|
|
97
97
|
`),{meta:n,body:t.trim(),path:at(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=pe.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return it(this.pathFor(e),ct(n)+`
|
|
98
98
|
|
|
99
99
|
`+t.body+`
|
|
100
|
-
`),
|
|
101
|
-
`)}function
|
|
100
|
+
`),Ii(this.draftPathFor(e)),{meta:n,body:t.body,path:at(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!me(t))throw new Error(`Draft not found: ${e}`);let n=ce(this.draftsDir,"_rejected");Ut(n,{recursive:!0}),ki(t,ce(n,`${e}.md`))}isRejected(e){return me(ce(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as vi,mkdirSync as Ci,readFileSync as Ai,writeFileSync as $i}from"fs";import{dirname as Mi,resolve as Pi}from"path";import{z as X}from"zod";var Ri=X.object({key:X.string(),count:X.number().int().min(0).default(0),firstSeen:X.string(),lastSeen:X.string(),taskIds:X.array(X.string()).default([]),sampleMessage:X.string().default(""),status:X.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:X.string().optional()}),_i=X.object({minedThrough:X.string().optional(),candidates:X.array(Ri).default([])});function sr(s){return Pi(s,"_candidates.json")}function Ei(s){let e=sr(s);if(!vi(e))return{candidates:[]};try{let t=_i.safeParse(JSON.parse(Ai(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Di(s,e){let t=sr(s);Ci(Mi(t),{recursive:!0}),$i(t,JSON.stringify(e,null,2)+`
|
|
101
|
+
`)}function Oi(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function Ni(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Li(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Bt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function rr(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function Wt(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Bt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],u=rr(o,Bt(a.meta.trigger));u>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),d=rr(o,Bt(l));d>0&&c.push("title/tags");let g=Math.min(1,u*.7+d*.5);g>=r&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Kt(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
|
|
102
102
|
`)})].join(`
|
|
103
103
|
|
|
104
|
-
`)}kn();yt();var Gt="turn-progress",
|
|
105
|
-
`).slice(-3).join(" ")):!1}var
|
|
104
|
+
`)}kn();yt();var Gt="turn-progress",or={progress:Je({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},qt=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function ir(s){return{agent:s.agent,request:qt(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:qt(e.input,300),...e.result!==void 0?{result:qt(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}yt();var ar="turn-handoff",cr="approval-binding",dr={nextStep:Je({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},ur={approves:Ae("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."})},Fi=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,lr=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,Hi=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Jt(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Hi.test(e.split(`
|
|
105
|
+
`).slice(-3).join(" ")):!1}var ji=/^\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 gr(s){return s.trim().length<=160&&ji.test(s)}function pr(s){return s.trim().length<=160}function mr(s){return{agent:s.agent,channel:s.channel,request:Fi(s.request,1500),agentReplyEnding:lr(s.reply,1200)}}function hr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:lr(s.previousReply,1200)}}var Ui=5*6e4,Bi=3,Wi=12,Ki=24*60*6e4,fr=new Set(["cron","heartbeat","bench","a2a","business"]),qi={observe(){},stop(){}};function yr(s){if(Tn(Gt)==="off")return qi;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,u=()=>{let g;for(let[m,w]of o)w>1&&(!g||w>g.times)&&(g={call:m,times:w});return g},l=g=>{if(c)return;c=!0,a=n.length;let m=ir({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-Wi),repeated:u(),trigger:g});fe(Gt,m,or,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:g}}).finally(()=>{c=!1})},d=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Ui);return d.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let w of m){if(w?.type!=="tool_use")continue;let T=w.input?JSON.stringify(w.input):"",b={tool:w.name||"tool",input:T};n.push(b),typeof w.id=="string"&&r.set(w.id,b);let v=`${b.tool}(${T})`,I=(o.get(v)??0)+1;o.set(v,I),I>=Bi&&!i.has(v)&&(i.add(v),l("repetition"))}else if(g?.type==="user")for(let w of m){if(w?.type!=="tool_result")continue;let T=r.get(w.tool_use_id);T&&(T.result=Array.isArray(w.content)?w.content.map(b=>typeof b?.text=="string"?b.text:"").join(""):typeof w.content=="string"?w.content:"",w.is_error&&(T.error=!0))}},stop(){clearInterval(d)}}}var Qt=new Map,br=(s,e,t)=>`${s}\0${e}\0${t}`;function wr(s){if(fr.has(s.channel)||!Jt(s.reply))return;let e=br(s.agent,s.channel,s.chatId);fe(ar,mr(s),dr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&Qt.set(e,{callId:t.callId,at:Date.now()})})}function xr(s){if(fr.has(s.channel))return;let e=br(s.agent,s.channel,s.chatId),t=Qt.get(e);if(t){Qt.delete(e);let n=xn().store;if(n&&Date.now()-t.at<Ki)try{n.label(t.callId,"userReply",gr(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!pr(s.message)||!Jt(s.previousReply)||fe(cr,hr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),ur,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function Tr(s,e,t=0){return new Promise((n,r)=>{let o,i=()=>{o=setTimeout(()=>r(dt(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};s.then(c=>{a(),n(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function dt(s){let e=s.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}function kr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var $r;function Wd(s){$r=s}function Kd(){return $r}var Ir=64*1024,zi=5*60*1e3,Xi=3e4,Se=".agentx/task-history",Yi=30;function Fe(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function Vi(s,e){let t={};return s?.path?.length&&(t.intentPath=s.path,t.intentPathLabel=s.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Zi(s,e,t={}){let n;try{n=s.listArticles(e)}catch{return""}if(n.length===0)return"";let r=new Map;for(let l of n){let d=l.meta.type||"untyped",g=r.get(d)||[];g.push(l.meta.title),r.set(d,g)}let o=t.maxArticles??400,i=n.length<=o,a=Array.from(r.entries()).sort().map(([l,d])=>i?`**${l}** (${d.length}) \u2014 ${d.sort().join(" \xB7 ")}`:`**${l}** \u2014 ${d.length} article${d.length===1?"":"s"}`).join(`
|
|
106
106
|
`),c=process.argv[1]||"dist/cli.js",u=s.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
107
107
|
node ${c} wiki query "the question" --dir ${u} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","[End Institutional Wiki]"].join(`
|
|
108
|
-
`)}var zt=8*1024;function
|
|
108
|
+
`)}var zt=8*1024;function Sr(s){if(s.length<=zt)return s;let e=s.length-zt;return s.slice(0,zt)+`\u2026[+${e}]`}function vr(s,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let r=typeof n.name=="string"?n.name:"";r&&s.set(r,(s.get(r)??0)+1)}}function ea(s,e){if(!s||s.length===0)return null;for(let t of s)if((e.get(t)??0)===0)return t;return null}function Cr(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=Z();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Sr(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Sr(a):null,at:r})}return}}function ta(){let s="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
109
109
|
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
110
110
|
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
111
111
|
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
@@ -126,25 +126,25 @@ Agent: ${t.slice(0,1e3)}`}],{model:ti,maxTokens:512})).content.trim().match(/\[[
|
|
|
126
126
|
\u2192 ${i}(${a})
|
|
127
127
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Fe(i,800)}
|
|
128
128
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
129
|
-
`:""}}var
|
|
130
|
-
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Hn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=se(e.autonomy),i=o?null:
|
|
129
|
+
`:""}}var Ar=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Ln;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new On;activeSouls=new Map;taskOutputs=new Map;taskAborts=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 nt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new En(void 0,void 0,"unified"),this.memoryStore=new Nn,this.patternStore=new ot,this.rateLimiter=new st,this.tokenTracker=new Ie,this.messageQueue=new rt,Qs({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Rn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new _n({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let u=c.toLowerCase();n.includes(u)&&u.length>o&&(r=i,o=u.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,r);i=Ps(g.messages,e.message??""),c=Rs(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let u={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await fe(Qn,Xn(u),zn,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!Yn(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),Z().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-453FXKHQ.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let u=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",r,...u],source:{channel:r,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,r,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
130
|
+
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Hn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=se(e.autonomy),i=o?null:qs().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let p=await i;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 a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let p=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some($=>$.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 c=e.context?.channel||"api",u=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||o){let p=Date.now(),f=25*6e4,$=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(O=>setTimeout(O,$))}}else{let p=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:u,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let $=this.messageQueue.pendingCount(e.agentId,c,u);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${$})`),{content:"",error:`__queued__:${f}:${$}`}}}let l=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(!l.ok)return this.log(`[${e.agentId}] ${l.reason}`),{content:"",error:l.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let d={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(d),e.runningTaskId=d.id,e.onStart)try{e.onStart(d.id)}catch{}let g=new AbortController;this.taskAborts.set(d.id,{agentId:e.agentId,channel:d.channel,chatId:typeof d.chatId=="string"?d.chatId:"",originalMessage:e.message||"",controller:g});let m={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(d.id,m);let w=p=>{if(p){m.buffer+=p,m.buffer.length>Ir&&(m.buffer=m.buffer.slice(m.buffer.length-Ir));for(let f of m.subscribers)try{f(p)}catch{}}},T=he();e.taskId=T;let b=new Map,v;if(t){let p=ta();v=f=>{let $=p(f);if($&&w($),Cr(T,e.agentId,f),vr(b,f),r)try{r(f)}catch{}}}else v=p=>{if(Cr(T,e.agentId,p),vr(b,p),r)try{r(p)}catch{}};let I=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,D=I?setTimeout(()=>g.abort(new Error(`timed out after ${Math.round(I/1e3)}s`)),I):void 0;D?.unref?.(),g.signal.addEventListener("abort",()=>{this.log(`[${e.agentId}] task ${d.id} aborted in step "${d.step??"start"}" \u2014 ${dt(g.signal).message}`)},{once:!0});let C=(p,f,$=0)=>g.signal.aborted?Promise.reject(dt(g.signal)):(d.step=p,Tr(f(),g.signal,$)),A=!1,_=p=>{if(A)return;A=!0,this.runReleases.delete(d.id),D&&clearTimeout(D),a.activeTasks--;let f=a.runningTasks.findIndex($=>$.id===d.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(d.id),m.done=!0,m.endedAt=new Date;for(let $ of m.subscribers)try{$(`
|
|
131
131
|
[task finished]
|
|
132
|
-
`)}catch{}m.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),
|
|
133
|
-
`).length}L`,J=`[${e.agentId}] ${h}:${x} ${W} | session.messages=${f.length}`+(f.length>0?` first=${$.timestamp.slice(11,19)}(${$.role}:${($.content||"").slice(0,40).replace(/\n/g," ")}) last=${
|
|
134
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${je.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let
|
|
135
|
-
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.`:"",
|
|
132
|
+
`)}catch{}m.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),zi).unref?.();try{let $=m.endedAt,O={id:d.id,agentId:e.agentId,channel:d.channel,chatId:d.chatId,sender:d.sender,message:e.message||"",startedAt:d.startedAt.toISOString(),endedAt:$.toISOString(),durationMs:$.getTime()-d.startedAt.getTime(),ok:!p?.error,error:p?.error,responseText:p?.content||"",transcript:m.buffer};this.persistTaskRecord(O);let W=(O.responseText||O.error||"").trim();if(W){let J=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:J,at:$,ok:O.ok})}}catch($){this.log(`[${e.agentId}] task history persist failed: ${$?.message}`)}this.messageQueue.markDone(e.agentId,c,u).then($=>{if($.length!==0){this.log(`[${e.agentId}] flushing ${$.length} queued message(s)`);for(let O of $){let W=O.originalContext||{channel:O.channel,sender:O.sender,chatId:O.chatId};this.execute({message:O.text,agentId:e.agentId,context:W}).then(J=>this.postQueuedResponseToChannel(e.agentId,W,J)).catch(J=>{this.log(`[${e.agentId}] queued message failed: ${J.message}`)})}}}).catch($=>{this.log(`[${e.agentId}] queue flush failed: ${$.message}`)})};this.runReleases.set(d.id,_),this.messageQueue.markRunning(e.agentId,c,u),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent})`);let h=e.context?.channel||"api",{evaluateRequest:E,selectRequestContext:N}=await import("./request-planner-BRLDCYU5.js"),L=await C("request-gate",()=>E(e.message,e.agentId,h));L.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let x=e.context?.chatId||e.context?.group||e.context?.sender||"default",F=e.context?.sender||"User",S=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,h,x),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${h}:${x}`),Z().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:x,reason:"stale",at:new Date().toISOString()})),e.freshSession||await C("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,h,x,e.seedHistory));let y=[...this.sessions.getSession(e.agentId,h,x).messages].reverse().find(p=>p.role==="agent")?.content;xr({agent:e.agentId,channel:h,chatId:x,message:e.message,previousReply:y,taskId:T}),this.sessions.addUserMessage(e.agentId,h,x,F,e.message);let k=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:h,chatId:x,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(k).toISOString(),taskId:T,resumeOrigin:Hs(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let M,H=this.classifier;if(H&&h!=="a2a"&&!S)try{M=await C("classify",()=>H.classify({text:e.message,channel:h,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(p){this.log(`[classifier] classify failed for ${e.agentId}: ${p?.message||p}`)}let R=this.config.workflows?.matching,z;if(this.config.workflows?.enabled&&R?.enabled&&!o)try{let p=new Gn({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=Jn({agentId:e.agentId,channel:h,message:e.message,intentPath:M?.path},p.list());f&&f.confidence>=R.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${R.mode} reasons=${f.reasons.join(",")||"n/a"}`),R.mode==="auto"&&f.confidence>=R.autoRunThreshold&&(this.workflowAutoRunner?z={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 Mr=this.wikiHub.getAgentWiki(e.agentId),Xt=this.memoryStore.findRelevant(e.message,e.agentId,S?3:8),Yt=this.memoryStore.buildContext(Xt),Vt=this.memoryStore.contextFacts(Xt),Pr=this.patternStore.findRelevant(e.message,e.agentId,5),Rr=this.patternStore.buildContext(Pr),Zt="";if(!S)try{let{loadLocalSkills:p,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),$=await C("skills",()=>p(a.def.workspace));Zt=f($,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,h,x):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,h,x):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,h,x):void 0;if(j&&this.sessions.isSessionStale(e.agentId,h,x)&&(this.log(`[${e.agentId}] session stale for ${h}:${x}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,x,"stale"),this.sessions.clearClaudeSessionId(e.agentId,h,x),Z().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:x,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,h,x)){let p=this.sessions.getLastTurnContextTokens(e.agentId,h,x);this.log(`[${e.agentId}] tier-2 rotation for ${h}:${x} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,x,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,h,x),Z().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:x,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,h,x)){let p=this.sessions.getTurnCount(e.agentId,h,x);this.log(`[${e.agentId}] max-turns rotation for ${h}:${x} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,x,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,h,x),Z().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:x,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let p=j;await C("rotate",()=>this.maybeRotateForContinuity(e,a,h,x,p))&&(j=void 0)}try{let p=await C("compact",()=>this.sessions.compactIfNeeded(e.agentId,h,x,this.memoryStore));if(p.compacted){let f=p.qualityScore??"?",$=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${h}:${x} (quality: ${f}%, ${$} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let O=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${O.overallScore} (lexicon=${O.lexiconDecay}, tools=${O.toolShift}, semantic=${O.semanticDrift})`),O.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${O.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let _r=process.env.AGENTX_CONTEXT_SURGERY==="1",Er=S?{maxMessages:8,maxChars:2400}:_r&&kr(h,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Dr=!j&&!S?Zi(Mr,e.agentId):void 0,He=j?void 0:this.sessions.buildHistoryContext(e.agentId,h,x,Er),Or=j?void 0:this.sessions.getRotationMemo(e.agentId,h,x)??void 0,en,tn=[];if(this.config.procedures?.injection?.enabled&&!j&&!S)try{let p=new Ne({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=Wt(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){en=Kt(f),tn=f.map($=>({id:$.procedure.meta.id,title:$.procedure.meta.title}));for(let $ of f)this.log(`[${e.agentId}] procedure match ${$.procedure.meta.id} score=${$.score.toFixed(2)} (${$.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(le&&le.cat)try{let f=this.sessions.getSession(e.agentId,h,x).messages,$=f[0],O=f[f.length-1],W=He===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${He.length}c/${He.split(`
|
|
133
|
+
`).length}L`,J=`[${e.agentId}] ${h}:${x} ${W} | session.messages=${f.length}`+(f.length>0?` first=${$.timestamp.slice(11,19)}(${$.role}:${($.content||"").slice(0,40).replace(/\n/g," ")}) last=${O.timestamp.slice(11,19)}(${O.role}:${(O.content||"").slice(0,40).replace(/\n/g," ")})`:"");le.cat("context",J)}catch(p){le.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let nn;if(a.def.contextReferences&&!j)try{let p=a.def.workspace,f=this.referencesCache.get(p);if(!f){let[O,W]=await C("references",()=>Promise.all([wt(a.def.workspace),xt(a.def.workspace)]));if(O.byId.size===0&&W.recipes.length===0){let[J,ue]=await C("references",()=>Promise.all([wt(process.cwd()),xt(process.cwd())]));f={refs:J,recipes:ue}}else f={refs:O,recipes:W};this.referencesCache.set(p,f)}let $=jn({agentId:e.agentId,intentTags:M?.path,message:e.message},f.recipes,f.refs);$.cards.length>0&&(nn=Fn($.cards,500*4)),$.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${$.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let sn=this.sessions.getCrossSessionSummary(e.agentId,h,x,e.message),rn,je=Ms(e.message);if(je)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:h,chatId:x,lookbackDays:je.lookbackDays,limit:12});if(p.turns.length>0){let f=[`[Long-memory recall \u2014 last ${je.lookbackDays}d on this chat (cue-triggered)]`],$=[...p.turns].sort((O,W)=>O.ts.localeCompare(W.ts));for(let O of $){let W=O.ts.slice(11,16)+" "+O.day,J=O.role==="user"?O.senderName||"User":O.senderName||"Agent";f.push(`${W} ${J}: ${O.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]"),rn=f.join(`
|
|
134
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${je.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let Nr=S?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",on,an,cn=!1;if(Nr==="planner"&&!L.active&&h!=="voice"&&h!=="desktop"){try{let{planContext:p}=await import("./context-planner-LJT5IKH6.js"),f=await C("plan-context",()=>p({agentId:e.agentId,channel:h,chatId:x,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(cn=!0,on=f.sessionHistory,Yt=f.memoryContext,Vt=f.memoryFacts,sn=f.crossChatContext,an=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)`)}cn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,h,x),j=void 0)}let ut=`${e.agentId}:${h}:${x}`,Ue=Cn(e.message);Ue&&(Ue==="default"?(this.activeSouls.delete(ut),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(ut,Ue),this.log(`[${e.agentId}] Soul switched to: ${Ue}`)));let Lr=this.activeSouls.get(ut),Fr=Sn(a.def.workspace,Lr),Hr=vn(Fr),jr=this.agentMemory.indexMarkdown(e.agentId),Ur=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
135
|
+
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.`:"",Br=a.def.richMessages!==!1&&(h==="telegram"||h==="whatsapp")?["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text."].join(`
|
|
136
136
|
`):"",dn="";if(a.def.workspace){let p=B(a.def.workspace,"CLAUDE.md");if(Y(p))try{let f=Le(p,"utf-8");dn=`[Project CLAUDE.md]
|
|
137
137
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
138
138
|
|
|
139
|
-
[CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Be=e.context?.runbookPath,lt=[];if(Be&&Y(Be)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,$=4e3,
|
|
139
|
+
[CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Be=e.context?.runbookPath,lt=[];if(Be&&Y(Be)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,$=4e3,O=16e3;for(let W of p){if(f>=O)break;let J=B(Be,W);if(Y(J))try{let ue=Le(J,"utf-8"),P=ue.length>$?ue.slice(0,$)+`
|
|
140
140
|
|
|
141
141
|
[${W} truncated to ${$} bytes]`:ue;lt.push(`[Project Runbook \u2014 ${W} from ${Be}]
|
|
142
|
-
${P}`),f+=P.length}catch{}}}let
|
|
142
|
+
${P}`),f+=P.length}catch{}}}let Wr=lt.length>0?lt.join(`
|
|
143
143
|
|
|
144
|
-
`):"",gt=[a.def.systemPrompt||"",
|
|
144
|
+
`):"",gt=[a.def.systemPrompt||"",Ur,Br,dn,Wr,Hr||"",jr||""].filter(p=>p.trim().length>0).join(`
|
|
145
145
|
|
|
146
|
-
`)||void 0,un={channel:h,chatId:x,channelScope:e.context?.group?"group":h==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,h),systemPrompt:a.def.systemPrompt,sender:F,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:S||
|
|
147
|
-
`),
|
|
146
|
+
`)||void 0,un={channel:h,chatId:x,channelScope:e.context?.group?"group":h==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,h),systemPrompt:a.def.systemPrompt,sender:F,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:S||kr(h,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:S?void 0:Rr||void 0,procedureContext:en,references:nn,skillInjection:Zt||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:on??He,memoryContext:Yt||void 0,crossChatContext:sn||void 0,longMemoryRecall:rn||void 0,wikiContext:Dr,handoverNote:this.buildHandoverNote(e.agentId,h,x),rotationMemo:Or,intent:M?{path:M.path,pathLabel:M.pathLabel,pathId:M.pathId,axes:M.axes,leaf:M.leaf,status:M.status}:void 0,message:e.message},We=L.active&&L.preprocess?await C("select-context",()=>N(un)):{input:un,excluded:[]};We.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${We.excluded.join(", ")}`);let Ke=Fs(We.input,S?{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),Kr=Dn(Ke,{memory:Vt,procedures:tn,wikiContext:We.input.wikiContext}),pt=(Ke?.length??0)+(gt?.length??0)+(e.message?.length??0),qe={history:Ke?.length??0,sysPrompt:gt?.length??0,message:e.message?.length??0},ln=er(e.agentId,h,x);tr(ln,pt,qe);let gn=nr(ln);gn&&this.log(`[${e.agentId}] ${gn}`),pt>16e3&&this.log(`[${e.agentId}] large context for ${h}:${x}: ${pt} bytes (history=${qe.history}, sysPrompt=${qe.sysPrompt}, message=${qe.message})`);let mt,pn=In(a.def.tier,this.config.decisions.routing);if(!e.model&&pn&&(!L.active||L.preprocess))try{let{routeTaskModel:p}=await import("./routing-DP6S7OJL.js"),f=await C("route-model",()=>p({message:e.message,agent:e.agentId,channel:h,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,h,x),cheapModel:pn}));f.downgraded&&(mt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let qr={...e,systemPromptAppend:gt,...mt?{model:mt}:{}},de,mn=yr({agent:e.agentId,request:e.message,taskId:T,budgetMinutes:a.def.maxExecutionMinutes??20}),Gr=v;v=p=>{mn.observe(p),Gr?.(p)};try{let p=this.workflowAutoRunner;if(z&&p){let U=z;try{let G=await C("workflow-auto-run",()=>p({workflowId:U.workflowId,agentId:e.agentId,channel:h,chatId:x,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:h,chatId:x,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:M?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${z.workflowId} run=${G.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),de={content:"",duration:0,metadata:{handledByWorkflow:z.workflowId,workflowRunId:G.runId,workflowMatchConfidence:z.confidence}},de}catch(G){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${G?.message||G}`)}}if(a.def.tier==="claude-code"){let U=a.def.persistentProcess?Ye():null,G=U!=null&&U.hasLive({agentId:e.agentId,channel:h,chatId:x}),ne=!!j||G,V=[Gs(ne),Vs(ne)].find(Ce=>Ce&&Ce.abort);if(V){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${V.reason}`);let Ce={content:"",error:V.message,duration:0};if(!t){m.buffer=`[error] ${V.message}`;for(let Jr of m.subscribers)try{Jr(m.buffer)}catch{}}return de=Ce,Ce}Xs();let ve=Zs();ve&&this.log(`[${e.agentId}] ${ve}`)}let f=a.def.tier==="claude-code",$=f?t:(U,G)=>{U&&w(U),t&&t(U,G)},O=!1,W=f?n:U=>{U&&(O?w(U):(w(`\u{1F4AD} ${U}`),O=!0)),n&&n(U)},J=()=>{O&&(w(`
|
|
147
|
+
`),O=!1)},ue=f?$:$?(U,G)=>{J(),$(U,G)}:void 0,P=await C("agent",()=>Cs(a.def,qr,this.providers,ue,Ke,j,v,g.signal,W),Xi);if(!P.error){let U=ea(a.def.toolUseRequired,b);if(U){let G=Array.from(b.entries()).map(([ne,Ge])=>`${ne}=${Ge}`).join(", ")||"none";P.error=`tool_required_not_called: ${U} (invoked: ${G})`,P.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${G}`)}}de=P;let te=P.usage?Ns(P.usage):void 0;if(Z().emit("task:completed",{taskId:T,agentId:e.agentId,channel:h,chatId:x,durationMs:Date.now()-k,error:P.error||void 0,inputTokens:te?.inputTokens,outputTokens:te?.outputTokens,cacheReadTokens:te?.cacheReadTokens,cacheCreateTokens:te?.cacheCreateTokens,tier2InputTokens:te?.tier2InputTokens,tier2OutputTokens:te?.tier2OutputTokens,tier2CacheReadTokens:te?.tier2CacheReadTokens,tier2CacheCreateTokens:te?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:L.arm,numTurns:P.numTurns,injectedContext:Kr,finalResponse:P.content||void 0,billedModel:P.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&(P.content||P.error)){let U=P.error?`[error] ${P.error}`:P.content;m.buffer=U;for(let G of m.subscribers)try{G(U)}catch{}}if(P.error)a.errors++,this.log(`[${e.agentId}] error: ${P.error}`);else{if(this.sessions.addAgentMessage(e.agentId,h,x,P.content),wr({agent:e.agentId,channel:h,chatId:x,request:e.message,reply:P.content,taskId:T}),P.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,h,x,P.claudeSessionId),P.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,h,x,P.codexSessionId),P.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,h,x,P.opencodeSessionId),(P.claudeSessionId||P.codexSessionId||P.opencodeSessionId)&&P.usage&&this.sessions.recordTurnUsage(e.agentId,h,x,P.usage,P.contextTokens),P.usage){let V=P.contextTokens,ve=(P.usage.inputTokens||0)+(P.usage.cacheReadTokens||0)+(P.usage.cacheCreateTokens||0);(V??ve)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${h}:${x}: context=${V??"n/a"} tokens (cumulative turn total=${ve}) \u2014 next turn will rotate`)}if(Mn({channel:h,content:`User: ${e.message}`,responseLength:P.content.length}).capture){try{let V=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:V,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:h,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
148
148
|
|
|
149
|
-
Agent: ${P.content}`,meta:
|
|
150
|
-
//# sourceMappingURL=chunk-
|
|
149
|
+
Agent: ${P.content}`,meta:Vi(M,e.context)})}catch{}Pn(e.agentId,e.message,P.content,{channel:h,chatId:x,sender:F},this.memoryStore).catch(()=>{}),Ws(e.agentId,e.message,P.content,{channel:h,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=P.billedModel||e.model||a.def.model,ne=e.context?.channel,Ge=ne&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ne}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,P.duration||0,P.usage,e.message.length,P.content.length,!1,G,ne,Ge),this.log(`[${e.agentId}] completed in ${P.duration}ms`+(P.tokensUsed?` (${P.tokensUsed} tokens)`:""))}return P}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=ze(p.message);return de={content:"",error:Xe(f),errorKind:f.kind},de}finally{mn.stop(),_(de)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=B(process.cwd(),Se,this.safe(e.agentId),t);Y(n)||Gi(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Qi(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=B(process.cwd(),Se,this.safe(e));if(!Y(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),u=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let d of[u,c]){let g=B(a,d);if(Y(g))try{for(let m of ee(g)){if(!m.endsWith(".json"))continue;let w=m.split("-")[0],T=parseInt(w,10);if(!Number.isFinite(T)||T<i||T>n)continue;let b=Math.floor((n-T)/36e5),v=t-1-b;v>=0&&v<t&&o[v]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Se);if(!Y(e))return 0;let t=0;for(let n of ee(e)){let r=B(e,n),o;try{o=ee(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ee(a).filter(u=>u.endsWith(".json")).sort().reverse()}catch{continue}for(let u of c)try{let l=JSON.parse(Le(B(a,u),"utf-8")),d=(l.responseText||l.error||"").trim();if(!d)continue;let g=d.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Yi){let t=B(process.cwd(),Se);if(!Y(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ee(t)){let i=B(t,o),a;try{a=ee(i)}catch{continue}for(let c of a){let u=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(u)||u>=n))try{Ji(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Se,this.safe(e));if(!Y(n))return[];let r=ee(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=B(n,i),c;try{c=ee(a).filter(u=>u.endsWith(".json"))}catch{continue}c.sort().reverse();for(let u of c){if(o.length>=t)break;try{let l=JSON.parse(Le(B(a,u),"utf-8")),{transcript:d,responseText:g,...m}=l;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Se,this.safe(e));if(!Y(n))return null;let r=this.safe(t),o=ee(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(Y(a))try{return JSON.parse(Le(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=qn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:u}=o,l=o.controller.signal.aborted,d=!1;l&&u&&(d=this.sessions.removeLastUserMessageIfMatches(i,a,c,u)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),m=!1;if(r.replace){let w=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(w))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${w}`),m=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${d?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:m,edited:d,pending:g}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(u=>{let l=!1,d=g=>{l||(l=!0,u(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>d({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{g.error?.startsWith("__queued__")?d({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?d({ok:!1,status:500,error:g.error||"run did not start"}):d({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>d({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{Vn as a,Zn as b,ma as c,ts as d,uo as e,ns as f,os as g,Ca as h,Pa as i,Ra as j,vo as k,Is as l,Po as m,Ro as n,_o as o,Cs as p,nt as q,st as r,ic as s,Lt as t,Z as u,Ks as v,di as w,qs as x,Ne as y,Ei as z,Di as A,Oi as B,Ni as C,Li as D,Wt as E,Wd as F,Kd as G,Vi as H,Zi as I,zt as J,Sr as K,vr as L,ea as M,Cr as N,Ar as O};
|
|
150
|
+
//# sourceMappingURL=chunk-YEV6W34S.js.map
|