agentix-cli 0.150.0 → 0.151.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/{App-2O2UUZGG.js → App-WAWZFD66.js} +2 -2
- package/dist/{ChatApp-YU4NF63L.js → ChatApp-TRJIS3O4.js} +2 -2
- package/dist/{absorb-eval-WHWOJYDX.js → absorb-eval-CFWLHUTB.js} +2 -2
- package/dist/{agent-NLCR6VBE.js → agent-6KCTPI7E.js} +2 -2
- package/dist/{board-dashboard-VPDXHHWC.js → board-dashboard-5V6RHW3E.js} +16 -16
- package/dist/{board-dashboard-VPDXHHWC.js.map → board-dashboard-5V6RHW3E.js.map} +1 -1
- package/dist/{chunk-GMMRBTLQ.js → chunk-2GJQDJBF.js} +2 -2
- package/dist/{chunk-AONY6U45.js → chunk-4GXJMHSA.js} +2 -2
- package/dist/{chunk-WGPMUWX7.js → chunk-5I7NJMK6.js} +3 -3
- package/dist/{chunk-Y5GI35AZ.js → chunk-6LFOX6Q5.js} +304 -294
- package/dist/chunk-6LFOX6Q5.js.map +1 -0
- package/dist/{chunk-ATCIRFH6.js → chunk-ALE354ZC.js} +2 -2
- package/dist/{chunk-GRI5HOPC.js → chunk-C5UTFHPB.js} +2 -2
- package/dist/{chunk-UZWF7PFH.js → chunk-CBML7UCP.js} +5 -5
- package/dist/{chunk-5QXRPYOY.js → chunk-CTQ25CUL.js} +2 -2
- package/dist/{chunk-JOHDOEZ4.js → chunk-DFGANY25.js} +2 -2
- package/dist/{chunk-EIY2HRAS.js → chunk-DJQIJF4R.js} +2 -2
- package/dist/{chunk-DWOERPBG.js → chunk-DWXCZRBJ.js} +2 -2
- package/dist/{chunk-5IHUZVPU.js → chunk-EJTKLVIW.js} +2 -2
- package/dist/{chunk-E7LPZAXP.js → chunk-ETBDN5WX.js} +2 -2
- package/dist/{chunk-6TJNWUMA.js → chunk-FGJNSYHM.js} +3 -3
- package/dist/{chunk-NW4N67TU.js → chunk-IMITYHBT.js} +2 -2
- package/dist/chunk-L6IW6HWE.js +64 -0
- package/dist/chunk-L6IW6HWE.js.map +1 -0
- package/dist/{chunk-IGA3T3ZT.js → chunk-LVS5ESTS.js} +2 -2
- package/dist/chunk-O7SYQXKS.js +181 -0
- package/dist/chunk-O7SYQXKS.js.map +1 -0
- package/dist/chunk-OSH2PEBH.js +2 -0
- package/dist/{chunk-JXF54PT7.js.map → chunk-OSH2PEBH.js.map} +1 -1
- package/dist/{chunk-QZ6VBDMX.js → chunk-PUSBK2OQ.js} +8 -8
- package/dist/chunk-PUSBK2OQ.js.map +1 -0
- package/dist/{chunk-OWMKQ4HZ.js → chunk-Q5NLNLD5.js} +2 -2
- package/dist/{chunk-S22IBRY6.js → chunk-RGJZV5RY.js} +2 -2
- package/dist/{chunk-NMYC5RW7.js → chunk-TZZBGWLX.js} +2 -2
- package/dist/{chunk-3HVRWULP.js → chunk-UALK4F3W.js} +2 -2
- package/dist/chunk-V3VWYIJ3.js +7 -0
- package/dist/chunk-V3VWYIJ3.js.map +1 -0
- package/dist/{chunk-6QFDFYI7.js → chunk-X3T2GCSI.js} +2 -2
- package/dist/chunk-X6C6U4GL.js +5 -0
- package/dist/chunk-X6C6U4GL.js.map +1 -0
- package/dist/{chunk-2MW32M2D.js → chunk-XD7HTMOP.js} +2 -2
- package/dist/{chunk-6YNRLI6I.js → chunk-XVJXXELY.js} +2 -2
- package/dist/{chunk-BZ6Y264Z.js → chunk-YGDJV4ZZ.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-A2N6ETK2.js → client-VT7GT3SK.js} +2 -2
- package/dist/{config-2QM2WTI2.js → config-NZS2UTHI.js} +2 -2
- package/dist/{config-mutate-UJS4F7BT.js → config-mutate-LINLC354.js} +2 -2
- package/dist/config-mutator-FUMSW5HD.js +2 -0
- package/dist/{contributions-43FWZOGF.js → contributions-67B3BYLV.js} +2 -2
- package/dist/doctor-FOKX4K2G.js +2 -0
- package/dist/{follow-up-tool-VB7K6HCL.js → follow-up-tool-JOIOYOON.js} +2 -2
- package/dist/{grants-2S33F2LV.js → grants-QXF7N6SS.js} +2 -2
- package/dist/{hub-JNNNUAZM.js → hub-QETWDYPD.js} +2 -2
- package/dist/index.d.ts +42 -0
- package/dist/index.js +1 -1
- package/dist/{program-ZNTQK36Z.js → program-XFZBG3EI.js} +189 -189
- package/dist/program-XFZBG3EI.js.map +1 -0
- package/dist/{promote-VFYVWVTL.js → promote-WNYNTGKC.js} +2 -2
- package/dist/{query-RB2MU2HV.js → query-ZU2DDCEH.js} +2 -2
- package/dist/{query-settings-5B54WHCS.js → query-settings-BXRIJWWO.js} +2 -2
- package/dist/{registry-6OX7U6FV.js → registry-7BITIEQ2.js} +2 -2
- package/dist/{request-planner-TUHVEYSF.js → request-planner-DLQP2NV6.js} +2 -2
- package/dist/{review-candidates-FDYTGG2N.js → review-candidates-3BMHLIBW.js} +2 -2
- package/dist/{routing-U35SFPEI.js → routing-FVZCQJ6T.js} +2 -2
- package/dist/schedule-tool-TDVJHRQX.js +2 -0
- package/dist/{scheduler-H2QHWNQ2.js → scheduler-SYI5MZ3H.js} +2 -2
- package/dist/{seat-EB3KJMIE.js → seat-6JF7BYM7.js} +2 -2
- package/dist/{select-IU4IOVSO.js → select-JT4I3JOH.js} +2 -2
- package/dist/{set-enabled-64BSJ7LR.js → set-enabled-JRGFKA3S.js} +2 -2
- package/dist/{tool-B23ACEHV.js → tool-P6GVYNDO.js} +2 -2
- package/dist/{tool-W3CIQZJ7.js → tool-UDOUNWQT.js} +2 -2
- package/dist/{wiki-4KMRUD5C.js → wiki-MTZHDFHK.js} +2 -2
- package/dist/wiki-enrich-CHR4RCRE.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-A76PNG4E.js +0 -4
- package/dist/chunk-A76PNG4E.js.map +0 -1
- package/dist/chunk-JXF54PT7.js +0 -2
- package/dist/chunk-P34VSROA.js +0 -7
- package/dist/chunk-P34VSROA.js.map +0 -1
- package/dist/chunk-PXKIPU27.js +0 -64
- package/dist/chunk-PXKIPU27.js.map +0 -1
- package/dist/chunk-QZ6VBDMX.js.map +0 -1
- package/dist/chunk-Y5GI35AZ.js.map +0 -1
- package/dist/chunk-Z7GEW2SR.js +0 -174
- package/dist/chunk-Z7GEW2SR.js.map +0 -1
- package/dist/config-mutator-VWR3SMD3.js +0 -2
- package/dist/doctor-IN6MWP6I.js +0 -2
- package/dist/program-ZNTQK36Z.js.map +0 -1
- package/dist/schedule-tool-EPQKUYJX.js +0 -2
- package/dist/wiki-enrich-N4GLW2JX.js +0 -2
- /package/dist/{App-2O2UUZGG.js.map → App-WAWZFD66.js.map} +0 -0
- /package/dist/{ChatApp-YU4NF63L.js.map → ChatApp-TRJIS3O4.js.map} +0 -0
- /package/dist/{absorb-eval-WHWOJYDX.js.map → absorb-eval-CFWLHUTB.js.map} +0 -0
- /package/dist/{agent-NLCR6VBE.js.map → agent-6KCTPI7E.js.map} +0 -0
- /package/dist/{chunk-GMMRBTLQ.js.map → chunk-2GJQDJBF.js.map} +0 -0
- /package/dist/{chunk-AONY6U45.js.map → chunk-4GXJMHSA.js.map} +0 -0
- /package/dist/{chunk-WGPMUWX7.js.map → chunk-5I7NJMK6.js.map} +0 -0
- /package/dist/{chunk-ATCIRFH6.js.map → chunk-ALE354ZC.js.map} +0 -0
- /package/dist/{chunk-GRI5HOPC.js.map → chunk-C5UTFHPB.js.map} +0 -0
- /package/dist/{chunk-UZWF7PFH.js.map → chunk-CBML7UCP.js.map} +0 -0
- /package/dist/{chunk-5QXRPYOY.js.map → chunk-CTQ25CUL.js.map} +0 -0
- /package/dist/{chunk-JOHDOEZ4.js.map → chunk-DFGANY25.js.map} +0 -0
- /package/dist/{chunk-EIY2HRAS.js.map → chunk-DJQIJF4R.js.map} +0 -0
- /package/dist/{chunk-DWOERPBG.js.map → chunk-DWXCZRBJ.js.map} +0 -0
- /package/dist/{chunk-5IHUZVPU.js.map → chunk-EJTKLVIW.js.map} +0 -0
- /package/dist/{chunk-E7LPZAXP.js.map → chunk-ETBDN5WX.js.map} +0 -0
- /package/dist/{chunk-6TJNWUMA.js.map → chunk-FGJNSYHM.js.map} +0 -0
- /package/dist/{chunk-NW4N67TU.js.map → chunk-IMITYHBT.js.map} +0 -0
- /package/dist/{chunk-IGA3T3ZT.js.map → chunk-LVS5ESTS.js.map} +0 -0
- /package/dist/{chunk-OWMKQ4HZ.js.map → chunk-Q5NLNLD5.js.map} +0 -0
- /package/dist/{chunk-S22IBRY6.js.map → chunk-RGJZV5RY.js.map} +0 -0
- /package/dist/{chunk-NMYC5RW7.js.map → chunk-TZZBGWLX.js.map} +0 -0
- /package/dist/{chunk-3HVRWULP.js.map → chunk-UALK4F3W.js.map} +0 -0
- /package/dist/{chunk-6QFDFYI7.js.map → chunk-X3T2GCSI.js.map} +0 -0
- /package/dist/{chunk-2MW32M2D.js.map → chunk-XD7HTMOP.js.map} +0 -0
- /package/dist/{chunk-6YNRLI6I.js.map → chunk-XVJXXELY.js.map} +0 -0
- /package/dist/{chunk-BZ6Y264Z.js.map → chunk-YGDJV4ZZ.js.map} +0 -0
- /package/dist/{client-A2N6ETK2.js.map → client-VT7GT3SK.js.map} +0 -0
- /package/dist/{config-2QM2WTI2.js.map → config-NZS2UTHI.js.map} +0 -0
- /package/dist/{config-mutate-UJS4F7BT.js.map → config-mutate-LINLC354.js.map} +0 -0
- /package/dist/{config-mutator-VWR3SMD3.js.map → config-mutator-FUMSW5HD.js.map} +0 -0
- /package/dist/{contributions-43FWZOGF.js.map → contributions-67B3BYLV.js.map} +0 -0
- /package/dist/{doctor-IN6MWP6I.js.map → doctor-FOKX4K2G.js.map} +0 -0
- /package/dist/{follow-up-tool-VB7K6HCL.js.map → follow-up-tool-JOIOYOON.js.map} +0 -0
- /package/dist/{grants-2S33F2LV.js.map → grants-QXF7N6SS.js.map} +0 -0
- /package/dist/{hub-JNNNUAZM.js.map → hub-QETWDYPD.js.map} +0 -0
- /package/dist/{promote-VFYVWVTL.js.map → promote-WNYNTGKC.js.map} +0 -0
- /package/dist/{query-RB2MU2HV.js.map → query-ZU2DDCEH.js.map} +0 -0
- /package/dist/{query-settings-5B54WHCS.js.map → query-settings-BXRIJWWO.js.map} +0 -0
- /package/dist/{registry-6OX7U6FV.js.map → registry-7BITIEQ2.js.map} +0 -0
- /package/dist/{request-planner-TUHVEYSF.js.map → request-planner-DLQP2NV6.js.map} +0 -0
- /package/dist/{review-candidates-FDYTGG2N.js.map → review-candidates-3BMHLIBW.js.map} +0 -0
- /package/dist/{routing-U35SFPEI.js.map → routing-FVZCQJ6T.js.map} +0 -0
- /package/dist/{schedule-tool-EPQKUYJX.js.map → schedule-tool-TDVJHRQX.js.map} +0 -0
- /package/dist/{scheduler-H2QHWNQ2.js.map → scheduler-SYI5MZ3H.js.map} +0 -0
- /package/dist/{seat-EB3KJMIE.js.map → seat-6JF7BYM7.js.map} +0 -0
- /package/dist/{select-IU4IOVSO.js.map → select-JT4I3JOH.js.map} +0 -0
- /package/dist/{set-enabled-64BSJ7LR.js.map → set-enabled-JRGFKA3S.js.map} +0 -0
- /package/dist/{tool-B23ACEHV.js.map → tool-P6GVYNDO.js.map} +0 -0
- /package/dist/{tool-W3CIQZJ7.js.map → tool-UDOUNWQT.js.map} +0 -0
- /package/dist/{wiki-4KMRUD5C.js.map → wiki-MTZHDFHK.js.map} +0 -0
- /package/dist/{wiki-enrich-N4GLW2JX.js.map → wiki-enrich-CHR4RCRE.js.map} +0 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import{$ as Hr,H as Mr,I as Rr,J as Pr,L as _r,M as Er,N as Or,O as Dr,R as Nr,S as Lr,V as Ur,W as Fr,a as pr,b as fr,ba as jr,d as hr,f as Xe,l as At,m as Ar,t as Ct,v as Cr}from"./chunk-YGDJV4ZZ.js";import{b as mr}from"./chunk-MEFPXHQJ.js";import{a as $r}from"./chunk-W4YR2RO2.js";import{a as gr}from"./chunk-5TTHN7DP.js";import{b as wr,c as xn,d as xr,e as $t,h as Sr}from"./chunk-XVJXXELY.js";import{e as ur,f as lr}from"./chunk-36AXN6ZB.js";import{a as wn,b as yr}from"./chunk-J3SOEFRE.js";import{a as bn,b as br}from"./chunk-SIU6STB2.js";import{e as Ir,i as Tr,j as kr,k as vr}from"./chunk-X5C5W3E4.js";import{a as dr}from"./chunk-XD7HTMOP.js";import{g as ar,h as cr}from"./chunk-DJQIJF4R.js";import{c as Qs,f as Xs}from"./chunk-2GJQDJBF.js";import{s as Js,v as vt,w as zs,y as we,z as yn}from"./chunk-Q5NLNLD5.js";import{a as Qe,b as Oe,f as kt}from"./chunk-72SZI2UW.js";import{a as Ee,b as gn}from"./chunk-FCPTN6NF.js";import{a as Ys,c as Zs}from"./chunk-MYVHVJWZ.js";import{d as De,g as Vs,h as Ce}from"./chunk-6TURWSMN.js";import{a as er,b as tr,c as nr,d as sr,l as rr}from"./chunk-AV7T3SYT.js";import{a as or,b as ir}from"./chunk-Y5MFVVTM.js";import{c as Ds,d as Ns}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ua as gc,V as Hs,X as mn,Z as uc,aa as js,ea as lc,ka as Bs,la as hn,ma as Ws,na as ze,oa as qs,pa as Gs,va as Ks}from"./chunk-L6IW6HWE.js";import{g as Je,h as cc}from"./chunk-BRK6M6LA.js";import{f as fn,n as dc}from"./chunk-UIBUZ2N3.js";import{a as Ls,b as ge,c as Us,d as Fs,e as pn}from"./chunk-2QNT5JDS.js";yn();kt();var Mt="tool-set",Br=["answer","code","full"],Wr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},pc=.1;function Gr(n){return{task:qr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:qr(n.agentPrompt,600)}:{}}}var Kr={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Jr(n,e=pc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Sn(s.answer),o=Sn(s.code),i=Sn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function zr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Wr.answer.includes(t))?"answer":e.every(t=>Wr.code.includes(t))?"code":"full"}function Qr(n,e){return Br.indexOf(n)<Br.indexOf(e)}function Sn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function qr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Xr=!1;function Yr(n,e){let t=vt(Mt);if(t!=="off")return t==="active"&&!Xr&&(Xr=!0,e(`[decisions] seat "${Mt}" is set to active, but only shadow is built: it records and changes nothing`)),we(Mt,Gr(n),Kr,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Jr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Zr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=zr(r);zs(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Qr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function fc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Vr(n,e){let t=fc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function In(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}yn();kt();var eo="session-continuity",to={continues:Qe("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:Qe("Does the new request refer to something stated earlier in the conversation?")};function no(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Tn(n.message,1200),previousRequest:n.previousMessage?Tn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Tn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function so(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Tn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ut}from"execa";import{spawn as mc}from"node:child_process";import{createHash as hc}from"node:crypto";import{createInterface as yc}from"node:readline";var be=class extends Error{},wc=n=>mc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),kn=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(),yc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
|
+
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},vn=class{constructor(e=wc,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=hc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[$])=>x.localeCompare($))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new be("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,$])=>!$.connection.busy);if(!x)throw new be("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new kn(e,this.launchProcess)}}catch{throw new be("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,u,l,p,m=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),y=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(y),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let R=new Promise((E,k)=>{i.failTurn=k,i.notify=(L,N)=>{if(N?.threadId!==u)return;let O=N.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:L.replace("/","."),...O?{item:{...O,type:B[O.type]||O.type}}:{}}),L==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(c=O.text),L==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=N.delta,e.onDelta?.(N.delta,d)),L==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}L==="turn/completed"&&(N.turn.status==="completed"?E():k(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return R.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await R,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new be(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(y),clearTimeout(b),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ro=new vn;import{execFile as Fc}from"child_process";import{StringDecoder as tt}from"string_decoder";import{mkdtempSync as To,readFileSync as ko,rmSync as vo}from"fs";import{join as Nt}from"path";import{tmpdir as $o}from"os";function Rt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Pt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function _t(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var oo=null;function Et(){return oo}function Fg(n){oo=n}function Ye(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function bc(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Ne=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},io=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Ye(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=bc(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Ne(`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 Ne(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ye(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Ye(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";s.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as xc}from"child_process";import{randomUUID as Sc}from"crypto";import{existsSync as Ic,readFileSync as Tc}from"fs";import{resolve as kc}from"path";function vc(n){let e=kc(n,"CLAUDE.md");if(!Ic(e))return null;try{let t=Tc(e,"utf8");return rr(t)}catch{return null}}var $c=20*60*1e3,Ac=5e3,Ze=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Cc(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var ao=class{constructor(e={}){this.opts=e}spawn(e,t){return new $n(e,t,this.opts)}},$n=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=xc(r,o,{cwd:t.workspace,env:Ce(Cc({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:vc(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=Sc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
|
+
`);let d=e.deadlineMs??$c,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new Ze(d)),l=!1,p=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let h=await this.nextEvent(m);if(h===null&&this.killReason)throw new Ve(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let b=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ac);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
|
+
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};pn();dc();gn();import{resolve as co,join as uo}from"path";var Mc=4e3;function Ot(n){try{let e=uo(co(n.root),".agentx","db.sqlite"),t=fn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,Mc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
5
|
+
(id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
|
|
6
|
+
verdict, effective_action, mode, severity, approver, ms)
|
|
7
|
+
VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
|
|
8
|
+
@verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:s,ts:Date.now(),agent_id:n.input.agentId??null,task_id:n.taskId??null,tool:n.input.tool,command:r,resolved_target:n.verdict.resolvedTarget,matched_rule:n.verdict.ruleId,verdict:n.verdict.action,effective_action:n.verdict.effectiveAction,mode:n.mode,severity:n.verdict.severity,approver:n.approver??null,ms:n.ms??null}),s}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
|
|
9
|
+
`),null}}function Zg(n){let e=uo(co(n.root),".agentx","db.sqlite"),t=fn({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}pn();var Rc=50,Pc=6*60*60*1e3,Dt=null,Le=new Map;function np(n){Dt=n===null?null:String(n)}function go(){return Dt}function _c(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function po(n,e,t){if(!ge(n))return{args:[]};if(!Dt)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:_c(Dt,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function fo(n,e){return!ge(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Ec(n){for(let[e,t]of Le)n-t.at>Pc&&Le.delete(e)}function Oc(n,e){let t=Date.now();Ec(t);let s=Le.get(n)??{at:t,blocks:[]};s.blocks.length<Rc&&s.blocks.push(e),s.at=t,Le.set(n,s)}function mo(n){if(!n)return[];let e=Le.get(n);return Le.delete(n),e?.blocks??[]}function lo(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function sp(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0;try{let o=Ls.safeParse(e.level),i=o.success?Us(o.data,{tool:t,command:s,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",d=i.ruleId??"autonomy",c=i.reason??"blocked",u={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:d,reason:c},l={matched:!0,action:"deny",effectiveAction:"deny",ruleId:d,severity:"high",message:c,resolvedTarget:null};return Ot({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:l,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Oc(e.taskId,u),{stdout:lo(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${c} (rule: ${d}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:u}}catch(o){return{stdout:lo(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}Gs();var Dc=6*60*60*1e3,et=new Map;function Nc(n){for(let[e,t]of et)n-t.at>Dc&&et.delete(e)}function ho(n,e){let t=Date.now();Nc(t),et.set(n,{at:t,limits:e})}function yo(n){et.delete(n)}function Lc(n,e,t){let s=new URLSearchParams({person:"1",task:e,...t?{agent:t}:{}}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function wo(n,e,t){let s=go();if(!s)return{error:"this person's tool and skill limits cannot be enforced: guard hook endpoint is not configured"};let r={matcher:"*",hooks:[{type:"command",command:Lc(s,e,t),timeout:15}]},o=[...n],i=o.indexOf("--settings");if(i===-1)return o.push("--settings",JSON.stringify({hooks:{PreToolUse:[r]}})),{args:o};let a=JSON.parse(o[i+1]);return a.hooks=a.hooks??{},a.hooks.PreToolUse=[...a.hooks.PreToolUse??[],r],o[i+1]=JSON.stringify(a),{args:o}}function bo(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function An(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function Uc(n,e,t){if(n.tools.some(s=>ze(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>ze(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function cp(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?et.get(e.taskId):void 0;if(!r)return{stdout:An("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=Uc(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,d={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Ot({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:d,mode:"enforce",taskId:e.taskId??null}),{stdout:An(`[agentx-people] Blocked: ${a} here (set by the owner). Do not work around it. Finish what you can without it and say in your answer what was not done and why.`),blocked:{personId:o.personId,tool:t,skill:i.skill,reason:a}}}catch(r){return{stdout:An(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var Hc=5e3;function V(n){let e=Rt(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
10
|
+
`)}return{error:Pt(e),errorKind:e.kind}}function Ao(){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 Lt(){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 xo(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function Se(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let d of r.peers){let c=d.handle?` (mention: ${d.handle})`:"",u=d.role?` \u2014 ${d.role}`:"";o.push(`\u2022 ${d.name}${c}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
|
|
11
|
+
`))}return e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
|
|
12
|
+
`)}function Co(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let d=r||n.model;return d&&a.push("--model",d),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Mn(n,e){return!e||e.trim().length===0?n:`[System]
|
|
13
|
+
${e.trim()}
|
|
14
|
+
|
|
15
|
+
[User]
|
|
16
|
+
${n}`}function jc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Mn(e,s)),o}function Bc(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function So(n){return JSON.stringify(n)}function Mo(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${So(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(So).join(",")}]`]}function Ro(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Mo()),i||a.push("--color","never");let d=s||n.model;return d&&a.push("--model",d),n.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Mn(e,r)),a}function Ft(n,e){let t=De(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),nt(t,e)}function nt(n,e){return n.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function Po(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),n}function Ht(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function Wc(n,e){let t=Ft(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...s,mcp:r}),t}function qc(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function xe(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Rn(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:xe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:xe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:xe(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:xe(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Rn(s,e+1);if(r)return r}}function _o(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function Pn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=Pn(t,e+1);if(s)return s}}}function Gc(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
|
|
17
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=Rn(a)||t,s=_o(a)||s,r=Pn(a)||r,o=Eo(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Eo(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return Io(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return Io(e)}}}function Io(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function Kc(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function _n(n,e,t,s,r){let o=Kc(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
|
|
18
|
+
`)}function Jc(n){try{let e=JSON.parse(n);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function zc(n){try{let e=JSON.parse(n),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||_t(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function Oo(n,e,t,s,r){let o=Date.now(),i=Se(n,e,t),a=No(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=Co(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(_n(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:l,stderr:p,exitCode:m,killed:h}=await new Promise(x=>{let $=Ce(Po(nt(De(n.workspace),e),e),n.billing),R=!1,E=Fc("claude",d,{cwd:n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...$,HOME:$.HOME||"/home/"+($.USER||"user")}},(k,L,N)=>{x({stdout:L||"",stderr:N||"",exitCode:k?k.code??1:0,killed:R})});if(E.stdin?.end(),r){let k=()=>{R=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{E.kill("SIGTERM")}catch{}setTimeout(()=>{try{E.killed||E.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?k():r.addEventListener("abort",k,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&m!==0){let x,$=Date.now()-o;return m===143&&$<u-Hc?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round($/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:$}:(m===143?x=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?x=Ao():x=p?.trim()||`Claude Code exited with code ${m}`,{content:"",...V(x),duration:Date.now()-o})}let b=Jc(l);if(b)return{content:"",...V(b),duration:Date.now()-o};let y=zc(l);return{content:y.text,duration:Date.now()-o,claudeSessionId:y.sessionId,usage:y.usage,numTurns:y.numTurns,costUsd:y.costUsd,billedModel:y.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function Do(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let d=Se(n,e,s),c=No(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let u=Co(n,d,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...c.args]);_n(e.agentId,n,e.model,r,"stream");let l="",p="",m="",h=O=>{let B=p&&!m?`
|
|
19
|
+
|
|
20
|
+
`:"";m+=O,l=p+(p?`
|
|
21
|
+
|
|
22
|
+
`:"")+m,t(B+O,l)},b=new Cn,y=!1,x,$,R,E,k,L,N;try{let O=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),B=Ce(Po(nt(De(n.workspace),e),e),n.billing),F=Ut("claude",u,{cwd:n.workspace,timeout:O,reject:!1,env:B,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},z=new Promise(Q=>{q=Q}),A=!1,T;if(i){let Q=()=>{A=!0,T=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{F.kill("SIGTERM")}catch{}setTimeout(()=>{try{F.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?Q():i.addEventListener("abort",Q,{once:!0})}let S="",U=new tt("utf8");F.stdout&&F.stdout.on("data",Q=>{S+=U.write(Q);let ne=S.split(`
|
|
23
|
+
`);S=ne.pop()||"";for(let X of ne)if(X.trim())try{let _=JSON.parse(X);if(o)try{o(_)}catch{}if(_.type==="assistant"&&_.message?.usage){let se=_.message.usage,ie=(se.input_tokens||0)+(se.cache_read_input_tokens||0)+(se.cache_creation_input_tokens||0);ie>0&&(E=ie)}if(_.type==="assistant"&&_.message?.content){for(let se of _.message.content)if(se.type==="text"&&se.text){let ie=se.text.slice(m.length);ie&&h(ie)}}if(_.type==="content_block_delta"&&_.delta?.text&&h(_.delta.text),b.observe(_),_.type==="result"&&_.result){if(_.is_error&&typeof _.result=="string")N=_.result;else{let se=(typeof _.result=="string",_.result);if(typeof se=="string"&&se.length>m.length){let ie=se.slice(m.length);ie&&h(ie)}}_.usage&&($={inputTokens:_.usage.input_tokens||0,outputTokens:_.usage.output_tokens||0,cacheReadTokens:_.usage.cache_read_input_tokens||0,cacheCreateTokens:_.usage.cache_creation_input_tokens||0}),typeof _.model=="string"?x=_.model:x=_t(_.modelUsage)||x,typeof _.session_id=="string"&&(R=_.session_id),typeof _.num_turns=="number"&&(k=_.num_turns),typeof _.total_cost_usd=="number"&&(L=_.total_cost_usd)}_.type==="result"&&(b.pending===0?q():(y||process.stderr.write(`[claude-stream] agent=${e.agentId} task=${e.taskId??"?"} turn ended with ${b.pending} background task(s) running; the task stays open until they end
|
|
24
|
+
`),y=!0,m&&(p=l,m=""))),_.type==="system"&&_.subtype==="init"&&(typeof _.model=="string"&&(x=_.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${_.apiKeySource} version=${_.claude_code_version} model=${_.model} permMode=${_.permissionMode}
|
|
25
|
+
`))}catch{X.trim()&&!X.startsWith("{")&&h(X+`
|
|
26
|
+
`)}});let j=await td(F,z),P=U.end();if(P&&(S+=P),A)return{content:"",error:T||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!l&&j.stdout&&(l=typeof j.stdout=="string"?j.stdout:""),j.exitCode!==0&&!l){let Q=typeof j.stderr=="string"?j.stderr:"",ne=j,X;return ne.timedOut?X=`Claude Code timed out after ${Math.round(O/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:ne.signal?X=Q.trim()||`Claude Code killed by signal ${ne.signal}`:ne.code==="ENOENT"||/ENOENT|spawn claude/i.test((ne.shortMessage||"")+" "+Q)?X=Ao():X=Q.trim()||`Claude Code exited with code ${ne.exitCode??"unknown"}`,{content:"",...V(X),duration:Date.now()-a}}return N?{content:"",...V(N),duration:Date.now()-a,usage:$,contextTokens:E,numTurns:k,billedModel:x,claudeSessionId:R}:{content:l,duration:Date.now()-a,usage:$,contextTokens:E,numTurns:k,costUsd:L,billedModel:x,claudeSessionId:R}}catch(O){return{content:l||"",...V(O.message),duration:Date.now()-a,usage:$,contextTokens:E,numTurns:k,billedModel:x,claudeSessionId:R}}}async function Qc(n,e,t,s){let r=Date.now(),o=Se(n,e,t),i=To(Nt($o(),"agentx-codex-")),a=Nt(i,"last-message.txt"),d=Ro(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let c=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await Ut("codex",d,{cwd:n.workspace,timeout:c,reject:!1,env:Ft(n,e),extendEnv:!1,stdin:"ignore"}),l=Gc(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,h;return m.timedOut?h=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?h=l.apiError:m.signal?h=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?h=Lt():h=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...V(h),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let p="";try{p=ko(a,"utf8").trim()}catch{}return p||(p=u.stdout.trim()),{content:p,duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}catch(c){let u=/ENOENT|spawn codex/i.test(c?.message||"")?Lt():c?.message;return{content:"",...V(u||"Codex CLI failed"),duration:Date.now()-r}}finally{vo(i,{recursive:!0,force:!0})}}async function Xc(n,e,t,s,r,o){let i=Date.now(),a=Se(n,e,s),d=To(Nt($o(),"agentx-codex-")),c=Nt(d,"last-message.txt"),u=Ro(n,a,!0,e.model,e.systemPromptAppend,c,r),l="",p,m,h,b;try{let y=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),x=Ut("codex",u,{cwd:n.workspace,timeout:y,reject:!1,env:Ft(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let $="",R="",E=!1,k=new tt("utf8"),L=new tt("utf8"),N=Math.min(y,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),O,B=()=>{O&&clearTimeout(O),O=setTimeout(()=>{E=!0,x.kill("SIGTERM",{forceKillAfterTimeout:5e3})},N)};B(),x.stderr?.on("data",T=>{B(),R+=L.write(T),R.length>16e3&&(R=R.slice(-16e3))}),x.stdout?.on("data",T=>{B(),$+=k.write(T);let S=$.split(`
|
|
27
|
+
`);$=S.pop()||"";for(let U of S)if(U.trim())try{let j=JSON.parse(U);if(o)try{o(j)}catch{}p=Rn(j)||p,m=_o(j)||m,h=Pn(j)||h,b=Eo(j)||b;let P=qc(j);if(P&&P!==l){let Q=P.startsWith(l)?P.slice(l.length):P;l=P.startsWith(l)?P:l+P,Q&&t(Q,l)}}catch{l+=U+`
|
|
28
|
+
`,t(U+`
|
|
29
|
+
`,l)}});let F=await x;O&&clearTimeout(O);let q=k.end();q&&($+=q);let z=L.end();if(z&&(R+=z),F.exitCode!==0&&!l||b){let T=R||(typeof F.stderr=="string"?F.stderr:""),S=F,U;return E?U=`Codex CLI produced no output for ${Math.round(N/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:S.timedOut?U=`Codex CLI timed out after ${Math.round(y/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:b?U=b:S.signal?U=T.trim()||`Codex CLI killed by signal ${S.signal}`:S.code==="ENOENT"||/ENOENT|spawn codex/i.test((S.shortMessage||"")+" "+T)?U=Lt():U=T.trim()||`Codex CLI exited with code ${S.exitCode??"unknown"}`,{content:"",...V(U),duration:Date.now()-i,usage:p,billedModel:m,codexSessionId:h||r}}let A="";try{A=ko(c,"utf8").trim()}catch{}if(A&&A!==l){let T=A.startsWith(l)?A.slice(l.length):A;l=A,T&&t(T,l)}return{content:l,duration:Date.now()-i,usage:p,billedModel:m,codexSessionId:h||r}}catch(y){let x=/ENOENT|spawn codex/i.test(y?.message||"")?Lt():y?.message;return{content:l,...V(x||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:m,codexSessionId:h||r}}finally{vo(d,{recursive:!0,force:!0})}}async function Yc(n,e,t,s,r,o,i,a){let d=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let c=Se(n,e,s),u=jc(n,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",p,m=e.freshSession?void 0:r,h,b,y=!0,x;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),R=Wc(n,e);if(n.persistentProcess)try{b=await Zs.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:n.workspace,env:R,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",b.url),R=b.env,o?.({type:"opencode.ready",reused:b.reused,startupMs:Date.now()-d})}catch(T){if(!(T instanceof Ys))throw T;T.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:T.message})}if(i?.aborted)throw new Error("task cancelled by operator");let E=Ut("opencode",u,{cwd:n.workspace,timeout:$,reject:!1,env:R,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let k=!1,L,N=()=>{b?.invalidate(),k=!0,L=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{E.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",N,{once:!0}),x=()=>i?.removeEventListener("abort",N),i?.aborted&&N();let O="",B="",F=new tt("utf8"),q=new tt("utf8"),z=T=>{if(T.trim())try{let S=JSON.parse(T);try{o?.(S)}catch{}typeof S.sessionID=="string"&&(m=S.sessionID);let U=S.type==="text"&&typeof S.part?.text=="string"?S.part.text:void 0;U&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-d,reused:b?.reused??!1}),l+=U,t?.(U,l));let j=S.type==="reasoning"&&typeof S.part?.text=="string"?S.part.text:void 0;j&&a?.(j);let P=S.type==="step_finish"?S.part?.tokens:void 0;P&&(p={inputTokens:xe(P.input),outputTokens:xe(P.output),cacheReadTokens:xe(P.cache?.read),cacheCreateTokens:xe(P.cache?.write)}),h=Bc(S)||h}catch{l+=T+`
|
|
30
|
+
`,t?.(T+`
|
|
31
|
+
`,l)}};E.stdout?.on("data",T=>{O+=F.write(T);let S=O.split(`
|
|
32
|
+
`);O=S.pop()||"";for(let U of S)z(U)}),E.stderr?.on("data",T=>{B+=q.write(T)});let A=await E;if(i&&i.removeEventListener("abort",N),O+=F.end(),O.trim()&&z(O),B+=q.end(),k)return{content:"",error:L||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(A.exitCode!==0||h){let T=A,S;return T.timedOut?S=`OpenCode timed out after ${Math.round($/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+B)?S=xo():S=B.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(S),duration:Date.now()-d,usage:p,opencodeSessionId:m}}return y=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch($){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let R=/ENOENT|spawn opencode/i.test($?.message||"")?xo():$?.message;return{content:l,...V(R||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:m}}finally{x?.(),b?.release(y)}}async function Zc(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Vc(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let b=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let y=n.provider||"claude-code",x=s?`${s}
|
|
33
|
+
|
|
34
|
+
${e.message}`:e.message,$=e.context?.sender,R=typeof $=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),E=e.context?.channel==="web-chat"&&R?{userId:$,agentId:e.agentId||"acme-public"}:void 0,k=sr(n),L=Object.keys(k).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:l.signal,mcpServers:L?k:void 0};if(r){let{generateStream:z}=await import("./agent-6KCTPI7E.js"),A="",T,S,U,j;for await(let P of z(N)){if(d)try{d(P)}catch{}if(P.type==="text_delta")A+=P.text,r(P.text,A);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}T=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}P.result.tokensUsed!=null&&(T=P.result.tokensUsed)}else P.type==="error"&&(j=P.error)}return j&&!A?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${j}`),duration:Date.now()-c}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:A||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:O}=await import("./agent-6KCTPI7E.js"),B=await O(N),F=B.inputTokens,q=B.outputTokens;if((F===void 0||q===void 0)&&B.tokensUsed){let z=B.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Cn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},ed=1e3;async function td(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),ed),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function nd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let A=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>A}catch(A){return A instanceof Ne,null}m&&_n(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,$,R,E,k,L,N="",O="",B=A=>{if(!i||!A)return;let T;if(O&&A.startsWith(O)?T=A.slice(O.length):T=N&&!N.endsWith(`
|
|
35
|
+
`)?`
|
|
36
|
+
|
|
37
|
+
${A}`:A,O=A,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let z=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(z=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let S=T.raw.message?.content??[];for(let j of S)j.type==="text"&&typeof j.text=="string"?(b=j.text,B(j.text)):j.type==="tool_use"&&(O="");let U=T.raw.message?.usage;if(U){let j=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);j>0&&(R=j)}}if(T.type==="result"){let S=T.raw;if(S.is_error){let U=V(typeof S.result=="string"?S.result:"claude error");y=U.error,x=U.errorKind}else typeof S.result=="string"&&S.result.length>0&&(b=S.result,N||B(S.result));typeof S.session_id=="string"&&(L=S.session_id),S.usage&&($={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(E=S.num_turns),typeof S.message?.model=="string"?k=S.message.model:typeof S.model=="string"?k=S.model:k=_t(S.modelUsage)||k}}}catch(A){if(F)y="task cancelled by operator",x="cancelled";else if(z)if(A instanceof Ve)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,x="interrupted";else if(A instanceof Ze){let T=V(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);y=T.error,x=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);y=T.error,x=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!y&&(y="task cancelled by operator",x="cancelled"),{content:F?"":b,error:y,errorKind:x,duration:Date.now()-d,usage:$,contextTokens:R,numTurns:E,billedModel:k,claudeSessionId:L}}function No(n){let e=ge(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?po(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:wo(t.args,n.taskId,n.agentId)}function sd(n){return ge(n.autonomy)||!!n.personLimits}async function rd(n,e,t,s,r,o,i){let a=ge(e.autonomy)?e.autonomy:void 0,d=a&&fo(a,n.tier)||e.personLimits&&bo(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${Fs(a)}
|
|
38
|
+
|
|
39
|
+
${e.message}`:e.message},l=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${l} task=${c} via=spawn (persistent process bypassed)
|
|
40
|
+
`),e.personLimits&&ho(c,e.personLimits);try{let p=t?await Do(n,u,t,s,r,o,i):await Oo(n,u,s,r,i);if(!a)return p;let m=mo(c);return{...p,autonomy:a,...m.length?{autonomyBlocks:m}:{}}}finally{e.personLimits&&yo(c)}}async function Lo(n,e,t,s,r,o,i,a,d){if(sd(e))return rd(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let c=await nd(n,e,r,o,i,a,s);if(c!==null)return c}return s?Do(n,e,s,r,o,i,a):Oo(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let c=await ro.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:n.workspace,env:Ft(n,e),args:Mo(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Mn(Se(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...c,...c.error?V(c.error):{}}}catch(c){if(!(c instanceof be))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Xc(n,e,s,r,o,i):Qc(n,e,r,o);case"opencode":return Yc(n,e,s,r,o,i,a,d);case"sdk":{let c=n.provider||"claude",u=t[c]?.apiKey;return u?Zc(n,e,u,r):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=n.provider||"claude-code",u=t[c],l=u?.apiKey;return Vc(n,e,l,r,s,{thinking:u?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ue,writeFileSync as Uo,mkdirSync as od,existsSync as jt,readdirSync as En}from"fs";import{resolve as Fe}from"path";var On=12e3,st=30,id=720,ad=40,cd=18e4,dd="[Compacted conversation summary",ud=7*864e5,ld=[/\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 gd(n){return n?ld.some(e=>e.test(n)):!1}var pd=[{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 Ho(n){if(!n)return null;let e=0;for(let t of pd)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Fo(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function jo(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function Bo(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function fd(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var Bt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Fe(e,".agentx/sessions"),jt(this.sessionsDir)||od(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??id),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??ad),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??cd),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let d=this.adapterResolver(t);if(!d?.seedHistory)return;let c=(async()=>{try{let u=await d.seedHistory(s,{maxMessages:st,maxChars:On});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,c);try{await c}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Fe(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(jt(o))try{let c=JSON.parse(Ue(o,"utf-8"));return this.cache.set(r,c),c}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),d={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,d),this.save(d),d}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!jt(i))return null;try{return JSON.parse(Ue(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Fo(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,s,r){let o=this.getSession(e,t,s),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,s,r){let o=this.getSession(e,t,s);Fo(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}continueFrom(e,t,s){if(t.channel===s.channel&&t.chatId===s.chatId)return!1;let r=this.sessionKey(e,t.channel,t.chatId);if(!(this.cache.has(r)||jt(this.sessionFile(r))||this.loadPreviousDaySession(e,t.channel,t.chatId)!==null))return!1;let i=this.getSession(e,t.channel,t.chatId);if(!i.claudeSessionId&&!i.codexSessionId&&!i.opencodeSessionId)return!1;let a=this.getSession(e,s.channel,s.chatId);return a.claudeSessionId=i.claudeSessionId,a.codexSessionId=i.codexSessionId,a.opencodeSessionId=i.opencodeSessionId,a.turnCount=i.turnCount,a.lastTurnInputTokens=i.lastTurnInputTokens,a.lastTurnContextTokens=i.lastTurnContextTokens,a.updatedAt=i.updatedAt,this.save(a),!0}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??st),a=Math.max(200,r.maxChars??On),d=[],c=0;for(let p=o.messages.length-1;p>=0&&d.length<i;p--){let m=o.messages[p];if(c+=m.content.length,d.push(m),c>=a)break}d.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let p of d){let m=fd(p.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let h=p.name||(p.role==="user"?"User":"Agent");u.push(`${h}: ${p.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
41
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),d;try{d=En(this.sessionsDir).filter(E=>E.startsWith(`${a}:`)&&E.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let c=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,p=d.filter(E=>{let k=E.match(l);if(!k)return!1;let L=k[1];return L>=c&&L<=u}),m=[],h=0,b=e.query?.toLowerCase(),y=e.participants?.length?new Set(e.participants):void 0;for(let E of p){let k;try{k=JSON.parse(Ue(Fe(this.sessionsDir,E),"utf-8"))}catch{continue}if(k.agentId===e.agentId&&!(e.channel&&k.channel!==e.channel)&&!(e.chatId&&k.chatId!==e.chatId))for(let L of k.messages)h++,!(!L.timestamp||L.timestamp<o||L.timestamp>=i)&&(y&&L.role==="user"&&!y.has(L.name??"")||b&&!L.content.toLowerCase().includes(b)||m.push({ts:L.timestamp,role:L.role,senderName:L.name??"",content:L.content,channel:k.channel,chatId:k.chatId,day:k.day,sessionFile:E}))}m.sort((E,k)=>k.ts.localeCompare(E.ts));let x=m.slice(0,t),$=x.length>0?x[x.length-1].ts:null,R=m.length>t;return{turns:x,oldestTs:$,hasMore:R,totalScanned:h}}recentByChatId(e){let t=Math.min(Math.max(e.limit??st,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=En(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let p=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),d=[];for(let l of a){let p;try{p=JSON.parse(Ue(Fe(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let m of p.messages)!m.timestamp||m.timestamp<s||d.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:p.agentId,sessionFile:l})}let c=new Set,u=[];for(let l of d){let p=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;c.has(p)||(c.add(p),u.push(l))}return u.sort((l,p)=>l.ts.localeCompare(p.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!gd(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=En(this.sessionsDir).filter(c=>c.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&c.includes(o)&&c.endsWith(".json")),d=[];for(let c of a)try{let u=JSON.parse(Ue(Fe(this.sessionsDir,c),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,h=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);d.push(`From ${m} (${u.channel}):
|
|
42
|
+
${h.join(`
|
|
43
|
+
`)}`)}catch{}return d.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...d,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
44
|
+
`)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:d}=await import("./compaction-FS6XNRLM.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:s});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(dd)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,s){let r=this.getSession(e,t,s);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Fe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ue(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Uo(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>ud?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>st&&(e.messages=e.messages.slice(-st));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>On&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ae.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);Uo(t,JSON.stringify(e,null,2))}catch{}}};var Wt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};var md={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},Wo=4;function Jo(n,e=md){let t=yd(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*Wo;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Wo,d=qo(i.content,a,i.keep);if(r+d.length>o){let c=o-r;c>100&&s.push(qo(d,c,i.keep));break}s.push(d),r+=d.length}return s.join(`
|
|
45
|
+
|
|
46
|
+
`)}function qo(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
|
|
47
|
+
`,r=n.indexOf(`
|
|
48
|
+
`),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=Ko(n,i);if(!Go.test(a.slice(0,a.indexOf(`
|
|
49
|
+
`)+1||void 0))){let d=u=>n.slice(0,n.length-u.length).match(hd)?.pop(),c=d(a);if(c&&c.length+1<i/2){a=Ko(n,i-c.length-1);let u=Go.test(a.slice(0,a.indexOf(`
|
|
50
|
+
`)+1||void 0))?"":d(a);u&&(a=u+`
|
|
51
|
+
`+a)}}return o+s+a}var Go=/^— \d\d:\d\d —(\n|$)/,hd=/^— \d\d:\d\d —$/gm;function Ko(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
|
|
52
|
+
`);return s>=0&&s<e/2?t.slice(s+1):t}function yd(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(wd(n,t("channel",200))),s.push(bd(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
|
|
53
|
+
`)[0],tags:["identity",n.agentId]}),n.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:n.bootstrapContext,tags:["bootstrap","identity","personality"]}),n.references&&s.push({name:"references",priority:4.7,maxTokens:t("references",500),content:n.references,tags:["references","verified","deterministic"]}),n.intent&&n.intent.path.length>0){let i=[`[Intent path: ${n.intent.pathLabel}${n.intent.status==="pending"?" (pending approval)":""}]`],a=n.intent.path[n.intent.path.length-1],d=n.intent.axes?.[a];if(d&&Object.keys(d).length){let c=Object.entries(d).map(([u,l])=>` ${u}: ${l}`).join(`
|
|
54
|
+
`);i.push(c)}n.intent.leaf?.input&&i.push(` input: ${n.intent.leaf.input}`),s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
55
|
+
`),tags:["intent",...n.intent.path]})}else{let i=xd(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
56
|
+
`),tags:["artifacts",...n.mediaType?["media"]:[]]}),n.skillInjection&&s.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:n.skillInjection,tags:["skills","auto-inject"]}),n.patternContext&&s.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:n.patternContext,tags:["patterns","behavioral","self-improving"]}),n.procedureContext&&s.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:n.procedureContext,tags:["procedures","sop"]}),n.workflowRunContext&&s.push({name:"workflow-run",priority:6.55,maxTokens:t("workflow-run",200),content:n.workflowRunContext,tags:["workflow","plan"]}),n.memoryContext&&s.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:n.memoryContext,tags:["memory","persistent"]});let o=n.groupHistory||n.sessionHistory;if(o&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"],keep:"tail"}),n.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:n.crossChatContext,tags:["history","cross-chat"]}),n.contextOnDemand&&s.push({name:"on-demand",priority:7,maxTokens:t("on-demand",150),content:n.contextOnDemand,tags:["history","on-demand","lean"]}),n.longMemoryRecall&&s.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:n.longMemoryRecall,tags:["history","long-memory"]}),n.handoverNote){let i=[`[Handover] You are taking over this conversation from ${n.handoverNote.fromAgent}.`];n.handoverNote.summary&&i.push(`Operator summary: ${n.handoverNote.summary}`),i.push(`Handover time: ${n.handoverNote.at}`),s.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
57
|
+
`),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner:]`,n.rotationMemo.memo].join(`
|
|
58
|
+
`),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function wd(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:r,rules:s}}function bd(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
60
|
+
`),tags:s}}function xd(n){let e=[],t=n.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var Sd="resumeDelivery";function Np(n){if(!n||n.kind!=="direct"||!n.context||n.context[Sd]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var Id=32e3;function zo(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Id?e:null}catch{return null}}function Lp(n){if(!n)return null;try{let e=JSON.parse(n);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}function Qo(n){return new Date(n).toISOString().slice(11,16)}function Xo(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Qo(n)} UTC, running at ${Qo(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var qt=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(d=>`[${d.sender}, ${new Date(d.timestamp).toISOString().slice(11,16)}]: ${d.text}`).join(`
|
|
61
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(d=>d.queuedAt??d.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};var Td=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,kd=String.raw`(?=[\w.-]*[A-Za-z])(?![\w-]*\.(?:ts|js|mjs|cjs|tsx|jsx|md|py|go|rs|json|ya?ml|txt|sh|html|css)\b)[\w.-]+`,Yo=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,Zo=new RegExp(String.raw`(?<![\w/.-])((?:${Td}\/)+${kd})([#!])(\d+)\b`,"g");function Gt(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(Yo.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${Zo.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function vd(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(Yo)){let s=Gt(t[0]);s&&e.add(s)}for(let t of n.matchAll(Zo))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function Hp(n){let e=n.context&&typeof n.context=="object"?n.context:null;return Gt(n.home)??Gt(e?.home)}var $d="[agentx:same-home]";function Vo(n,e,t){if(!e.length)return null;for(let s of n){if(s.channel===t.channel&&s.chatId===t.chatId)continue;let r=s.homes?.find(i=>e.includes(i));if(!r)continue;let o=s.startedAt.toISOString().slice(11,16);return`${$d} Another run of yours is already working on ${r} (started ${o}Z, chat ${s.channel}:${s.chatId??"?"}). Coordinate with it or stop: do not redo or overwrite its work. Keep what is not committed in a branch, not in a shared folder.`}return null}function ei(n){let e=Gt(n.home),t=vd(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as Ad,writeFileSync as ti,appendFileSync as Cd,mkdirSync as Md,existsSync as ni}from"fs";import{resolve as Dn}from"path";var si=50,Rd="claude-haiku-4-5-20251001",Pd=`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.
|
|
62
|
+
|
|
63
|
+
Extract patterns like:
|
|
64
|
+
- "When asked about X, the approach that works is Y"
|
|
65
|
+
- "User prefers Z style of communication"
|
|
66
|
+
- "For deployment tasks, always check A before doing B"
|
|
67
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
68
|
+
|
|
69
|
+
SKIP:
|
|
70
|
+
- Factual information (names, dates, URLs)
|
|
71
|
+
- Routine task completions
|
|
72
|
+
- Greetings or small talk
|
|
73
|
+
|
|
74
|
+
Output a JSON array:
|
|
75
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
76
|
+
|
|
77
|
+
If nothing worth extracting, output: []`,Kt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Dn(e,".agentx/patterns"),ni(this.patternsDir)||Md(this.patternsDir,{recursive:!0})}filePath(e){return Dn(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ni(t))return[];try{return Ad(t,"utf-8").split(`
|
|
78
|
+
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Cd(this.filePath(e),JSON.stringify(s)+`
|
|
79
|
+
`)}findRelevant(e,t,s=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(u=>`${u.context} ${u.pattern}`),i=Dn(this.patternsDir,`${t}_bm25_cache.json`),a=Ns(o,i),c=Ds(e,a).slice(0,s).map(u=>r[u.docIndex]).filter(u=>u.confidence>=.3);return c.length>0&&this.recordAccess(t,c.map(u=>u.id)),c}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
80
|
+
`)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(d=>i.includes(d)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&ti(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
|
|
81
|
+
`)+`
|
|
82
|
+
`)}prune(e){let t=this.getAll(e);t.length<=si||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,si),ti(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
|
|
83
|
+
`)+`
|
|
84
|
+
`))}};async function ri(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-55NC2SFN.js"),d=(await o("claude").generate([{role:"system",content:Pd},{role:"user",content:`User: ${e.slice(0,500)}
|
|
85
|
+
|
|
86
|
+
Agent: ${t.slice(0,1e3)}`}],{model:Rd,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!d)return;let c=JSON.parse(d[0]);if(!(!Array.isArray(c)||c.length===0)){for(let u of c)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as _d}from"events";var Ed=2e4,Ln=class{inner=new _d;envelopeListeners=new Set;ring=new Sr;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let s=this.inner.emit(e,t);try{this.publish(Od(e,t))}catch{}return s}publish(e){let t=$t(),s=e.id??xr(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:xn(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>Ed&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:xn(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function Od(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var Nn;function ee(){return Nn||(Nn=new Ln),Nn}gn();gn();var oi=["manual","notify","auto"];function Dd(n){return typeof n=="string"&&oi.includes(n)}var Un={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Nd=7*24*60*6e4,rt=class{constructor(e={},t){this.store=t;this.opts={...Un,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-Nd;for(let[o,i]of Object.entries(s))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,s){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:Ee(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:Ld(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Ld(n,e){return n.length<=e?n:`${n.slice(0,e)}
|
|
87
|
+
\u2026[truncated ${n.length-e} chars]`}gc();import{z as Ud}from"zod";var ai=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Fd(n){if(n==null)return{ok:!0,subscriptions:ai};let e=Ud.array(Ks).min(1).safeParse(n);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var Hd=15,jd=1500,ii=200;function ci(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Bd(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function nf(n,e,t={}){let s=Bd(e,n.cursor),r=s.length?ci(s):n.cursor,o=s.filter(c=>n.subscriptions.some(u=>Ir(u,c)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:d}=Wd(o,i,t);return{text:a,cursor:r,matched:o.length,shown:d}}function Wd(n,e,t={}){let s=Math.max(3,t.maxLines??Hd),r=Math.max(200,t.maxChars??jd),o=n.map(a=>qd(`- ${kr(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let d=i-a,u=[d?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];d&&u.push(`+${d} more \u2014 \`agentx events --since ${e}\``);let l=u.join(`
|
|
88
|
+
`);if(u.length<=s&&l.length<=r)return{text:l,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function qd(n){return n.length<=ii?n:`${n.slice(0,ii-1)}\u2026`}import{existsSync as Gd,mkdirSync as Kd,readFileSync as Jd,renameSync as zd,writeFileSync as Qd}from"node:fs";import{homedir as Xd}from"node:os";import{dirname as Yd,join as Zd}from"node:path";function Vd(n){return{load:()=>Gd(n)?JSON.parse(Jd(n,"utf-8")):{},save:e=>{Kd(Yd(n),{recursive:!0});let t=`${n}.tmp`;Qd(t,JSON.stringify(e,null,2),{mode:384}),zd(t,n)}}}function eu(){if(!process.env.VITEST)return Vd(process.env.AGENTX_ATTACH_BINDINGS_FILE??Zd(Xd(),".agentx","attach-bindings.json"))}var Fn;function di(){return Fn||(Fn=new rt({},eu())),Fn}pn();import{readFileSync as tu}from"fs";import{homedir as nu}from"os";import{join as su}from"path";var ot=null,ru=6e4;function ou(){try{let n=su(nu(),".claude.json"),e=tu(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function iu(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function au(n=!1){let e=Date.now();return!n&&ot&&e-ot.checkedAt<ru||(ot=iu(ou(),e)),ot}function ui(n){let e=au();return e.available||n?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var gi={warnRatio:.8},He={...gi},cu=5*60*60*1e3,du=60*60*1e3,Me=[];function pi(n){He={...gi,...n||{}}}function fi(n){let e=n-cu,t=0;for(;t<Me.length&&Me[t]<e;)t++;t>0&&Me.splice(0,t)}function mi(n=Date.now()){fi(n),Me.push(n)}var je=new Map,uu=15*60*1e3;function hi(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function lu(n){let e=hi(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function gu(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=lu(s.resetsAt??s.resets_at),a=hi(s.utilization),d=s.overageStatus??s.overage_status,c=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||d==="allowed"||d==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...c&&{usingOverage:c},seenAt:e}}function yi(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function wi(n,e){let t=yi(n);return!t||!e||e.toLowerCase().includes(t)}function Hn(n,e=Date.now(),t){let s=gu(n,e);if(!s)return null;if(s.status!=="rejected")for(let[r,o]of je)o.status!=="rejected"||r===s.window||(!yi(r)||t&&wi(r,t))&&je.delete(r);return je.set(s.window,s),s}function bi(n=Date.now()){return[...je.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:(e.resetsAt??e.seenAt+uu)>n)}function pu(n=Date.now(),e){return bi(n).find(t=>wi(t.window,e))??null}function yf(n=Date.now()){let e=bi(n);for(let t of e)je.delete(t.window);return e}function fu(){return[...je.values()].sort((n,e)=>e.seenAt-n.seenAt)}function li(n){return typeof n=="number"&&n>0}function xi(n=Date.now()){fi(n);let e=n-du,t=0;for(let o=Me.length-1;o>=0&&Me[o]>=e;o--)t++;let s=Me.length,r={lastHour:t,last5h:s,maxPerHour:li(He.maxPerHour)?He.maxPerHour:void 0,maxPer5h:li(He.maxPer5h)?He.maxPer5h:void 0,provider:fu()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function Si(n){return n.replace(/_/g," ")}function Ii(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function Ti(n,e=Date.now(),t){let s=xi(e);if(n)return null;let r=pu(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Si(r.window)} window as rejected. Cold dispatches are held until it resets ${Ii(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.maxPerHour} claude-code runs in the last hour. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPerHour in agentx.json (applies on save).`,usage:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.maxPer5h} claude-code runs in the last 5h. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPer5h in agentx.json (applies on save).`,usage:s}:null}function ki(n=Date.now()){let e=xi(n),t=e.provider.find(r=>r.status==="allowed_warning");if(t){let r=t.utilization!==void 0?` (${Math.round(t.utilization*100)}% used)`:"";return`claude plan ${Si(t.window)} window nearing its limit${r}, resets ${Ii(t.resetsAt,n)}`}let s=He.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of local cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}var jn=new Map;function vi(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function $i(n,e,t,s=Date.now()){let r=jn.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},jn.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function Ai(n){let e=jn.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as xu,readFileSync as Su}from"fs";import{resolve as Iu}from"path";import{existsSync as mu,readFileSync as hu,unlinkSync as yu,writeFileSync as wu}from"fs";import{resolve as Mi}from"path";var Ci="_agentxManaged";function Jt(n=process){let e=n.argv[1]?Mi(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function If(n,e){return!e||n.agentx?n:{...n,agentx:e}}function Tf(n,e){let t=Mi(n,".mcp.json"),s=mu(t),r=s?bu(t):null,o=r!==null&&r[Ci]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return yu(t),"removed";let a={[Ci]:!0,mcpServers:e};return wu(t,JSON.stringify(a,null,2)+`
|
|
89
|
+
`),s?"updated":"installed"}function bu(n){try{return JSON.parse(hu(n,"utf-8"))}catch{return null}}var Tu=["github","a2a","workflow","cron"],ku=["claude-code","codex-cli"],vu={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},$u="AGENTX_MCP_TOOLS",Au=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting"],Cu=["agentx_agents","agentx_recent","agentx_wiki_query"];function Pi(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function _i(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...Au,...n.contextOnDemand?Cu:[],...s];return Array.from(new Set(r))}function Mu(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[$u]:e.join(",")}}}function Ei(n,e,t){if(!ku.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(Tu.includes(e)?"lean":"full")}function Oi(n){return{...vu,...n?.lean??{}}}function Di(n){return n.settingSources.includes("project")}function Ru(n,e,t=Jt(),s){let r=Ni(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=Mu(o.agentx??r.agentx??t,_i(e,s)),o}function Ni(n){let e=Iu(n,".mcp.json");if(!xu(e))return{};try{let s=JSON.parse(Su(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function Li(n,e,t=Jt(),s){let r=Ru(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Pi(e,s);return i.length&&o.push("--tools",Fi(i).join(",")),o}function Ui(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Ri="ToolSearch";function Fi(n){return n.includes(Ri)?n:[...n,Ri]}function Hi(n,e=Jt()){let t=Ni(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function ji(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), and stored knowledge (agentx_wiki_query).`].join(`
|
|
90
|
+
`)}function Bi(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=Pi(e,t);r.length&&s.push(`tools=${Fi(r).join("+")}`);let o=_i(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ce,mkdirSync as ig,readdirSync as pe,readFileSync as ct,rmSync as ag,writeFileSync as cg}from"fs";import{resolve as K}from"path";import{randomUUID as dg}from"crypto";import{existsSync as Pe,mkdirSync as Bn,readFileSync as Pu,readdirSync as _u,renameSync as Eu,unlinkSync as Ou,writeFileSync as zt}from"fs";import{resolve as Ie,relative as Qt}from"path";import{z as Y}from"zod";var Re=Y.object({id:Y.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:Y.string().min(1),trigger:Y.string().min(1,"procedures must describe when they apply"),inputs:Y.array(Y.string()).default([]),expected:Y.string().optional(),kpis:Y.array(Y.string()).default([]),owner:Y.string().optional(),tags:Y.array(Y.string()).default([]),status:Y.enum(["draft","active","deprecated"]).default("active"),source:Y.string().optional(),evidence:Y.array(Y.string()).default([]),created:Y.string().optional(),updated:Y.string().optional(),related:Y.array(Y.string()).default([])});function Du(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
|
|
91
|
+
`)){let r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function Xt(n){let e=["---"];return e.push(`id: ${n.id}`),e.push(`title: "${n.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${n.trigger.replace(/"/g,'\\"')}"`),n.inputs?.length&&e.push(`inputs: ${JSON.stringify(n.inputs)}`),n.expected&&e.push(`expected: "${n.expected.replace(/"/g,'\\"')}"`),n.kpis?.length&&e.push(`kpis: ${JSON.stringify(n.kpis)}`),n.owner&&e.push(`owner: ${n.owner}`),n.tags?.length&&e.push(`tags: ${JSON.stringify(n.tags)}`),e.push(`status: ${n.status}`),n.source&&e.push(`source: "${n.source.replace(/"/g,'\\"')}"`),n.evidence?.length&&e.push(`evidence: ${JSON.stringify(n.evidence)}`),n.related?.length&&e.push(`related: ${JSON.stringify(n.related)}`),n.created&&e.push(`created: ${n.created}`),n.updated&&e.push(`updated: ${n.updated}`),e.push("---"),e.join(`
|
|
92
|
+
`)}var it=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Ie(process.cwd(),".agentx/procedures"),Bn(this.baseDir,{recursive:!0})}pathFor(e){return Ie(this.baseDir,`${e}.md`)}get draftsDir(){return Ie(this.baseDir,"_drafts")}draftPathFor(e){return Ie(this.draftsDir,`${e}.md`)}parseFile(e){let t=Pu(e,"utf-8"),{meta:s,body:r}=Du(t),o=Re.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:Qt(this.baseDir,e)}:null}listDir(e){if(!Pe(e))return[];let t=[];for(let s of _u(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Ie(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return Pe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return Pe(t)?this.parseFile(t):null}add(e,t){let s=Re.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(Pe(r))throw new Error(`Procedure already exists: ${s.id}`);return zt(r,Xt(s)+`
|
|
93
|
+
|
|
94
|
+
`+t.trim()+`
|
|
95
|
+
`),{meta:s,body:t.trim(),path:Qt(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=Re.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return zt(this.pathFor(e),Xt(o)+`
|
|
96
|
+
|
|
97
|
+
`+i.trim()+`
|
|
98
|
+
`),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=Re.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(s.id))throw new Error(`Procedure already exists: ${s.id}`);let r=this.draftPathFor(s.id);if(Pe(r))throw new Error(`Draft already exists: ${s.id}`);return Bn(this.draftsDir,{recursive:!0}),zt(r,Xt(s)+`
|
|
99
|
+
|
|
100
|
+
`+t.trim()+`
|
|
101
|
+
`),{meta:s,body:t.trim(),path:Qt(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let s=Re.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return zt(this.pathFor(e),Xt(s)+`
|
|
102
|
+
|
|
103
|
+
`+t.body+`
|
|
104
|
+
`),Ou(this.draftPathFor(e)),{meta:s,body:t.body,path:Qt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!Pe(t))throw new Error(`Draft not found: ${e}`);let s=Ie(this.draftsDir,"_rejected");Bn(s,{recursive:!0}),Eu(t,Ie(s,`${e}.md`))}isRejected(e){return Pe(Ie(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Nu,mkdirSync as Lu,readFileSync as Uu,writeFileSync as Fu}from"fs";import{dirname as Hu,resolve as ju}from"path";import{z as oe}from"zod";var Bu=oe.object({key:oe.string(),count:oe.number().int().min(0).default(0),firstSeen:oe.string(),lastSeen:oe.string(),taskIds:oe.array(oe.string()).default([]),sampleMessage:oe.string().default(""),status:oe.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:oe.string().optional()}),Wu=oe.object({minedThrough:oe.string().optional(),candidates:oe.array(Bu).default([])});function Wi(n){return ju(n,"_candidates.json")}function qu(n){let e=Wi(n);if(!Nu(e))return{candidates:[]};try{let t=Wu.safeParse(JSON.parse(Uu(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Gu(n,e){let t=Wi(n);Lu(Hu(t),{recursive:!0}),Fu(t,JSON.stringify(e,null,2)+`
|
|
105
|
+
`)}function Ku(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function Ju(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function zu(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function Wn(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function qi(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function qn(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=Wn(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let d=[],c=qi(o,Wn(a.meta.trigger));c>0&&d.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=qi(o,Wn(u));l>0&&d.push("title/tags");let p=Math.min(1,c*.7+l*.5);p>=r&&i.push({procedure:a,score:p,reasons:d})}return i.sort((a,d)=>d.score-a.score).slice(0,s)}function Gn(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
|
|
106
|
+
`)})].join(`
|
|
107
|
+
|
|
108
|
+
`)}yn();kt();var Jn="turn-progress",Gi={progress:Oe({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.")},Kn=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function Ki(n){return{agent:n.agent,request:Kn(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:Kn(e.input,300),...e.result!==void 0?{result:Kn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}kt();var Ji="turn-handoff",zi="approval-binding",Qi={nextStep:Oe({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.")},Xi={approves:Qe("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."})},Qu=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,Yi=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,Xu=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function zn(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Xu.test(e.split(`
|
|
109
|
+
`).slice(-3).join(" ")):!1}var Yu=/^\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 Zi(n){return n.trim().length<=160&&Yu.test(n)}function Vi(n){return n.trim().length<=160}function ea(n){return{agent:n.agent,channel:n.channel,request:Qu(n.request,1500),agentReplyEnding:Yi(n.reply,1200)}}function ta(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:Yi(n.previousReply,1200)}}var Zu=5*6e4,Vu=3,el=12,tl=24*60*6e4,na=new Set(["cron","heartbeat","bench","a2a","business"]),nl={observe(){},stop(){}};function sa(n){if(vt(Jn)==="off")return nl;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let p;for(let[m,h]of o)h>1&&(!p||h>p.times)&&(p={call:m,times:h});return p},u=p=>{if(d)return;d=!0,a=s.length;let m=Ki({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-el),repeated:c(),trigger:p});we(Jn,m,Gi,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:p}}).finally(()=>{d=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??Zu);return l.unref?.(),{observe(p){let m=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let h of m){if(h?.type!=="tool_use")continue;let b=h.input?JSON.stringify(h.input):"",y={tool:h.name||"tool",input:b};s.push(y),typeof h.id=="string"&&r.set(h.id,y);let x=`${y.tool}(${b})`,$=(o.get(x)??0)+1;o.set(x,$),$>=Vu&&!i.has(x)&&(i.add(x),u("repetition"))}else if(p?.type==="user")for(let h of m){if(h?.type!=="tool_result")continue;let b=r.get(h.tool_use_id);b&&(b.result=Array.isArray(h.content)?h.content.map(y=>typeof y?.text=="string"?y.text:"").join(""):typeof h.content=="string"?h.content:"",h.is_error&&(b.error=!0))}},stop(){clearInterval(l)}}}var Qn=new Map,ra=(n,e,t)=>`${n}\0${e}\0${t}`;function oa(n){if(na.has(n.channel)||!zn(n.reply))return;let e=ra(n.agent,n.channel,n.chatId);we(Ji,ea(n),Qi,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&Qn.set(e,{callId:t.callId,at:Date.now()})})}function ia(n){if(na.has(n.channel))return;let e=ra(n.agent,n.channel,n.chatId),t=Qn.get(e);if(t){Qn.delete(e);let s=Js().store;if(s&&Date.now()-t.at<tl)try{s.label(t.callId,"userReply",Zi(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!Vi(n.message)||!zn(n.previousReply)||we(zi,ta({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),Xi,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}cc();uc();lc();function aa(n){let e=n?.dueAt;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}}function Yt(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function Vf(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=Yt(n);return!t||Yt(e)?e:{...e??{},taskType:t}}Gs();function ca(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(_e(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(d=>{a(),s(d)},d=>{a(),r(d)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function _e(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Be=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function da(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Be(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as sl,spawn as rl}from"child_process";import{existsSync as ol,mkdirSync as il,readFileSync as al,renameSync as cl,writeFileSync as dl}from"fs";import{dirname as ul}from"path";var Vt={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function ll(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function gl(n){try{return!n||!ol(n)?void 0:sl("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function Xn(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function ua(n){let e={...Vt,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=Xn(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??gl,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let d=ll(r(a));if(d&&d.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var pl=24*60*60*1e3,fl=7*pl,Zt=class{constructor(e){this.file=e}sessions=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(al(this.file,"utf8")),t=Array.isArray(e?.sessions)?e.sessions:[];this.sessions=t.filter(s=>s&&typeof s.repo=="string"&&typeof s.sessionId=="string"&&Number.isFinite(s.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<fl);try{il(ul(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;dl(t,JSON.stringify({sessions:this.sessions},null,2)),cl(t,this.file)}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},ml=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
|
|
110
|
+
`);function hl(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var yl=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function la(n){return n.replace(yl,"")}function wl(n){let e=la(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function ga(n){let e=n.spawn??((d,c,u)=>rl(d,c,u)),t=n.python??"python3",s=["-c",ml,"claude",...hl(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=d=>{o+=d.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>la(o).trim().split(`
|
|
111
|
+
`).slice(-5).join(`
|
|
112
|
+
`).slice(-600);return new Promise(d=>{let c=!1,u=h=>{c||(c=!0,d(h))},l;try{l=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(h){u({ok:!1,reason:`could not start ${t}: ${h?.message||h}`,output:o});return}let p=h=>{try{l.pid&&process.kill(-l.pid,h)}catch{try{l.kill(h)}catch{}}},m=setTimeout(()=>{p("SIGTERM"),setTimeout(()=>p("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);m.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",h=>{clearTimeout(m);let b=h?.code==="ENOENT";u({ok:!1,reason:b?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${h?.message||h}`,output:o})}),l.on("close",h=>{if(clearTimeout(m),c)return;let b=wl(o);if(n.sessionId){if(h===0){u({ok:!0,sessionId:n.sessionId,url:b.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(b.sessionId&&b.url){u({ok:!0,sessionId:b.sessionId,url:b.url,output:o});return}if(h!==0){u({ok:!1,reason:`claude --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var bl=1e5;function xl(n,e){let s=`
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.number} in ${e.repo}. Work in this repository and open or update a pull request that references #${e.number}.`,r=bl-s.length;return`${n.length>r?`${n.slice(0,r)}
|
|
116
|
+
[message cut at ${r} characters]`:n}${s}`}function Sl(n,e,t){return[`Started a Claude cloud session for this ${e==="pull"?"pull request":"issue"}. The result arrives as a pull request.`,`Session: \`${n.sessionId}\``,n.url,`Comments here are forwarded to that session for the next ${t} hours.`].join(`
|
|
117
|
+
`)}function Il(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function pa(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:Il(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=xl(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:Sl(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as $l}from"child_process";import{existsSync as Al,mkdirSync as Cl,mkdtempSync as Ml,readFileSync as ba,renameSync as Rl,rmSync as Pl,writeFileSync as _l}from"fs";import{homedir as El,tmpdir as Ol}from"os";import{dirname as Dl,join as Zn,resolve as Vn,sep as ya}from"path";var Tl=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function kl(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
|
|
118
|
+
`).filter(e=>!/^[ \t]*>/.test(e)).join(`
|
|
119
|
+
`)}function fa(n,e){return at(n)?n:`${n}
|
|
120
|
+
|
|
121
|
+
<!-- agentx:${e} -->`}function at(n){if(!n)return null;let e=kl(n).match(Tl);return e?e[1]:null}var ma="unknown";function im(n,e){let t=at(n);return t&&(!e||t===e)?t:null}function am(n){return`> \u{1F916} **${n}** (via AgentX)
|
|
122
|
+
|
|
123
|
+
`}function ha(n,e){if(!e||!n)return null;let t=at(n);return t&&t!==ma?t:null}function cm(n,e){return e&&at(n)===ma}function dm(n,e,t){let s=ha(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function um(n,e,t){let s=ha(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function lm(n,e){return e||!n?n:vl(n)}function gm(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function vl(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return at(n)?n.replace(/</g,"<"):n}var xa={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Sa(n){return`spec-tests/issue-${n}`}function Ia(n){return`test: spec tests for #${n}`}function Nl(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var Ll=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Ul(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${Ll(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function Fl(n){let e=n.split(/\r?\n/),t=r=>r.match(/^\s*[-*]\s+\[[ xX]\]\s+(.+?)\s*$/)?.[1],s=e.findIndex(r=>/^\s*#{1,6}\s*acceptance criteria\b/i.test(r));if(s>=0){let r=[];for(let o of e.slice(s+1)){if(/^\s*#{1,6}\s/.test(o))break;let i=t(o);i&&r.push(i)}if(r.length)return r}return e.map(t).filter(r=>!!r)}function Hl(n){let e=new Set;for(let t of n.matchAll(/`([^`\n]{2,160})`/g)){let s=t[1].trim();/\s/.test(s)&&!/^[\w.$]+\s*[(<]/.test(s)||/[A-Za-z_]/.test(s)&&e.add(s)}return[...e]}function jl(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:Fl(e),interfaces:Hl(`${n.title}
|
|
124
|
+
${e}`)}}var Yn=2e4;function Bl(n){let e=n.body.length>Yn?`${n.body.slice(0,Yn)}
|
|
125
|
+
[issue cut at ${Yn} characters]`:n.body,t=n.acceptanceCriteria.length?n.acceptanceCriteria.map((r,o)=>`${o+1}. ${r}`).join(`
|
|
126
|
+
`):"(the issue has no checklist; take the requirements from its text)",s=n.interfaces.length?n.interfaces.map(r=>`- \`${r}\``).join(`
|
|
127
|
+
`):"(none named)";return[`You are the spec-test agent for issue #${n.number} in ${n.repo}.`,"Another agent is writing the code for this issue at the same time. You do not see its code, and you must not guess at it. Write tests from the issue alone.","","## Your job","- Write one test file for this issue, following the repository's existing test conventions (framework, folder, naming). Read the existing tests and the public interfaces the issue names to get imports and signatures right.","- One test or more per acceptance criterion. Name each test after the criterion it checks, so a failure points at the criterion.","- Test behaviour through public interfaces. The code under test may not exist yet: that is expected, the tests may fail now.","- Only create or edit test files. Do not change any other file. Do not commit: the daemon commits your file.","- When a criterion cannot be tested from the issue text alone, write no test for it and say so in your final reply.","- End with a short reply: the file you wrote and one line per criterion (tested, or why not).","",`## Issue #${n.number}: ${n.title}`,e,"","## Acceptance criteria",t,"","## Interfaces the issue names",s].join(`
|
|
128
|
+
`)}function Ta(n,e){let t=Sa(n);return["","## Spec tests (#992)",`A separate test agent ("${e}") is writing tests for this issue from the issue text only, without seeing your code. It pushes them as one commit, "${Ia(n)}", to the branch \`${t}\`.`,"- Do not write those tests yourself. Do not edit or delete them, except as described below.",`- Before you open the pull request, and again before you finish, run \`git fetch origin ${t}\`. When the branch exists, merge it into your branch with \`git merge --no-ff origin/${t}\` (a merge, not a cherry-pick, squash or rebase, so the commit keeps its author), then run its tests.`,'- When a spec test fails, decide which it is. A code defect: fix the code. A test that misreads the acceptance criteria: change that test in a separate commit whose message starts with "test: spec misread" and quotes the criterion it misreads. Never skip or disable a spec test.','- In the pull request description, add a "Spec tests" section that lists each failure on the first run and your call (code defect or test misread), and ends with this line, filled in:'," <!-- agentx:spec-tests written=W failed-first-run=F code-defects=D test-misreads=M -->","- If the branch has not appeared by the time you finish, say so in that section."].join(`
|
|
129
|
+
`)}var Wl=90*24*60*60*1e3,en=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(ba(this.file,"utf8")),t=Array.isArray(e?.runs)?e.runs:[];this.runs=t.filter(s=>s&&typeof s.repo=="string"&&Number.isInteger(s.number)&&Number.isFinite(s.startedAt))}catch{this.runs=[]}}}save(){let e=Date.now();this.runs=this.runs.filter(t=>e-t.startedAt<Wl);try{Cl(Dl(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;_l(t,JSON.stringify({runs:this.runs},null,2)),Rl(t,this.file)}catch{}}get(e,t){this.load();let s=e.toLowerCase();return this.runs.find(r=>r.repo.toLowerCase()===s&&r.number===t)}record(e){this.load(),this.runs=this.runs.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.runs.push(e),this.save()}all(){return this.load(),[...this.runs]}},ql=10*6e4;function es(n,e,t=Date.now()){if(n){if(n.status!=="running")return`spec tests already ran for this issue (${n.status})`;if(!(t-n.startedAt>e.maxMinutes*6e4+ql))return"spec tests are already running for this issue"}}function ka(n){let{settings:e,issue:t}=n;if(!e.enabled)return{run:!1,reason:"spec tests are off"};if(!t)return{run:!1,reason:"the issue text could not be read"};if(!Ul(`${t.title}
|
|
130
|
+
${t.body}`,e.paths))return{run:!1,reason:`issue names none of the pilot paths (${e.paths.join(", ")||"none set"})`};if(e.agent.trim().toLowerCase()===n.codeAgent.trim().toLowerCase())return{run:!1,reason:`the test agent "${e.agent}" is the coding agent; set quality.specTests.agent to another name`};let s=es(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:jl(t)}}function Gl(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function Kl(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function Jl(n){let e=n.split("\0").filter(Boolean),t=[];for(let s=0;s<e.length;s++){let r=e[s],o=r.slice(0,2);t.push({status:o,path:r.slice(3)}),(o.startsWith("R")||o.startsWith("C"))&&s++}return t}function zl(n){let e=[],t=[];for(let s of n)s.status==="??"&&Gl(s.path)?e.push(s.path):t.push(s.status==="??"?`${s.path} (new, not a test file)`:`${s.path} (${s.status.trim()||"changed"}, existing file)`);return{keep:e,discard:t}}var Ql=[["private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/],["GitHub token",/\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})/],["GitLab token",/\bglpat-[A-Za-z0-9_-]{20,}/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}/],["API key (sk-)",/\bsk-(?!ant-)(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/],["Stripe key",/\b[sr]k_live_[A-Za-z0-9]{20,}/],["DigitalOcean token",/\bdo[pro]_v1_[a-f0-9]{64}\b/],["Hugging Face token",/\bhf_[A-Za-z0-9]{30,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["JSON Web Token",/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/],["AWS access key",/\b(AKIA|ASIA)[0-9A-Z]{16}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{35}\b/],["Slack token",/\bxox[abposr]-[A-Za-z0-9-]{10,}/],["Telegram bot token",/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/],["password in a URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s@/]{8,}@/i]];function Xl(n){return Ql.filter(([,e])=>e.test(n)).map(([e])=>e)}var Yl=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],Zl=n=>`/${Vn(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function Vl(n,e){let t=Vn(n),s=a=>t===a||t.startsWith(a.endsWith(ya)?a:a+ya),r=El(),o=[...e,r,...Yl.map(a=>Zn(r,a)),"/proc"].map(a=>Vn(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let d=`/${Zl(a)}/**`;i.push(`Read(${d})`,`Edit(${d})`)}return i}async function va(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Sa(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},d,c=(l,p,m=12e4)=>s("git",l,{cwd:p,timeoutMs:m});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let p=r(),m={...a,...l,finishedAt:p,minutes:Math.round((p-o)/6e4*10)/10};n.store.record(m);let h=m.costUsd===void 0?"cost not reported":`$${m.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${m.status} in ${m.minutes} min, ${h}${m.note?` \u2014 ${m.note}`:""}`),m.status!=="pushed"&&m.note)try{await n.noteOnIssue(fa(`Spec tests for #${t.number} (${e.agent}): ${m.note}`,e.agent))}catch(b){n.log(`[spec-tests] ${t.repo}#${t.number}: could not leave the note on the issue: ${b?.message||b}`)}return m};try{let l=await c(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let p=await c(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),m=p.code===0&&p.stdout.trim()?p.stdout.trim():"origin/main";d=(n.makeTempDir??(()=>Ml(Zn(Ol(),`agentx-spec-${t.number}-`))))();let h=await c(["worktree","add","--detach",d,m],n.checkout);if(h.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${m}: ${h.stderr.trim().slice(0,300)}`});let b=await n.runAgent({prompt:Bl(t),dir:d,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:Vl(d,n.protectedPaths??[n.checkout,process.cwd()])});if(b.budgetStopped)return await u({status:"budget-stopped",costUsd:b.costUsd,note:`stopped at the budget of $${e.maxCostPerIssue.toFixed(2)} (quality.specTests.maxCostPerIssue). No tests were pushed; review the issue's acceptance criteria by hand.`});if(b.timedOut)return await u({status:"timed-out",costUsd:b.costUsd,note:`stopped after ${e.maxMinutes} minutes (quality.specTests.maxMinutes). No tests were pushed.`});if(!b.ok)return await u({status:"failed",costUsd:b.costUsd,note:`the test agent failed: ${(b.error||"no reason given").slice(0,300)}`});let y=await c(["status","--porcelain","-z","--untracked-files=all"],d);if(y.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not list the files the test agent wrote: ${y.stderr.trim().slice(0,300)}`});let{keep:x,discard:$}=zl(Jl(y.stdout));if($.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${$.join(", ")}`),!x.length)return await u({status:"no-tests",costUsd:b.costUsd,note:`the test agent wrote no new test file${$.length?` (its other changes were discarded: ${$.join(", ")})`:""}.`});let R=0,E=[];for(let A of x){let T=ba(Zn(d,A),"utf8");R+=Kl(T);for(let S of Xl(T))E.push(`${S} in ${A}`)}if(E.length)return await u({status:"blocked",costUsd:b.costUsd,testFiles:x,note:`a written file looks like it holds a secret (${E.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let k=Nl(e.agent),L=["-c",`user.name=${k.name}`,"-c",`user.email=${k.email}`],N=await c(["add","--",...x],d);if(N.code!==0)return await u({status:"failed",costUsd:b.costUsd,note:`could not stage the tests: ${N.stderr.trim().slice(0,300)}`});let O=`Written by ${e.agent} from the text of #${t.number} and its acceptance criteria only, without the implementation (#992).`,B=await c([...L,"commit","--no-verify","-m",Ia(t.number),"-m",O],d);if(B.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:x,note:`could not commit the tests: ${B.stderr.trim().slice(0,300)}`});let F=(await c(["rev-parse","HEAD"],d)).stdout.trim(),q=await c(["push","origin",`HEAD:refs/heads/${i}`],d);if(q.code!==0)return await u({status:"failed",costUsd:b.costUsd,testFiles:x,commit:F,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let z=await u({status:"pushed",costUsd:b.costUsd,branch:i,commit:F,testFiles:x,testsWritten:R});if(n.tellAuthor)try{await n.tellAuthor(`The spec tests for #${t.number} are on \`${i}\` (${x.join(", ")}). Merge them with \`git fetch origin ${i} && git merge --no-ff origin/${i}\`, run them, and record the outcome in the pull request's "Spec tests" section as described in your task.`)}catch(A){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${A?.message||A}`)}return z}catch(l){return await u({status:"failed",note:`unexpected error: ${(l?.message||String(l)).slice(0,300)}`})}finally{if(d){try{await c(["worktree","remove","--force",d],n.checkout)}catch{}try{Al(d)&&Pl(d,{recursive:!0,force:!0})}catch{}}}}var eg=5e3;function $a(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,d=[],c=(p,m)=>{if(!a){a=!0;for(let h of d)clearTimeout(h);s({code:p,stdout:r,stderr:m??o,timedOut:i})}},u;try{u=$l(n,e,{cwd:t.cwd,env:t.env,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(p){c(-1,p?.message||String(p));return}let l=t.killGraceMs??eg;t.timeoutMs&&d.push(setTimeout(()=>{i=!0,u.kill("SIGTERM"),d.push(setTimeout(()=>{u.kill("SIGKILL"),d.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),c(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",p=>{r+=p}),u.stderr?.on("data",p=>{o+=p}),u.stdin?.on("error",()=>{}),u.on("error",p=>c(-1,p.message)),u.on("close",p=>c(p??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var tn=async(n,e,t)=>{let s=await $a(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},tg="Read,Glob,Grep,Write,Edit";function ng(n){return["-p","-","--output-format","json","--tools",tg,"--permission-mode","acceptEdits","--max-budget-usd",String(n.maxBudgetUsd),...n.model?["--model",n.model]:[],"--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",JSON.stringify({disableAllHooks:!0,permissions:{deny:n.deny??[]}}),"--no-session-persistence"]}function wa(n,e){let t;try{t=JSON.parse(n)}catch{t=void 0}let s=typeof t?.total_cost_usd=="number"&&Number.isFinite(t.total_cost_usd)?t.total_cost_usd:void 0;return t?.subtype==="error_max_budget_usd"?{ok:!1,budgetStopped:!0,costUsd:s}:t?t.is_error||typeof t.subtype=="string"&&t.subtype!=="success"?{ok:!1,costUsd:s,error:String(t.result??t.subtype).slice(0,300)}:{ok:!0,costUsd:s,reply:String(t.result??"")}:{ok:!1,error:`claude exited ${e??"unknown"} with no result`}}var Aa=async n=>{let e=await $a("claude",ng(n),{cwd:n.dir,env:Vs(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:wa(e.stdout,e.code).costUsd};let t=wa(e.stdout,e.code);return!t.ok&&!t.budgetStopped&&e.stderr&&(!t.error||!e.stdout)&&(t.error=e.stderr.trim().slice(0,300)),t};async function Ca(n,e,t,s){let r=await n("gh",["issue","view",String(t),"--repo",e,"--json","title,body"],{cwd:s,timeoutMs:2e4});if(r.code===0)try{let o=JSON.parse(r.stdout);return typeof o?.title!="string"?void 0:{repo:e,number:t,title:o.title,body:typeof o.body=="string"?o.body:""}}catch{return}}async function Ma(n,e,t,s,r){let o=await n("gh",["issue","comment",String(t),"--repo",e,"--body",r],{cwd:s,timeoutMs:2e4});if(o.code!==0)throw new Error(o.stderr.trim().slice(0,300)||`gh exited ${o.code}`)}var rg=250,og=5e3,ug={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},Ra=`[Operating principle]
|
|
131
|
+
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.`,lg="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function gg(n){return n==="claude-code"?`${Ra}
|
|
132
|
+
${lg}`:n==="codex-cli"?Ra:""}function Pa(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var La;function Ph(n){La=n}function _h(){return La}var _a=64*1024,pg=5*60*1e3,fg=3e4,mg=300,We=".agentx/task-history",hg=30;function dt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function yg(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function wg(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=Tr(n,e,ee().recent());return vr(t,s)}function bg(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function xg(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let l=u.meta.type||"untyped",p=r.get(l)||[];p.push(u.meta.title),r.set(l,p)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
|
|
133
|
+
`),d=process.argv[1]||"dist/cli.js",c=n.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${s.length} article${s.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
134
|
+
node ${d} wiki query "the question" --dir ${c} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${d} wiki facts list --dir ${c}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,...t.notesInbox&&t.notesInbox.inbox!==e?["",`When you learn something the wiki should know (a change, a correction, a fact that went stale), leave a short note for the wiki run: \`node ${d} wiki notes add --from ${e} --change "what changed" --source "where you saw it" --date YYYY-MM-DD --daemon ${t.notesInbox.daemonUrl}\`. The run checks it before it changes anything. Notes stay inside the fleet; never put secrets in one.`]:[],"[End Institutional Wiki]"].join(`
|
|
135
|
+
`)}var ts=8*1024;function Sg(n,e){if(n)try{jr(n)}catch{}return e}function Ea(n){if(n.length<=ts)return n;let e=n.length-ts;return n.slice(0,ts)+`\u2026[+${e}]`}function Oa(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function Ig(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function Da(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=ee();if(s==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Ea(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Ea(a):null,at:r})}return}}function Tg(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
136
|
+
`;if(s==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
137
|
+
`;if(s==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
138
|
+
`;if(s==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
139
|
+
`;if(s==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
|
|
140
|
+
`;if(s==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
|
|
141
|
+
`;if(s==="codex.spawned"){let r=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${r}${o}
|
|
142
|
+
`}if(s==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
143
|
+
`;if(s==="turn.started")return`. codex turn started
|
|
144
|
+
`;if(s==="turn.completed"){let r=t.usage||{},o=r.input_tokens??r.inputTokens,i=r.output_tokens??r.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
|
|
145
|
+
`}if(s==="item.started"||s==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let d=r.text,c=d.startsWith(e)?d.slice(e.length):d;return e=d.startsWith(e)?d:e+d,c}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(s==="item.started")return`
|
|
146
|
+
> codex ${o}${i?` ${i}`:""}
|
|
147
|
+
`;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${dt(String(a),800)}`:""}
|
|
148
|
+
`}if(s==="error"||s==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${dt(String(r),800)}
|
|
149
|
+
`}if(s==="system"&&t.subtype==="init"){let r=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${r}${o}
|
|
150
|
+
`}if(s==="assistant"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>n.length&&(r+=o.text.slice(n.length),n=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")r+=`
|
|
151
|
+
\u{1F4AD} ${dt(o.thinking,600)}
|
|
152
|
+
`;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?dt(JSON.stringify(o.input),400):"";r+=`
|
|
153
|
+
\u2192 ${i}(${a})
|
|
154
|
+
`}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${dt(i,800)}
|
|
155
|
+
`}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
156
|
+
`:""}}var Na=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new mr;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;workflowAutoRunner;workflowRuns;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new pr;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;specTests;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new Bt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new dr(void 0,void 0,"graph"),this.memoryStore=new fr,this.patternStore=new Kt,this.rateLimiter=new Wt,this.tokenTracker=new lr,this.messageQueue=new qt,pi({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ar({baseDir:K(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new cr({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setRunNote(e){this.runNote=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=Ws(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Fr(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let d of a.def.mentions){if(t.atMentionsOnly&&!d.startsWith("@"))continue;let c=d.toLowerCase();s.includes(c)&&c.length>o&&(r=i,o=c.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,d=[];try{let p=this.sessions.getSession(e.agentId,s,r);i=jo(p.messages,e.message??""),d=Bo(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let c={message:e.message??"",previousMessage:i,recentRequests:d,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await we(eo,no(c),to,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!so(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),ee().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-2G6N3VF3.js"),d=await a(t,s);if(!d.memo){this.log(`[${e}] rotation memo skipped (${i}, ${d.reason}, ${d.durationMs}ms)`);return}let{storeRotationMemo:c}=await import("./rotation-memo-store-Z4D5KRA6.js"),u=c(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:d.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${d.durationMs}ms, ${d.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
157
|
+
`)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Zt(K(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Vt,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=Xn(t.context?.chatId),a=this.cloudSessionStore();return ua({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Vt,...e.cloudSessions??{}},i=Date.now(),a=Ce(nt(De(e.workspace),t),e.billing),d=l=>ga({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),c=await this.planSpecTests(t.agentId,s),u=await pa({route:s,agentId:t.agentId,message:c?`${t.message}
|
|
158
|
+
${Ta(c.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d,log:l=>this.log(l),trace:l=>{try{ee().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(c&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!es(this.specTestStore().get(c.repo,c.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,c,s.cwd,p=>d({cwd:s.cwd,prompt:p,sessionId:l}).then(m=>{if(!m.ok)throw new Error(m.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}specTestSettings(){return{...xa,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new en(K(process.cwd(),".agentx/spec-tests.json"))),this.specTests}async planSpecTests(e,t){let s=this.specTestSettings();if(!s.enabled||t.route!=="cloud"||t.kind!=="issue")return null;let r=await Ca(tn,t.repo,t.number,t.cwd),o=ka({settings:s,issue:r,codeAgent:e,previous:this.specTestStore().get(t.repo,t.number)});return o.run?o.input:(this.log(`[spec-tests] ${t.repo}#${t.number}: not running: ${o.reason}`),null)}async startSpecTests(e,t,s,r){try{await va({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:tn,runAgent:Aa,store:this.specTestStore(),noteOnIssue:o=>Ma(tn,t.repo,t.number,s,o),tellAuthor:r,log:o=>this.log(o)})}catch(o){this.log(`[spec-tests] ${t.repo}#${t.number}: ${o?.message||o}`)}}callerGone(e,t){let s=_e(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(u){i={content:"",error:u?.message??String(u)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let d=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;d&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:d,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&!d&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(c){let u=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${u}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let u=i.error?Xe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";wr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:u,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(u){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${u?.message??u}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};e.isolated&&(e.autonomy="report");let i=ge(e.autonomy),a=qs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:di().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(C=>C.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:g.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=Ht(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let g=Date.now(),f=25*6e4,C=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-g>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(v=>setTimeout(v,C))}}else if(u==="voice"){let g=Date.now(),f=25*6e4,C=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(C);){if(Date.now()-g>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(v=>setTimeout(v,500))}p=C,this.voiceClaims.add(C)}else{let g=c.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let C=this.messageQueue.pendingCount(e.agentId,u,l);return ee().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:mn(e.context),humanRoot:Je(e.context),person:hn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${C}) behind=${c.runningTasks.map(v=>v.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:hr(f,C)}}}let m=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,f)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!m.ok)return this.log(`[${e.agentId}] ${m.reason}`),{content:"",error:m.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let g=Xo(e.queuedAt);g&&(e.message=`${g}
|
|
159
|
+
${e.message}`),e.queuedAt=void 0}let h=ei({message:e.message,home:e.context?.home}),b=Vo(c.runningTasks,h,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});b&&(this.log(`[${e.agentId}] ${b.slice(0,160)}`),e.message=`${b}
|
|
160
|
+
${e.message}`),c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let y={...h.length?{homes:h}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};c.runningTasks.push(y),e.runningTaskId=y.id;let x=hn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(y.id,e.context??{}),e.onStart)try{e.onStart(y.id)}catch{}let $=new AbortController;this.taskAborts.set(y.id,{agentId:e.agentId,channel:y.channel,chatId:typeof y.chatId=="string"?y.chatId:"",originalMessage:e.message||"",controller:$,sender:e.context?.sender,rootId:$t()?.rootId,workflowRunId:e.workflowRunId??(typeof y.chatId=="string"&&y.chatId.startsWith("workflow:")&&y.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let R={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(y.id,R);let E=g=>{if(g){R.buffer+=g,R.buffer.length>_a&&(R.buffer=R.buffer.slice(R.buffer.length-_a));for(let f of R.subscribers)try{f(g)}catch{}}},k=Ee();e.taskId=k,y.traceId=k;let L=this.taskAborts.get(y.id);L&&(L.traceId=k);let N=new Map,O=(g,f,C)=>{try{ee().emit("task:step",{taskId:k,agentId:e.agentId,name:"pipeline",action:g,status:C,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},B=0,F=!1,q=()=>{F||(F=!0,B&&O("first-event",B,"ok"))},z;if(t){let g=Tg();z=f=>{q();let C=g(f);if(C&&E(C),Da(k,e.agentId,f),Oa(N,f),Hn(f,void 0,e.model||c.def.model),r)try{r(f)}catch{}}}else z=g=>{if(q(),Da(k,e.agentId,g),Oa(N,g),Hn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let A=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,T=A?setTimeout(()=>$.abort(new Error(`timed out after ${Math.round(A/1e3)}s`)),A):void 0;T?.unref?.();let S=(c.def.preSpawnTimeoutSec??mg)*1e3,U=setTimeout(()=>{$.abort(new Error(`timed out before spawn after ${Math.round(S/1e3)}s in step "${y.step??"start"}"`))},S);U.unref?.();let j=()=>{U&&clearTimeout(U),U=void 0},P=()=>`task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`,Q;$.signal.addEventListener("abort",()=>{let g=_e($.signal).message;/^timed out/.test(g)&&(Q=y.step??"start"),this.log(`[${e.agentId}] task ${y.id} aborted in step "${y.step??"start"}" \u2014 ${g} ${P()}`)},{once:!0});let ne=g=>{y.step=g,this.log(`[${e.agentId}] step ${g} ${P()}`)},X=(g,f,C=0)=>{if($.signal.aborted)return Promise.reject(_e($.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(j(),B=Date.now());let v=Date.now(),W=da(f(),ug[g]??0,g);return ca(W,$.signal,C).then(G=>(O(g,v,"ok"),G),G=>{throw O(g,v,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${P()}`),G})},_=async(g,f,C,v=0)=>{try{return await X(g,f,v)}catch(W){if(W instanceof Be)return C();throw W}},se=!1,ie=!1,ns=g=>{if(!(!se||ie)){ie=!0;try{ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-y.startedAt.getTime(),error:g?.error||($.signal.aborted?_e($.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(y.id)?!0:void 0,stopped:!this.interruptedRuns.has(y.id)&&(this.stoppedRuns.has(y.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ss=!1,rs=g=>{if(ss)return;ss=!0,ns(g),this.runReleases.delete(y.id),T&&clearTimeout(T),j(),c.activeTasks--;let f=c.runningTasks.findIndex(v=>v.id===y.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(y.id),this.taskAborts.delete(y.id);let C=this.runEndWaiters.get(y.id);this.runEndWaiters.delete(y.id);for(let v of C??[])try{v()}catch{}R.done=!0,R.endedAt=new Date;for(let v of R.subscribers)try{v(`
|
|
161
|
+
[task finished]
|
|
162
|
+
`)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),pg).unref?.();try{let v=R.endedAt,W={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(W);let G=(W.responseText||W.error||"").trim();if(G){let Z=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Z,at:v,ok:W.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let W=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,at:new Date().toISOString()});for(let Z of v){let $e=Z.originalContext||{channel:Z.channel,sender:Z.sender,chatId:Z.chatId};this.execute({message:Z.text,agentId:e.agentId,context:$e,queuedAt:Z.queuedAt??Z.timestamp}).then(me=>(Xe(me.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw G(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,rs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${P()}`);let w=e.context?.channel||"api",{evaluateRequest:Ua,selectRequestContext:Fa}=await import("./request-planner-DLQP2NV6.js"),os=_("request-gate",()=>Ua(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),nn=!1;os.then(()=>{nn=!0},()=>{nn=!0});let I=l,sn=e.context?.sender||"User",de=c.def.tier==="codex-cli",qe=Ei(this.config.session,w,c.def.tier),ut=Oi(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await _("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ha=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ia({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ha,taskId:k}),this.sessions.addUserMessage(e.agentId,w,I,sn,e.message);let is=Date.now(),as={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(is).toISOString(),taskId:k,resumeOrigin:zo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:mn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Hs(e.context),operator:js(e.context),dueAt:aa(e.context),taskType:Yt(e.context)};ee().emit("task:started",as),se=!0;let te,rn,cs=this.classifier;if(cs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();rn=cs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(y.intentPath=te.path.slice()),O("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),O("classify",g,"error")})}let ds=async g=>{if(!rn)return;let f;await Promise.race([rn,new Promise(C=>{f=setTimeout(C,g),f.unref?.()})]),f&&clearTimeout(f)};await ds(rg);let Te=this.config.workflows?.matching,fe,us,ls=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ls?.enabled&&(ls.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(us=Cr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Mr(this.config.workflows,e.agentId)&&Rr(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list()),C=Te?.autoRunThreshold??.85;f&&f.confidence>=C&&(fe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?dg():void 0,ja=ae?Pr(ae):void 0,Ba=this.wikiHub.getAgentWiki(e.agentId),gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),ps=this.memoryStore.buildContext(gs),fs=this.memoryStore.contextFacts(gs),Wa=this.patternStore.findRelevant(e.message,e.agentId,5),qa=this.patternStore.buildContext(Wa),ms="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),C=await X("skills",()=>g(c.def.workspace)),v=e.personLimits?.skills??[],W=v.length?C.filter(G=>!v.some(Z=>ze(Z,G.frontmatter.name))):C;ms=f(W,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=Vr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${In(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"cost");let C=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:C,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${In(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await _("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(H=void 0)}try{let g=await X("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",C=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${C} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Ga=process.env.AGENTX_CONTEXT_SURGERY==="1",Ka=de?{maxMessages:8,maxChars:2400}:Ga&&Pa(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ja=!H&&!de?xg(Ba,e.agentId,{notesInbox:bg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Ka):void 0,za=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,hs,ys=[];if(this.config.procedures?.injection?.enabled&&!H&&!de)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){hs=Gn(f),ys=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,C=f[0],v=f[f.length-1],W=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
|
|
163
|
+
`).length}L`,G=`[${e.agentId}] ${w}:${I} ${W} | session.messages=${f.length}`+(f.length>0?` first=${C.timestamp.slice(11,19)}(${C.role}:${(C.content||"").slice(0,40).replace(/\n/g," ")}) last=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let ws;if(c.def.contextReferences&&!H)try{let g=c.def.workspace,f=this.referencesCache.get(g);if(!f){let[v,W]=await X("references",()=>Promise.all([wn(c.def.workspace),bn(c.def.workspace)]));if(v.byId.size===0&&W.recipes.length===0){let[G,Z]=await X("references",()=>Promise.all([wn(process.cwd()),bn(process.cwd())]));f={refs:G,recipes:Z}}else f={refs:v,recipes:W};this.referencesCache.set(g,f)}let C=br({agentId:e.agentId,intentTags:te?.path,message:e.message},f.recipes,f.refs);C.cards.length>0&&(ws=yr(C.cards,500*4)),C.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${C.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let bs=ue||Ge?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),xs,pt=ue?null:Ho(e.message);if(pt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:pt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${pt.lookbackDays}d on this chat (cue-triggered)]`],C=[...g.turns].sort((v,W)=>v.ts.localeCompare(W.ts));for(let v of C){let W=v.ts.slice(11,16)+" "+v.day,G=v.role==="user"?v.senderName||"User":v.senderName||"Agent";f.push(`${W} ${G}: ${v.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),xs=f.join(`
|
|
164
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${pt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Qa=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Ss,Is,Ts=!1;nn||ne("request-gate");let ve=await os;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Qa==="planner"&&!ue&&!ve.active&&!Ge&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-3JDA7FNR.js"),f=await X("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Ts=!0,Ss=f.sessionHistory,ps=f.memoryContext,fs=f.memoryFacts,bs=f.crossChatContext,Is=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(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Ts&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let on=`${e.agentId}:${w}:${I}`,ft=nr(e.message);ft&&(ft==="default"?(this.activeSouls.delete(on),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(on,ft),this.log(`[${e.agentId}] Soul switched to: ${ft}`)));let Xa=this.activeSouls.get(on),Ya=er(c.def.workspace,Xa),Za=tr(Ya),Va=ue?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),ec=gg(c.def.tier),tc=kg(c.def.richMessages,w),nc=c.def.tier==="claude-code"&&(ue||qe!=="lean"||Di(ut)),ks="";if(c.def.workspace&&!nc){let g=K(c.def.workspace,"CLAUDE.md");if(ce(g))try{let f=ct(g,"utf-8");ks=`[Project CLAUDE.md]
|
|
165
|
+
${f.length>4e3?f.slice(0,4e3)+`
|
|
166
|
+
|
|
167
|
+
[CLAUDE.md truncated to 4KB]`:f}`}catch{}}let mt=e.context?.runbookPath,an=[];if(mt&&ce(mt)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,C=4e3,v=16e3;for(let W of g){if(f>=v)break;let G=K(mt,W);if(ce(G))try{let Z=ct(G,"utf-8"),$e=Z.length>C?Z.slice(0,C)+`
|
|
168
|
+
|
|
169
|
+
[${W} truncated to ${C} bytes]`:Z;an.push(`[Project Runbook \u2014 ${W} from ${mt}]
|
|
170
|
+
${$e}`),f+=$e.length}catch{}}}let sc=an.length>0?an.join(`
|
|
171
|
+
|
|
172
|
+
`):"",cn=[c.def.systemPrompt||"",ec,tc,ks,sc,Za||"",Va||""].filter(g=>g.trim().length>0).join(`
|
|
173
|
+
|
|
174
|
+
`)||void 0,ht={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:sn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ge||Pa(w,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:de?void 0:qa||void 0,procedureContext:[hs,us].filter(Boolean).join(`
|
|
175
|
+
|
|
176
|
+
`)||void 0,workflowRunContext:ja,references:ws,skillInjection:ms||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ss??gt,memoryContext:ps||void 0,crossChatContext:bs||void 0,longMemoryRecall:xs||void 0,contextOnDemand:Ge&&!H?ji(w,I):void 0,wikiContext:Ja,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(as)}catch{return}})(),rotationMemo:za,eventDigest:H?void 0:wg(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Hr(w,!H,c.def.richMessages);return g?Sg(c.def.workspace,g):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ue&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:Xs({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let vs=Qs(c.def.tier,this.config.decisions.routing),$s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&vs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-FVZCQJ6T.js"),f=await X("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:vs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),As=!1;$s.then(()=>{As=!0});let wt=ve.active&&ve.preprocess?await _("select-context",()=>Fa(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=Jo(wt.input,de?{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),rc=gr(bt,{memory:fs,procedures:ys,wikiContext:wt.input.wikiContext}),dn=(bt?.length??0)+(cn?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:cn?.length??0,message:e.message?.length??0},Cs=vi(e.agentId,w,I);$i(Cs,dn,xt);let Ms=Ai(Cs);Ms&&this.log(`[${e.agentId}] ${Ms}`),dn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${dn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),As||ne("route-model");let Rs=await $s,Ps=c.def.tier!=="claude-code"?void 0:ue?Ui():qe==="lean"?Li(c.def.workspace,ut,void 0,w):Hi(c.def.workspace);qe==="lean"&&!ue&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Bi(qe,ut,w)}`);let _s=c.def.tier==="claude-code"&&!H?Yr({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:k},g=>this.log(g)):void 0,oc={...e,systemPromptAppend:cn,...Ps?{claudeArgs:Ps}:{},...Rs?{model:Rs}:{}},re,Es=sa({agent:e.agentId,request:e.message,taskId:k,budgetMinutes:c.def.maxExecutionMinutes??20}),ic=z,Os=!1,un=!0;z=g=>{if(Es.observe(g),ae&&un)for(let f of Er(g))_r(f.name,f.input)||(un=!1);ic?.(g)};try{let g=this.workflowAutoRunner;if(fe&&g){let D=fe;try{let J=await X("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:D.follow?`Started the workflow "${J.title??D.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let D=Dr(ke,e.resumedFrom);Or(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:k,...D?{continues:D}:{}}),Os=!0,y.workflow={runId:ae,workflowId:Ar}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=c.def.persistentProcess?Et():null,J=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,le=[ui(ye),Ti(ye,void 0,e.model||c.def.model)].find(Tt=>Tt&&Tt.abort);if(le){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${le.reason}`);let Tt={content:"",error:le.message,duration:0};if(!t){R.buffer=`[error] ${le.message}`;for(let ac of R.subscribers)try{ac(R.buffer)}catch{}}return Tt}mi();let Ke=ki();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},C=this.planCloudSession(c.def,e);if(C.route==="local"){let D=f();if(D)return c.errors++,re=D,D}let v=c.def.tier==="claude-code",W=v?t:(D,J)=>{D&&E(D),t&&t(D,J)},G=!1,Z=v?s:D=>{D&&(G?E(D):(E(`\u{1F4AD} ${D}`),G=!0)),s&&s(D)},$e=()=>{G&&(E(`
|
|
177
|
+
`),G=!1)},me=v?W:W?(D,J)=>{$e(),W(D,J)}:void 0,M=await X("agent",async()=>{if(C.route!=="local"){let D=await this.runCloudSession(c.def,e,C,k);if(D)return D;let J=f();if(J)return J}return Lo(c.def,oc,this.providers,me,bt,H,z,$.signal,Z)},fg);if(!M.error){let D=Ig(c.def.toolUseRequired,N);if(D){let J=Array.from(N.entries()).map(([ye,It])=>`${ye}=${It}`).join(", ")||"none";M.error=`tool_required_not_called: ${D} (invoked: ${J})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${J}`)}}_s&&Zr(_s,{toolUses:N,eventsSeen:F,error:M.error,agentId:e.agentId},D=>this.log(D));let St=this.interruptedRuns.get(y.id);St&&(M.content="",M.error=St,M.errorKind="interrupted");let ln=St?void 0:this.stoppedRuns.get(y.id);ln&&(M.content="",M.error=ln,M.errorKind="stopped"),re=M;let he=M.usage?ur(M.usage):void 0;if(ie=!0,ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-is,error:M.error||void 0,errorKind:M.error?M.errorKind:void 0,interrupted:St?!0:void 0,stopped:ln?!0:void 0,inputTokens:he?.inputTokens,outputTokens:he?.outputTokens,cacheReadTokens:he?.cacheReadTokens,cacheCreateTokens:he?.cacheCreateTokens,tier2InputTokens:he?.tier2InputTokens,tier2OutputTokens:he?.tier2OutputTokens,tier2CacheReadTokens:he?.tier2CacheReadTokens,tier2CacheCreateTokens:he?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:M.numTurns,injectedContext:rc,finalResponse:M.content||void 0,billedModel:M.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let D=M.error?`[error] ${M.error}`:M.content;R.buffer=D;for(let J of R.subscribers)try{J(D)}catch{}}if(M.error)c.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,M.content),oa({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:M.content,taskId:k}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,M.usage,M.contextTokens),M.usage){let le=M.contextTokens,Ke=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(le??Ke)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${le??"n/a"} tokens (cumulative turn total=${Ke}) \u2014 next turn will rotate`)}if(or({channel:w,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await ds(og);try{let le=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:le,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
178
|
+
|
|
179
|
+
Agent: ${M.content}`,meta:yg(te,e.context)})}catch{}ir(e.agentId,e.message,M.content,{channel:w,chatId:I,sender:sn},this.memoryStore).catch(()=>{}),ri(e.agentId,e.message,M.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=M.billedModel||e.model||c.def.model,ye=e.context?.channel,It=ye&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ye}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,M.duration||0,M.usage,e.message.length,M.content.length,!1,J,ye,It),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${P()}`)}return M}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Rt(g.message);return re={content:"",error:Pt(f),errorKind:f.kind},re}finally{if(Es.stop(),Os&&ae&&ke)try{let g=re?.usage,f=Nr(ke,ae,{error:re?re.error||void 0:$.signal.aborted?_e($.signal).message:"run ended before completion",canceled:Lr(re?.errorKind)||this.stoppedRuns.has(y.id)||this.interruptedRuns.has(y.id)||!re&&$.signal.aborted,durationMs:Date.now()-y.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:un,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}ns(re),rs(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Ur(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),We,this.safe(e.agentId),t);ce(s)||ig(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);cg(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),We,this.safe(e));if(!ce(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=K(a,l);if(ce(p))try{for(let m of pe(p)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],b=parseInt(h,10);if(!Number.isFinite(b)||b<i||b>s)continue;let y=Math.floor((s-b)/36e5),x=t-1-y;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),We);if(!ce(e))return 0;let t=0;for(let s of pe(e)){let r=K(e,s),o;try{o=pe(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),d;try{d=pe(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(ct(K(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hg){let t=K(process.cwd(),We);if(!ce(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of pe(t)){let i=K(t,o),a;try{a=pe(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{ag(K(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return[];let r=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),d;try{d=pe(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(ct(K(a,c),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return null;let r=this.safe(t),o=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ce(a))try{return JSON.parse(ct(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=$r();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Xe(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=Ht(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);ee().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Bs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Xe(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function kg(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
180
|
+
`)}export{ro as a,Fg as b,io as c,vc as d,ao as e,Ot as f,Zg as g,np as h,sp as i,cp as j,Ht as k,Kc as l,Oo as m,Yc as n,Zc as o,Vc as p,Lo as q,Bt as r,Wt as s,Sd as t,Np as u,Lp as v,Gt as w,Hp as x,Ln as y,ee as z,oi as A,Dd as B,Fd as C,ci as D,nf as E,di as F,pi as G,bi as H,yf as I,xi as J,Jt as K,If as L,Tf as M,it as N,qu as O,Gu as P,Ku as Q,Ju as R,zu as S,qn as T,Yt as U,Vf as V,fa as W,at as X,ma as Y,im as Z,am as _,cm as $,dm as aa,um as ba,lm as ca,gm as da,vl as ea,lg as fa,gg as ga,Ph as ha,_h as ia,yg as ja,wg as ka,xg as la,ts as ma,Ea as na,Oa as oa,Ig as pa,Da as qa,Na as ra,kg as sa};
|
|
181
|
+
//# sourceMappingURL=chunk-O7SYQXKS.js.map
|