agentix-cli 0.147.0 → 0.149.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/dist/{App-AW4OROPH.js → App-2O2UUZGG.js} +2 -2
- package/dist/{ChatApp-USXQHII3.js → ChatApp-YU4NF63L.js} +2 -2
- package/dist/{absorb-eval-WZCC5VPS.js → absorb-eval-WHWOJYDX.js} +2 -2
- package/dist/{agent-TJ2K7FZG.js → agent-NLCR6VBE.js} +2 -2
- package/dist/{board-dashboard-JY4YQ5TM.js → board-dashboard-VPDXHHWC.js} +5 -5
- package/dist/{board-dashboard-JY4YQ5TM.js.map → board-dashboard-VPDXHHWC.js.map} +1 -1
- package/dist/{chunk-PUW4C6YO.js → chunk-2MW32M2D.js} +2 -2
- package/dist/{chunk-JLEVL66V.js → chunk-3HVRWULP.js} +2 -2
- package/dist/{chunk-7ICJCJ43.js → chunk-5IHUZVPU.js} +2 -2
- package/dist/{chunk-GJMYG53S.js → chunk-5QXRPYOY.js} +2 -2
- package/dist/{chunk-EG7Y2XLK.js → chunk-6QFDFYI7.js} +2 -2
- package/dist/{chunk-7HCSLOTP.js → chunk-6TJNWUMA.js} +3 -3
- package/dist/{chunk-P6PFTNN4.js → chunk-6YNRLI6I.js} +2 -2
- package/dist/chunk-A76PNG4E.js +4 -0
- package/dist/chunk-A76PNG4E.js.map +1 -0
- package/dist/{chunk-4F5XUF6T.js → chunk-AONY6U45.js} +2 -2
- package/dist/{chunk-7T6SMNVY.js → chunk-ATCIRFH6.js} +2 -2
- package/dist/{chunk-KW6SHOAN.js → chunk-BZ6Y264Z.js} +2 -2
- package/dist/{chunk-UVF3K5YS.js → chunk-DWOERPBG.js} +2 -2
- package/dist/{chunk-E7YHXMJG.js → chunk-E7LPZAXP.js} +2 -2
- package/dist/{chunk-Q2QU32JP.js → chunk-EIY2HRAS.js} +2 -2
- package/dist/{chunk-EKAUOUN2.js → chunk-GMMRBTLQ.js} +2 -2
- package/dist/{chunk-QXPX2NGL.js → chunk-GRI5HOPC.js} +2 -2
- package/dist/{chunk-P5BFFU4Y.js → chunk-IGA3T3ZT.js} +2 -2
- package/dist/{chunk-MMBFAVBR.js → chunk-JOHDOEZ4.js} +2 -2
- package/dist/chunk-MNG2AMKZ.js +3 -0
- package/dist/chunk-MNG2AMKZ.js.map +1 -0
- package/dist/{chunk-MXDTLR45.js → chunk-NMYC5RW7.js} +2 -2
- package/dist/{chunk-YE2X3AFU.js → chunk-NW4N67TU.js} +2 -2
- package/dist/{chunk-5TGY4RIQ.js → chunk-OWMKQ4HZ.js} +2 -2
- package/dist/{chunk-HAEI2LNC.js → chunk-P34VSROA.js} +2 -2
- package/dist/{chunk-6UP5VD3H.js → chunk-PXKIPU27.js} +3 -3
- package/dist/chunk-PXKIPU27.js.map +1 -0
- package/dist/{chunk-JCFVH3NC.js → chunk-QZ6VBDMX.js} +40 -40
- package/dist/chunk-QZ6VBDMX.js.map +1 -0
- package/dist/{chunk-GTOQWMRY.js → chunk-S22IBRY6.js} +2 -2
- package/dist/{chunk-GLLHUHX2.js → chunk-UZWF7PFH.js} +2 -2
- package/dist/chunk-WGPMUWX7.js +35 -0
- package/dist/chunk-WGPMUWX7.js.map +1 -0
- package/dist/chunk-X7UQY7CH.js +5 -0
- package/dist/chunk-X7UQY7CH.js.map +1 -0
- package/dist/{chunk-ZZNAR6R2.js → chunk-XNS5OQ3U.js} +212 -212
- package/dist/chunk-XNS5OQ3U.js.map +1 -0
- package/dist/{chunk-7W3TLSZQ.js → chunk-Z7GEW2SR.js} +5 -5
- package/dist/cli.js +1 -1
- package/dist/{client-GLBNS45C.js → client-A2N6ETK2.js} +2 -2
- package/dist/{config-VRDFC7LW.js → config-2QM2WTI2.js} +2 -2
- package/dist/{config-mutate-HU3KKYCD.js → config-mutate-UJS4F7BT.js} +2 -2
- package/dist/config-mutator-VWR3SMD3.js +2 -0
- package/dist/{contributions-JXPYCLVB.js → contributions-43FWZOGF.js} +2 -2
- package/dist/{doctor-5Y7QSXNQ.js → doctor-IN6MWP6I.js} +2 -2
- package/dist/{follow-up-tool-53AYA2UQ.js → follow-up-tool-VB7K6HCL.js} +2 -2
- package/dist/{grants-O7SJ2J4B.js → grants-2S33F2LV.js} +2 -2
- package/dist/{hub-YCOUZFNU.js → hub-JNNNUAZM.js} +2 -2
- package/dist/index.d.ts +44 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/note-tool-EZWSB3J3.js +2 -0
- package/dist/note-tool-EZWSB3J3.js.map +1 -0
- package/dist/{program-CIJEGFYG.js → program-OTENO5DS.js} +174 -174
- package/dist/program-OTENO5DS.js.map +1 -0
- package/dist/{promote-THTEHZHU.js → promote-VFYVWVTL.js} +2 -2
- package/dist/{query-N7JBDLR7.js → query-RB2MU2HV.js} +2 -2
- package/dist/{query-settings-BJTVDDCH.js → query-settings-5B54WHCS.js} +2 -2
- package/dist/{registry-LJ66OZYJ.js → registry-6OX7U6FV.js} +2 -2
- package/dist/{request-planner-PCELXLK7.js → request-planner-TUHVEYSF.js} +2 -2
- package/dist/{review-candidates-EMJUROJH.js → review-candidates-FDYTGG2N.js} +2 -2
- package/dist/{routing-D2KNBEMG.js → routing-U35SFPEI.js} +2 -2
- package/dist/schedule-tool-EPQKUYJX.js +2 -0
- package/dist/{scheduler-73UEBYV4.js → scheduler-H2QHWNQ2.js} +2 -2
- package/dist/{seat-UFAMWG7M.js → seat-EB3KJMIE.js} +2 -2
- package/dist/{select-EPWELLAV.js → select-IU4IOVSO.js} +2 -2
- package/dist/{set-enabled-LS65QZQS.js → set-enabled-64BSJ7LR.js} +2 -2
- package/dist/{tool-7LKYIA6D.js → tool-B23ACEHV.js} +2 -2
- package/dist/{tool-4S3YKLCN.js → tool-W3CIQZJ7.js} +2 -2
- package/dist/{wiki-LHT6X2JF.js → wiki-4KMRUD5C.js} +2 -2
- package/dist/wiki-enrich-N4GLW2JX.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-6UP5VD3H.js.map +0 -1
- package/dist/chunk-JCFVH3NC.js.map +0 -1
- package/dist/chunk-TJZGAKIB.js +0 -4
- package/dist/chunk-TJZGAKIB.js.map +0 -1
- package/dist/chunk-VY7TBMJU.js +0 -3
- package/dist/chunk-VY7TBMJU.js.map +0 -1
- package/dist/chunk-Z3AI4KXT.js +0 -18
- package/dist/chunk-Z3AI4KXT.js.map +0 -1
- package/dist/chunk-ZZNAR6R2.js.map +0 -1
- package/dist/config-mutator-JCAIGP6W.js +0 -2
- package/dist/program-CIJEGFYG.js.map +0 -1
- package/dist/schedule-tool-55MOWHKD.js +0 -2
- package/dist/wiki-enrich-CBBS3AC7.js +0 -2
- /package/dist/{App-AW4OROPH.js.map → App-2O2UUZGG.js.map} +0 -0
- /package/dist/{ChatApp-USXQHII3.js.map → ChatApp-YU4NF63L.js.map} +0 -0
- /package/dist/{absorb-eval-WZCC5VPS.js.map → absorb-eval-WHWOJYDX.js.map} +0 -0
- /package/dist/{agent-TJ2K7FZG.js.map → agent-NLCR6VBE.js.map} +0 -0
- /package/dist/{chunk-PUW4C6YO.js.map → chunk-2MW32M2D.js.map} +0 -0
- /package/dist/{chunk-JLEVL66V.js.map → chunk-3HVRWULP.js.map} +0 -0
- /package/dist/{chunk-7ICJCJ43.js.map → chunk-5IHUZVPU.js.map} +0 -0
- /package/dist/{chunk-GJMYG53S.js.map → chunk-5QXRPYOY.js.map} +0 -0
- /package/dist/{chunk-EG7Y2XLK.js.map → chunk-6QFDFYI7.js.map} +0 -0
- /package/dist/{chunk-7HCSLOTP.js.map → chunk-6TJNWUMA.js.map} +0 -0
- /package/dist/{chunk-P6PFTNN4.js.map → chunk-6YNRLI6I.js.map} +0 -0
- /package/dist/{chunk-4F5XUF6T.js.map → chunk-AONY6U45.js.map} +0 -0
- /package/dist/{chunk-7T6SMNVY.js.map → chunk-ATCIRFH6.js.map} +0 -0
- /package/dist/{chunk-KW6SHOAN.js.map → chunk-BZ6Y264Z.js.map} +0 -0
- /package/dist/{chunk-UVF3K5YS.js.map → chunk-DWOERPBG.js.map} +0 -0
- /package/dist/{chunk-E7YHXMJG.js.map → chunk-E7LPZAXP.js.map} +0 -0
- /package/dist/{chunk-Q2QU32JP.js.map → chunk-EIY2HRAS.js.map} +0 -0
- /package/dist/{chunk-EKAUOUN2.js.map → chunk-GMMRBTLQ.js.map} +0 -0
- /package/dist/{chunk-QXPX2NGL.js.map → chunk-GRI5HOPC.js.map} +0 -0
- /package/dist/{chunk-P5BFFU4Y.js.map → chunk-IGA3T3ZT.js.map} +0 -0
- /package/dist/{chunk-MMBFAVBR.js.map → chunk-JOHDOEZ4.js.map} +0 -0
- /package/dist/{chunk-MXDTLR45.js.map → chunk-NMYC5RW7.js.map} +0 -0
- /package/dist/{chunk-YE2X3AFU.js.map → chunk-NW4N67TU.js.map} +0 -0
- /package/dist/{chunk-5TGY4RIQ.js.map → chunk-OWMKQ4HZ.js.map} +0 -0
- /package/dist/{chunk-HAEI2LNC.js.map → chunk-P34VSROA.js.map} +0 -0
- /package/dist/{chunk-GTOQWMRY.js.map → chunk-S22IBRY6.js.map} +0 -0
- /package/dist/{chunk-GLLHUHX2.js.map → chunk-UZWF7PFH.js.map} +0 -0
- /package/dist/{chunk-7W3TLSZQ.js.map → chunk-Z7GEW2SR.js.map} +0 -0
- /package/dist/{client-GLBNS45C.js.map → client-A2N6ETK2.js.map} +0 -0
- /package/dist/{config-VRDFC7LW.js.map → config-2QM2WTI2.js.map} +0 -0
- /package/dist/{config-mutate-HU3KKYCD.js.map → config-mutate-UJS4F7BT.js.map} +0 -0
- /package/dist/{config-mutator-JCAIGP6W.js.map → config-mutator-VWR3SMD3.js.map} +0 -0
- /package/dist/{contributions-JXPYCLVB.js.map → contributions-43FWZOGF.js.map} +0 -0
- /package/dist/{doctor-5Y7QSXNQ.js.map → doctor-IN6MWP6I.js.map} +0 -0
- /package/dist/{follow-up-tool-53AYA2UQ.js.map → follow-up-tool-VB7K6HCL.js.map} +0 -0
- /package/dist/{grants-O7SJ2J4B.js.map → grants-2S33F2LV.js.map} +0 -0
- /package/dist/{hub-YCOUZFNU.js.map → hub-JNNNUAZM.js.map} +0 -0
- /package/dist/{promote-THTEHZHU.js.map → promote-VFYVWVTL.js.map} +0 -0
- /package/dist/{query-N7JBDLR7.js.map → query-RB2MU2HV.js.map} +0 -0
- /package/dist/{query-settings-BJTVDDCH.js.map → query-settings-5B54WHCS.js.map} +0 -0
- /package/dist/{registry-LJ66OZYJ.js.map → registry-6OX7U6FV.js.map} +0 -0
- /package/dist/{request-planner-PCELXLK7.js.map → request-planner-TUHVEYSF.js.map} +0 -0
- /package/dist/{review-candidates-EMJUROJH.js.map → review-candidates-FDYTGG2N.js.map} +0 -0
- /package/dist/{routing-D2KNBEMG.js.map → routing-U35SFPEI.js.map} +0 -0
- /package/dist/{schedule-tool-55MOWHKD.js.map → schedule-tool-EPQKUYJX.js.map} +0 -0
- /package/dist/{scheduler-73UEBYV4.js.map → scheduler-H2QHWNQ2.js.map} +0 -0
- /package/dist/{seat-UFAMWG7M.js.map → seat-EB3KJMIE.js.map} +0 -0
- /package/dist/{select-EPWELLAV.js.map → select-IU4IOVSO.js.map} +0 -0
- /package/dist/{set-enabled-LS65QZQS.js.map → set-enabled-64BSJ7LR.js.map} +0 -0
- /package/dist/{tool-7LKYIA6D.js.map → tool-B23ACEHV.js.map} +0 -0
- /package/dist/{tool-4S3YKLCN.js.map → tool-W3CIQZJ7.js.map} +0 -0
- /package/dist/{wiki-LHT6X2JF.js.map → wiki-4KMRUD5C.js.map} +0 -0
- /package/dist/{wiki-enrich-CBBS3AC7.js.map → wiki-enrich-N4GLW2JX.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as Lr,H as $r,I as Ar,J as Cr,L as Mr,M as Rr,N as Pr,O as _r,R as Er,S as Or,V as Dr,W as Nr,a as ur,b as lr,ba as Ur,d as pr,f as Xe,l as At,m as kr,t as Ct,v as vr}from"./chunk-
|
|
1
|
+
import{$ as Lr,H as $r,I as Ar,J as Cr,L as Mr,M as Rr,N as Pr,O as _r,R as Er,S as Or,V as Dr,W as Nr,a as ur,b as lr,ba as Ur,d as pr,f as Xe,l as At,m as kr,t as Ct,v as vr}from"./chunk-BZ6Y264Z.js";import{b as gr}from"./chunk-MEFPXHQJ.js";import{a as Tr}from"./chunk-W4YR2RO2.js";import{a as cr}from"./chunk-5TTHN7DP.js";import{b as mr,c as wn,d as yr,e as $t,h as wr}from"./chunk-6YNRLI6I.js";import{e as ar,f as dr}from"./chunk-36AXN6ZB.js";import{a as hn,b as fr}from"./chunk-J3SOEFRE.js";import{a as yn,b as hr}from"./chunk-SIU6STB2.js";import{e as br,i as xr,j as Sr,k as Ir}from"./chunk-X5C5W3E4.js";import{a as ir}from"./chunk-2MW32M2D.js";import{g as rr,h as or}from"./chunk-EIY2HRAS.js";import{c as Ks,f as Js}from"./chunk-GMMRBTLQ.js";import{s as qs,v as vt,w as Gs,y as we,z as mn}from"./chunk-OWMKQ4HZ.js";import{a as Qe,b as Oe,f as kt}from"./chunk-72SZI2UW.js";import{a as Ee,b as un}from"./chunk-FCPTN6NF.js";import{a as zs,c as Qs}from"./chunk-MYVHVJWZ.js";import{d as De,g as Xs,h as Ce}from"./chunk-6TURWSMN.js";import{a as Ys,b as Zs,c as Vs,d as er,l as tr}from"./chunk-AV7T3SYT.js";import{a as nr,b as sr}from"./chunk-Y5MFVVTM.js";import{c as _s,d as Es}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ua as nd,V as Ls,X as pn,Z as ed,aa as Us,ea as td,ka as Fs,la as fn,ma as Hs,na as ze,oa as js,pa as Bs,va as Ws}from"./chunk-PXKIPU27.js";import{g as Je,h as Za}from"./chunk-BRK6M6LA.js";import{f as gn,n as Va}from"./chunk-UIBUZ2N3.js";import{a as Os,b as ge,c as Ds,d as Ns,e as ln}from"./chunk-2QNT5JDS.js";mn();kt();var Mt="tool-set",Fr=["answer","code","full"],Hr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},sd=.1;function Br(n){return{task:jr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:jr(n.agentPrompt,600)}:{}}}var Wr={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 qr(n,e=sd){let s=n?.bundle?.probabilities;if(!s)return"full";let r=bn(s.answer),o=bn(s.code),i=bn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Gr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Hr.answer.includes(t))?"answer":e.every(t=>Hr.code.includes(t))?"code":"full"}function Kr(n,e){return Fr.indexOf(n)<Fr.indexOf(e)}function bn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function jr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Jr=!1;function zr(n,e){let t=vt(Mt);if(t!=="off")return t==="active"&&!Jr&&(Jr=!0,e(`[decisions] seat "${Mt}" is set to active, but only shadow is built: it records and changes nothing`)),we(Mt,Br(n),Wr,{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=qr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Qr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Gr(r);Gs(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}`+(Kr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function rd(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Xr(n,e){let t=rd(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 xn(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)`}mn();kt();var Yr="session-continuity",Zr={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 Vr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Sn(n.message,1200),previousRequest:n.previousMessage?Sn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Sn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function eo(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 Sn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ut}from"execa";import{spawn as od}from"node:child_process";import{createHash as id}from"node:crypto";import{createInterface as ad}from"node:readline";var be=class extends Error{},dd=n=>od("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),In=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(),ad({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
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()}},Tn=class{constructor(e=dd,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=id("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[M])=>w.localeCompare(M))])).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 w=[...this.entries].find(([,M])=>!M.connection.busy);if(!w)throw new be("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:s,connection:new In(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,c="",d,u,l,f,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=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 w={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",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let P=new Promise((N,R)=>{i.failTurn=R,i.notify=(E,U)=>{if(U?.threadId!==u)return;let D=U.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...U,type:E.replace("/","."),...D?{item:{...D,type:W[D.type]||D.type}}:{}}),E==="item/completed"&&D?.type==="agentMessage"&&D.phase==="final_answer"&&(d=D.text),E==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=U.delta,e.onDelta?.(U.delta,c)),E==="thread/tokenUsage/updated"){let F=U.tokenUsage.last;f=F.inputTokens;let G=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-G),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+G,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}E==="turn/completed"&&(U.turn.status==="completed"?N():R(new Error(U.turn.error?.message||`Codex turn ${U.turn.status}`)))}});return P.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await P,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:f,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new be(w.message);return{content:c,codexSessionId:u,usage:l,contextTokens:f,error:w.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(b),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},to=new Tn;import{execFile as Md}from"child_process";import{StringDecoder as tt}from"string_decoder";import{mkdtempSync as xo,readFileSync as So,rmSync as Io}from"fs";import{join as Nt}from"path";import{tmpdir as To}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 d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function 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,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var no=null;function Et(){return no}function kg(n){no=n}function Ye(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function cd(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"}},so=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=cd(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(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as ud}from"child_process";import{randomUUID as ld}from"crypto";import{existsSync as gd,readFileSync as pd}from"fs";import{resolve as fd}from"path";function md(n){let e=fd(n,"CLAUDE.md");if(!gd(e))return null;try{let t=pd(e,"utf8");return tr(t)}catch{return null}}var hd=20*60*1e3,yd=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 wd(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 ro=class{constructor(e={}){this.opts=e}spawn(e,t){return new kn(e,t,this.opts)}},kn=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=ud(r,o,{cwd:t.workspace,env:Ce(wd({...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:md(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),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=ld(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??hd,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ze(c)),l=!1,f=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ve(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(p.type==="user"&&p.uuid===i)l=!0,f&&(yield{type:f.type,raw:f});else if(p.type==="system"&&p.subtype==="init")f=p;else if(p.type==="result"){f=null;let b=typeof p.result=="string"?p.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:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{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)},yd);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
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"}}};ln();Va();un();import{resolve as oo,join as io}from"path";var bd=4e3;function Ot(n){try{let e=io(oo(n.root),".agentx","db.sqlite"),t=gn({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,bd):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function Pd(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};N.stdout?.on("data",T=>{D+=F.write(T);let x=D.split(`
|
|
32
32
|
`);D=x.pop()||"";for(let L of x)Q(L)}),N.stderr?.on("data",T=>{W+=G.write(T)});let $=await N;if(i&&i.removeEventListener("abort",U),D+=F.end(),D.trim()&&Q(D),W+=G.end(),R)return{content:"",error:E||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(M/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?x=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=yo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return S=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(M){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let P=/ENOENT|spawn opencode/i.test(M?.message||"")?yo():M?.message;return{content:l,...Z(P||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{w?.(),b?.release(S)}}async function Bd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Wd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let S=n.provider||"claude-code",w=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,M=e.context?.sender,P=typeof M=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(M),N=e.context?.channel==="web-chat"&&P?{userId:M,agentId:e.agentId||"acme-public"}:void 0,R=er(n),E=Object.keys(R).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:N,providerOpts:o,abortSignal:l.signal,mcpServers:E?R:void 0};if(r){let{generateStream:Q}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,M=e.context?.sender,P=typeof M=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(M),N=e.context?.channel==="web-chat"&&P?{userId:M,agentId:e.agentId||"acme-public"}:void 0,R=er(n),E=Object.keys(R).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:N,providerOpts:o,abortSignal:l.signal,mcpServers:E?R:void 0};if(r){let{generateStream:Q}=await import("./agent-NLCR6VBE.js"),$="",T,x,L,j;for await(let C of Q(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")$+=C.text,r(C.text,$);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(x=C.result.inputTokens),C.result.outputTokens!=null&&(L=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(j=C.error)}return j&&!$?f?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-d}:((x===void 0||L===void 0)&&T&&(x=Math.round(T*.7),L=T-x),{content:$||"Done.",tokensUsed:T,usage:x!==void 0||L!==void 0?{inputTokens:x||0,outputTokens:L||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:D}=await import("./agent-NLCR6VBE.js"),W=await D(U),F=W.inputTokens,G=W.outputTokens;if((F===void 0||G===void 0)&&W.tokensUsed){let Q=W.tokensUsed;F=Math.round(Q*.7),G=Q-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||G!==void 0?{inputTokens:F||0,outputTokens:G||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return f?b():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var $n=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}},qd=1e3;async function Gd(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"}),qd),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 Kd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof Ne,null}h&&Rn(e.agentId,n,e.model,s,"persistent");let p=Se(n,e,t),b="",S,w,M,P,N,R,E,U="",D="",W=$=>{if(!i||!$)return;let T;if(D&&$.startsWith(D)?T=$.slice(D.length):T=U&&!U.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${$}`:$,D=$,!!T){U+=T;try{i(T,U)}catch{}}},F=!1,G=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?G():o.addEventListener("abort",G,{once:!0}));let Q=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(Q=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(D="");let L=T.raw.message?.usage;if(L){let j=(L.input_tokens||0)+(L.cache_read_input_tokens||0)+(L.cache_creation_input_tokens||0);j>0&&(P=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let L=Z(typeof x.result=="string"?x.result:"claude error");S=L.error,w=L.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,U||W(x.result));typeof x.session_id=="string"&&(E=x.session_id),x.usage&&(M={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(N=x.num_turns),typeof x.message?.model=="string"?R=x.message.model:typeof x.model=="string"?R=x.model:R=_t(x.modelUsage)||R}}}catch($){if(F)S="task cancelled by operator",w="cancelled";else if(Q)if($ instanceof Ve)S=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,w="interrupted";else if($ instanceof Ze){let T=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=T.error,w=T.errorKind}else{let T=Z(`persistent claude process error: ${$?.message||String($)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",G),null}finally{o&&o.removeEventListener("abort",G)}return F&&!S&&(S="task cancelled by operator",w="cancelled"),{content:F?"":b,error:S,errorKind:w,duration:Date.now()-c,usage:M,contextTokens:P,numTurns:N,billedModel:R,claudeSessionId:E}}function Eo(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?uo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:mo(t.args,n.taskId,n.agentId)}function Jd(n){return ge(n.autonomy)||!!n.personLimits}async function zd(n,e,t,s,r,o,i){let a=ge(e.autonomy)?e.autonomy:void 0,c=a&&lo(a,n.tier)||e.personLimits&&ho(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${Ns(a)}
|
|
@@ -152,7 +152,7 @@ ${Xl}`:n==="codex-cli"?xa:""}function Sa(n,e){return e!=="claude-code"&&e!=="cod
|
|
|
152
152
|
${pa(d.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:c,log:l=>this.log(l),trace:l=>{try{V().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(d&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!Vn(this.specTestStore().get(d.repo,d.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,d,s.cwd,f=>c({cwd:s.cwd,prompt:f,sessionId:l}).then(h=>{if(!h.ok)throw new Error(h.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}specTestSettings(){return{...ua,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new Zt(J(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 wa(Vt,t.repo,t.number,t.cwd),o=fa({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 ma({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:Vt,runAgent:ya,store:this.specTestStore(),noteOnIssue:o=>ba(Vt,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 c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(d){let 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";mr().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=js(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:Vo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let g=await c;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 d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(v=>v.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=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:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=Ht(e.context),f;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let g=Date.now(),m=25*6e4,v=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(k=>setTimeout(k,v))}}else if(u==="voice"){let g=Date.now(),m=25*6e4,v=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(v);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(k=>setTimeout(k,500))}f=v,this.voiceClaims.add(v)}else{let g=d.def.queueMode||"collect",m=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(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let v=this.messageQueue.pendingCount(e.agentId,u,l);return V().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:pn(e.context),humanRoot:Je(e.context),person:fn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${v}) behind=${d.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:pr(m,v)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(f&&this.voiceClaims.delete(f),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let g=qo(e.queuedAt);g&&(e.message=`${g}
|
|
153
153
|
${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let b=fn(this.config.people,e.context);if(e.context&&(b?e.context.person=b.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let S=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:S,sender:e.context?.sender,rootId:$t()?.rootId,workflowRunId:e.workflowRunId??(typeof p.chatId=="string"&&p.chatId.startsWith("workflow:")&&p.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let w={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,w);let M=g=>{if(g){w.buffer+=g,w.buffer.length>Ia&&(w.buffer=w.buffer.slice(w.buffer.length-Ia));for(let m of w.subscribers)try{m(g)}catch{}}},P=Ee();e.taskId=P,p.traceId=P;let N=this.taskAborts.get(p.id);N&&(N.traceId=P);let R=new Map,E=(g,m,v)=>{try{V().emit("task:step",{taskId:P,agentId:e.agentId,name:"pipeline",action:g,status:v,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},U=0,D=!1,W=()=>{D||(D=!0,U&&E("first-event",U,"ok"))},F;if(t){let g=dg();F=m=>{W();let v=g(m);if(v&&M(v),va(P,e.agentId,m),ka(R,m),Fn(m,void 0,e.model||d.def.model),r)try{r(m)}catch{}}}else F=g=>{if(W(),va(P,e.agentId,g),ka(R,g),Fn(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let G=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,Q=G?setTimeout(()=>S.abort(new Error(`timed out after ${Math.round(G/1e3)}s`)),G):void 0;Q?.unref?.();let $=(d.def.preSpawnTimeoutSec??eg)*1e3,T=setTimeout(()=>{S.abort(new Error(`timed out before spawn after ${Math.round($/1e3)}s in step "${p.step??"start"}"`))},$);T.unref?.();let x=()=>{T&&clearTimeout(T),T=void 0},L=()=>`task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`,j;S.signal.addEventListener("abort",()=>{let g=_e(S.signal).message;/^timed out/.test(g)&&(j=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${g} ${L()}`)},{once:!0});let C=g=>{p.step=g,this.log(`[${e.agentId}] step ${g} ${L()}`)},q=(g,m,v=0)=>{if(S.signal.aborted)return Promise.reject(_e(S.signal));C(g),(g==="agent"||g==="workflow-auto-run")&&(x(),U=Date.now());let k=Date.now(),B=Vi(m(),Ql[g]??0,g);return Zi(B,S.signal,v).then(K=>(E(g,k,"ok"),K),K=>{throw E(g,k,"error"),K instanceof Be&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${L()}`),K})},te=async(g,m,v,k=0)=>{try{return await q(g,m,k)}catch(B){if(B instanceof Be)return v();throw B}},ne=!1,_=!1,se=g=>{if(!(!ne||_)){_=!0;try{V().emit("task:completed",{taskId:P,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:g?.error||(S.signal.aborted?_e(S.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,stopped:!this.interruptedRuns.has(p.id)&&(this.stoppedRuns.has(p.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ie=!1,ts=g=>{if(ie)return;ie=!0,se(g),this.runReleases.delete(p.id),Q&&clearTimeout(Q),x(),d.activeTasks--;let m=d.runningTasks.findIndex(k=>k.id===p.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id);let v=this.runEndWaiters.get(p.id);this.runEndWaiters.delete(p.id);for(let k of v??[])try{k()}catch{}w.done=!0,w.endedAt=new Date;for(let k of w.subscribers)try{k(`
|
|
154
154
|
[task finished]
|
|
155
|
-
`)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),Zl).unref?.();try{let k=w.endedAt,B={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(p.id)||g?.errorKind==="stopped"?{status:"stopped"}:j?{status:"timeout",step:j}:{},responseText:g?.content||"",transcript:w.buffer};this.persistTaskRecord(B);let K=(B.responseText||B.error||"").trim();if(K){let Y=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:B.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Y of k){let $e=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:$e,queuedAt:Y.queuedAt??Y.timestamp}).then(me=>(Xe(me.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw K(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,ts),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${L()}`);let y=e.context?.channel||"api",{evaluateRequest:Ca,selectRequestContext:Ma}=await import("./request-planner-PCELXLK7.js"),ns=te("request-gate",()=>Ca(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),en=!1;ns.then(()=>{en=!0},()=>{en=!0});let I=l,tn=e.context?.sender||"User",ce=d.def.tier==="codex-cli",qe=Ti(this.config.session,y,d.def.tier),ut=ki(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let Ra=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(g=>g.role==="agent")?.content;Xi({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:Ra,taskId:P}),this.sessions.addUserMessage(e.agentId,y,I,tn,e.message);let ss=Date.now(),rs={agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(ss).toISOString(),taskId:P,resumeOrigin:Bo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:pn(e.context),...b?{person:b}:{},humanRoot:Je(e.context),pickup:Ls(e.context),operator:Us(e.context),dueAt:Yi(e.context),taskType:Qt(e.context)};V().emit("task:started",rs),ne=!0;let ee,nn,os=this.classifier;if(os&&y!=="a2a"&&!ce){C("classify");let g=Date.now();nn=os.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),E("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),E("classify",g,"error")})}let is=async g=>{if(!nn)return;let m;await Promise.race([nn,new Promise(v=>{m=setTimeout(v,g),m.unref?.()})]),m&&clearTimeout(m)};await is(Wl);let Te=this.config.workflows?.matching,fe,as,ds=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ds?.enabled&&(ds.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(Te?.suggestThreshold??.65)&&(as=vr(m.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:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Te.mode} reasons=${m.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&m.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:m.workflow.id,confidence:m.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=$r(this.config.workflows,e.agentId)&&Ar(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list()),v=Te?.autoRunThreshold??.85;m&&m.confidence>=v&&(fe={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?zl():void 0,Pa=ae?Cr(ae):void 0,_a=this.wikiHub.getAgentWiki(e.agentId),cs=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),us=this.memoryStore.buildContext(cs),ls=this.memoryStore.contextFacts(cs),Ea=this.patternStore.findRelevant(e.message,e.agentId,5),Oa=this.patternStore.buildContext(Ea),gs="";if(!ce)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),v=await q("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],B=k.length?v.filter(K=>!k.some(Y=>ze(Y,K.frontmatter.name))):v;gs=m(B,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,y,I,lt)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let g=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=Xr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:lt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${xn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${xn(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,g),()=>!1)&&(H=void 0)}try{let g=await q("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",v=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${m}%, ${v} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Da=process.env.AGENTX_CONTEXT_SURGERY==="1",Na=ce?{maxMessages:8,maxChars:2400}:Da&&Sa(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,La=!H&&!ce?og(_a,e.agentId,{notesInbox:rg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,y,I,Na):void 0,Ua=H?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ps,fs=[];if(this.config.procedures?.injection?.enabled&&!H&&!ce)try{let g=new it({baseDir:J(process.cwd(),this.config.procedures.dir)}),m=Wn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){ps=qn(m),fs=m.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of m)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let m=this.sessions.getSession(e.agentId,y,I).messages,v=m[0],k=m[m.length-1],B=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
|
|
155
|
+
`)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),Zl).unref?.();try{let k=w.endedAt,B={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(p.id)||g?.errorKind==="stopped"?{status:"stopped"}:j?{status:"timeout",step:j}:{},responseText:g?.content||"",transcript:w.buffer};this.persistTaskRecord(B);let K=(B.responseText||B.error||"").trim();if(K){let Y=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:B.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Y of k){let $e=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:$e,queuedAt:Y.queuedAt??Y.timestamp}).then(me=>(Xe(me.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw K(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,ts),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${L()}`);let y=e.context?.channel||"api",{evaluateRequest:Ca,selectRequestContext:Ma}=await import("./request-planner-TUHVEYSF.js"),ns=te("request-gate",()=>Ca(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),en=!1;ns.then(()=>{en=!0},()=>{en=!0});let I=l,tn=e.context?.sender||"User",ce=d.def.tier==="codex-cli",qe=Ti(this.config.session,y,d.def.tier),ut=ki(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let Ra=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(g=>g.role==="agent")?.content;Xi({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:Ra,taskId:P}),this.sessions.addUserMessage(e.agentId,y,I,tn,e.message);let ss=Date.now(),rs={agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(ss).toISOString(),taskId:P,resumeOrigin:Bo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:pn(e.context),...b?{person:b}:{},humanRoot:Je(e.context),pickup:Ls(e.context),operator:Us(e.context),dueAt:Yi(e.context),taskType:Qt(e.context)};V().emit("task:started",rs),ne=!0;let ee,nn,os=this.classifier;if(os&&y!=="a2a"&&!ce){C("classify");let g=Date.now();nn=os.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),E("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),E("classify",g,"error")})}let is=async g=>{if(!nn)return;let m;await Promise.race([nn,new Promise(v=>{m=setTimeout(v,g),m.unref?.()})]),m&&clearTimeout(m)};await is(Wl);let Te=this.config.workflows?.matching,fe,as,ds=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ds?.enabled&&(ds.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(Te?.suggestThreshold??.65)&&(as=vr(m.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:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Te.mode} reasons=${m.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&m.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:m.workflow.id,confidence:m.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=$r(this.config.workflows,e.agentId)&&Ar(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:J(process.cwd(),this.config.workflows.dir)}),m=Ct({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},g.list()),v=Te?.autoRunThreshold??.85;m&&m.confidence>=v&&(fe={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?zl():void 0,Pa=ae?Cr(ae):void 0,_a=this.wikiHub.getAgentWiki(e.agentId),cs=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),us=this.memoryStore.buildContext(cs),ls=this.memoryStore.contextFacts(cs),Ea=this.patternStore.findRelevant(e.message,e.agentId,5),Oa=this.patternStore.buildContext(Ea),gs="";if(!ce)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),v=await q("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],B=k.length?v.filter(K=>!k.some(Y=>ze(Y,K.frontmatter.name))):v;gs=m(B,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,y,I,lt)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let g=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=Xr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:lt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${xn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),V().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${xn(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,g),()=>!1)&&(H=void 0)}try{let g=await q("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",v=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${m}%, ${v} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Da=process.env.AGENTX_CONTEXT_SURGERY==="1",Na=ce?{maxMessages:8,maxChars:2400}:Da&&Sa(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,La=!H&&!ce?og(_a,e.agentId,{notesInbox:rg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,y,I,Na):void 0,Ua=H?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ps,fs=[];if(this.config.procedures?.injection?.enabled&&!H&&!ce)try{let g=new it({baseDir:J(process.cwd(),this.config.procedures.dir)}),m=Wn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){ps=qn(m),fs=m.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of m)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let m=this.sessions.getSession(e.agentId,y,I).messages,v=m[0],k=m[m.length-1],B=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
|
|
156
156
|
`).length}L`,K=`[${e.agentId}] ${y}:${I} ${B} | session.messages=${m.length}`+(m.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",K)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let ms;if(d.def.contextReferences&&!H)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,B]=await q("references",()=>Promise.all([hn(d.def.workspace),yn(d.def.workspace)]));if(k.byId.size===0&&B.recipes.length===0){let[K,Y]=await q("references",()=>Promise.all([hn(process.cwd()),yn(process.cwd())]));m={refs:K,recipes:Y}}else m={refs:k,recipes:B};this.referencesCache.set(g,m)}let v=hr({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);v.cards.length>0&&(ms=fr(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let hs=ue||Ge?"":this.sessions.getCrossSessionSummary(e.agentId,y,I,e.message),ys,pt=ue?null:Lo(e.message);if(pt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:I,lookbackDays:pt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${pt.lookbackDays}d on this chat (cue-triggered)]`],v=[...g.turns].sort((k,B)=>k.ts.localeCompare(B.ts));for(let k of v){let B=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${B} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),ys=m.join(`
|
|
157
157
|
`),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 Fa=ce?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",ws,bs,xs=!1;en||C("request-gate");let ve=await ns;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Fa==="planner"&&!ue&&!ve.active&&!Ge&&y!=="voice"&&y!=="desktop"){try{let{planContext:g}=await import("./context-planner-3JDA7FNR.js"),m=await q("plan-context",()=>g({agentId:e.agentId,channel:y,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(xs=!0,ws=m.sessionHistory,us=m.memoryContext,ls=m.memoryFacts,hs=m.crossChatContext,bs=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.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)`)}xs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,y,I),H=void 0)}let sn=`${e.agentId}:${y}:${I}`,ft=Vs(e.message);ft&&(ft==="default"?(this.activeSouls.delete(sn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(sn,ft),this.log(`[${e.agentId}] Soul switched to: ${ft}`)));let Ha=this.activeSouls.get(sn),ja=Ys(d.def.workspace,Ha),Ba=Zs(ja),Wa=ue?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),qa=Yl(d.def.tier),Ga=cg(d.def.richMessages,y),Ka=d.def.tier==="claude-code"&&(ue||qe!=="lean"||vi(ut)),Ss="";if(d.def.workspace&&!Ka){let g=J(d.def.workspace,"CLAUDE.md");if(de(g))try{let m=dt(g,"utf-8");Ss=`[Project CLAUDE.md]
|
|
158
158
|
${m.length>4e3?m.slice(0,4e3)+`
|
|
@@ -166,9 +166,9 @@ ${$e}`),m+=$e.length}catch{}}}let Ja=rn.length>0?rn.join(`
|
|
|
166
166
|
|
|
167
167
|
`)||void 0,ht={channel:y,chatId:I,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:tn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ce||Ge||Sa(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ce?void 0:Oa||void 0,procedureContext:[ps,as].filter(Boolean).join(`
|
|
168
168
|
|
|
169
|
-
`)||void 0,workflowRunContext:Pa,references:ms,skillInjection:gs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ws??gt,memoryContext:us||void 0,crossChatContext:hs||void 0,longMemoryRecall:ys||void 0,contextOnDemand:Ge&&!H?Pi(y,I):void 0,wikiContext:La,handoverNote:this.buildHandoverNote(e.agentId,y,I),watcherNote:(()=>{try{return this.runNote?.(rs)}catch{return}})(),rotationMemo:Ua,eventDigest:H?void 0:sg(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Lr(y,!H,d.def.richMessages);return g?ig(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.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:Js({tier:d.def.tier,channel:y,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 Is=Ks(d.def.tier,this.config.decisions.routing),Ts=yt?.downgraded?Promise.resolve(yt.model):!e.model&&Is&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
169
|
+
`)||void 0,workflowRunContext:Pa,references:ms,skillInjection:gs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ws??gt,memoryContext:us||void 0,crossChatContext:hs||void 0,longMemoryRecall:ys||void 0,contextOnDemand:Ge&&!H?Pi(y,I):void 0,wikiContext:La,handoverNote:this.buildHandoverNote(e.agentId,y,I),watcherNote:(()=>{try{return this.runNote?.(rs)}catch{return}})(),rotationMemo:Ua,eventDigest:H?void 0:sg(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Lr(y,!H,d.def.richMessages);return g?ig(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.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:Js({tier:d.def.tier,channel:y,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 Is=Ks(d.def.tier,this.config.decisions.routing),Ts=yt?.downgraded?Promise.resolve(yt.model):!e.model&&Is&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-U35SFPEI.js"),m=await q("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:Is}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ks=!1;Ts.then(()=>{ks=!0});let wt=ve.active&&ve.preprocess?await te("select-context",()=>Ma(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,ce?{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),za=cr(bt,{memory:ls,procedures:fs,wikiContext:wt.input.wikiContext}),an=(bt?.length??0)+(on?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:on?.length??0,message:e.message?.length??0},vs=mi(e.agentId,y,I);hi(vs,an,xt);let $s=yi(vs);$s&&this.log(`[${e.agentId}] ${$s}`),an>16e3&&this.log(`[${e.agentId}] large context for ${y}:${I}: ${an} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),ks||C("route-model");let As=await Ts,Cs=d.def.tier!=="claude-code"?void 0:ue?Ci():qe==="lean"?Ai(d.def.workspace,ut,void 0,y):Ri(d.def.workspace);qe==="lean"&&!ue&&!H&&this.log(`[${e.agentId}] session profile for ${y}: ${_i(qe,ut,y)}`);let Ms=d.def.tier==="claude-code"&&!H?zr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:P},g=>this.log(g)):void 0,Qa={...e,systemPromptAppend:on,...Cs?{claudeArgs:Cs}:{},...As?{model:As}:{}},re,Rs=Ji({agent:e.agentId,request:e.message,taskId:P,budgetMinutes:d.def.maxExecutionMinutes??20}),Xa=F,Ps=!1,dn=!0;F=g=>{if(Rs.observe(g),ae&&dn)for(let m of Rr(g))Mr(m.name,m.input)||(dn=!1);Xa?.(g)};try{let g=this.workflowAutoRunner;if(fe&&g){let O=fe;try{let z=await q("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:y,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:y,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:z.runId,workflowMatchConfidence:fe.confidence}},re}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ae&&ke)try{let O=_r(ke,e.resumedFrom);Pr(ke,{runId:ae,agentId:e.agentId,channel:y,chatId:I,message:e.message,taskId:P,...O?{continues:O}:{}}),Ps=!0,p.workflow={runId:ae,workflowId:kr}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;C("dispatch-gate");let O=d.def.persistentProcess?Et():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:y,chatId:I}),ye=!!H||z,le=[ei(ye),pi(ye,void 0,e.model||d.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){w.buffer=`[error] ${le.message}`;for(let Ya of w.subscribers)try{Ya(w.buffer)}catch{}}return Tt}oi();let Ke=fi();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},v=this.planCloudSession(d.def,e);if(v.route==="local"){let O=m();if(O)return d.errors++,re=O,O}let k=d.def.tier==="claude-code",B=k?t:(O,z)=>{O&&M(O),t&&t(O,z)},K=!1,Y=k?s:O=>{O&&(K?M(O):(M(`\u{1F4AD} ${O}`),K=!0)),s&&s(O)},$e=()=>{K&&(M(`
|
|
170
170
|
`),K=!1)},me=k?B:B?(O,z)=>{$e(),B(O,z)}:void 0,A=await q("agent",async()=>{if(v.route!=="local"){let O=await this.runCloudSession(d.def,e,v,P);if(O)return O;let z=m();if(z)return z}return Oo(d.def,Qa,this.providers,me,bt,H,F,S.signal,Y)},Vl);if(!A.error){let O=ag(d.def.toolUseRequired,R);if(O){let z=Array.from(R.entries()).map(([ye,It])=>`${ye}=${It}`).join(", ")||"none";A.error=`tool_required_not_called: ${O} (invoked: ${z})`,A.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}Ms&&Qr(Ms,{toolUses:R,eventsSeen:D,error:A.error,agentId:e.agentId},O=>this.log(O));let St=this.interruptedRuns.get(p.id);St&&(A.content="",A.error=St,A.errorKind="interrupted");let cn=St?void 0:this.stoppedRuns.get(p.id);cn&&(A.content="",A.error=cn,A.errorKind="stopped"),re=A;let he=A.usage?ar(A.usage):void 0;if(_=!0,V().emit("task:completed",{taskId:P,agentId:e.agentId,channel:y,chatId:I,durationMs:Date.now()-ss,error:A.error||void 0,errorKind:A.error?A.errorKind:void 0,interrupted:St?!0:void 0,stopped:cn?!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:A.numTurns,injectedContext:za,finalResponse:A.content||void 0,billedModel:A.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&(A.content||A.error)){let O=A.error?`[error] ${A.error}`:A.content;w.buffer=O;for(let z of w.subscribers)try{z(O)}catch{}}if(A.error)d.errors++,this.log(`[${e.agentId}] error: ${A.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,I,A.content),Qi({agent:e.agentId,channel:y,chatId:I,request:e.message,reply:A.content,taskId:P}),A.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,I,A.claudeSessionId),A.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,I,A.codexSessionId),A.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,I,A.opencodeSessionId),(A.claudeSessionId||A.codexSessionId||A.opencodeSessionId)&&A.usage&&this.sessions.recordTurnUsage(e.agentId,y,I,A.usage,A.contextTokens),A.usage){let le=A.contextTokens,Ke=(A.usage.inputTokens||0)+(A.usage.cacheReadTokens||0)+(A.usage.cacheCreateTokens||0);(le??Ke)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${I}: context=${le??"n/a"} tokens (cumulative turn total=${Ke}) \u2014 next turn will rotate`)}if(nr({channel:y,content:`User: ${e.message}`,responseLength:A.content.length}).capture){await is(ql);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:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
171
171
|
|
|
172
172
|
Agent: ${A.content}`,meta:ng(ee,e.context)})}catch{}sr(e.agentId,e.message,A.content,{channel:y,chatId:I,sender:tn},this.memoryStore).catch(()=>{}),zo(e.agentId,e.message,A.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=A.billedModel||e.model||d.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,A.duration||0,A.usage,e.message.length,A.content.length,!1,z,ye,It),this.log(`[${e.agentId}] completed in ${A.duration}ms`+(A.tokensUsed?` (${A.tokensUsed} tokens)`:"")+` ${L()}`)}return A}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Rt(g.message);return re={content:"",error:Pt(m),errorKind:m.kind},re}finally{if(Rs.stop(),Ps&&ae&&ke)try{let g=re?.usage,m=Er(ke,ae,{error:re?re.error||void 0:S.signal.aborted?_e(S.signal).message:"run ended before completion",canceled:Or(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:dn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}se(re),ts(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:Dr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=J(process.cwd(),We,this.safe(e.agentId),t);de(s)||Gl(s,{recursive:!0});let r=J(s,`${this.safe(e.id)}.json`);Jl(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=J(process.cwd(),We,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let f=J(a,l);if(de(f))try{for(let h of pe(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],b=parseInt(p,10);if(!Number.isFinite(b)||b<i||b>s)continue;let S=Math.floor((s-b)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=J(process.cwd(),We);if(!de(e))return 0;let t=0;for(let s of pe(e)){let r=J(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=J(r,i),c;try{c=pe(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(dt(J(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=tg){let t=J(process.cwd(),We);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of pe(t)){let i=J(t,o),a;try{a=pe(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Kl(J(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=J(process.cwd(),We,this.safe(e));if(!de(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=J(s,i),c;try{c=pe(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(dt(J(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=J(process.cwd(),We,this.safe(e));if(!de(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=J(s,i,`${r}.json`);if(de(a))try{return JSON.parse(dt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=Tr();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(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}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}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Ht(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let 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:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:Fs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!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}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=f=>{u||(u=!0,d(f))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{Xe(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}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 cg(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(`
|
|
173
173
|
`)}export{to as a,kg as b,so as c,md as d,ro as e,Ot as f,Lg as g,jg as h,Bg as i,Jg as j,Ht as k,Nd as l,Po as m,jd as n,Bd as o,Wd as p,Oo as q,jt as r,Bt as s,uc as t,Sp as u,Ip as v,Nn as w,V as x,Qo as y,xc as z,kc as A,Zo as B,Fp as C,Vo as D,si as E,ci as F,Vp as G,ui as H,Gt as I,rf as J,of as K,it as L,Mu as M,Ru as N,Pu as O,_u as P,Eu as Q,Wn as R,Qt as S,Nf as T,ra as U,at as V,oa as W,Wf as X,qf as Y,Gf as Z,Kf as _,Jf as $,zf as aa,Qf as ba,ul as ca,Xl as da,Yl as ea,ph as fa,fh as ga,ng as ha,sg as ia,og as ja,es as ka,Ta as la,ka as ma,ag as na,va as oa,$a as pa,cg as qa};
|
|
174
|
-
//# sourceMappingURL=chunk-
|
|
174
|
+
//# sourceMappingURL=chunk-Z7GEW2SR.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-OTENO5DS.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-NW4N67TU.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-A2N6ETK2.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,Ha as n,Ia as o,Ja as p,Ka as q,La as r,Ma as s,Na as t,Oa as u,Pa as v,Qa as w,Ra as x,Sa as y,Ua as z,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-
|
|
1
|
+
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,Ha as n,Ia as o,Ja as p,Ka as q,La as r,Ma as s,Na as t,Oa as u,Pa as v,Qa as w,Ra as x,Sa as y,Ua as z,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";z();export{a as INTEGRATION_KINDS,u as WIKI_CONTRIBUTE_JOB,v as WIKI_CONTRIBUTE_MERGE_JOB,x as WIKI_SUMMARIZE_JOB,o as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,s as crossFieldProblems,p as daemonConfigSchema,b as eventSubscriptionSchema,q as expandEnvVars,d as isCronExpression,r as loadDaemonConfig,l as membersConfigSchema,g as mergePolicyConfigSchema,k as peopleConfigSchema,j as personSchema,n as qualityReportConfigSchema,m as requestStatusConfigSchema,i as requestsConfigSchema,f as reviewGateConfigSchema,t as validateWorkspaces,h as watchersConfigSchema,w as withContributionJobs,y as withSummariesJob};
|
|
2
|
+
//# sourceMappingURL=config-2QM2WTI2.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-mutate-
|
|
1
|
+
import{a,b}from"./chunk-6QFDFYI7.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-UJS4F7BT.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-E7LPZAXP.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-VWR3SMD3.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-
|
|
1
|
+
import{a as ee}from"./chunk-S22IBRY6.js";import"./chunk-5IHUZVPU.js";import{f as Q,k as V}from"./chunk-5TTHN7DP.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-6TJNWUMA.js";import"./chunk-SKSYII3K.js";import"./chunk-EIY2HRAS.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-OWMKQ4HZ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
3
|
${k.join(`
|
|
4
4
|
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
|
|
|
54
54
|
`).replace(/\n{3,}/g,`
|
|
55
55
|
|
|
56
56
|
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
-
//# sourceMappingURL=contributions-
|
|
57
|
+
//# sourceMappingURL=contributions-43FWZOGF.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g}from"./chunk-P34VSROA.js";import"./chunk-WGPMUWX7.js";import"./chunk-IMLAPB7G.js";import"./chunk-A76PNG4E.js";import"./chunk-MNG2AMKZ.js";import"./chunk-KP7KDLZ2.js";import"./chunk-JXF54PT7.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{g as daemonVoiceCheck,b as doctor,a as runDoctorChecks,e as runMirrorChecks,d as runNativeChecks,c as runNotificationChecks,f as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-IN6MWP6I.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-GRI5HOPC.js";import"./chunk-RKPAVWXF.js";import"./chunk-5QXRPYOY.js";import{b as I}from"./chunk-PYHR4HXO.js";import"./chunk-KP7KDLZ2.js";import"./chunk-6YNRLI6I.js";import"./chunk-E7LPZAXP.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
|
|
2
2
|
`)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
3
|
`)).join(`
|
|
4
4
|
`):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
5
|
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
|
|
6
6
|
`):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
7
|
-
//# sourceMappingURL=follow-up-tool-
|
|
7
|
+
//# sourceMappingURL=follow-up-tool-VB7K6HCL.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=grants-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-JOHDOEZ4.js";import"./chunk-A76PNG4E.js";import"./chunk-MNG2AMKZ.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_GRANT_DAYS,a as GUEST_SCOPE_PREFIX,b as JOIN_CARD_BY,h as JOIN_FAILED,d as MAX_GRANT_DAYS,j as NO_GRANT,l as PAUSED,k as WAITING_HOST,s as endGrant,o as grantBrief,u as grantForGuest,e as grantIdOf,n as guestAccess,p as guestTask,g as inviteGuest,i as joinGuest,f as newGrantId,q as pauseGrant,r as resumeGrant,m as settleGrant,t as updateGrant};
|
|
2
|
+
//# sourceMappingURL=grants-2S33F2LV.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=hub-
|
|
1
|
+
import{a}from"./chunk-2MW32M2D.js";import"./chunk-DWOERPBG.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-EIY2HRAS.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWMKQ4HZ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
|
|
2
|
+
//# sourceMappingURL=hub-JNNNUAZM.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -6534,7 +6534,30 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
6534
6534
|
include?: ("card" | "request")[] | undefined;
|
|
6535
6535
|
answerUrl?: string | undefined;
|
|
6536
6536
|
}>>;
|
|
6537
|
+
/** The mesh peer that has the owner's notes app, for a node without
|
|
6538
|
+
* one. Unset: approvals.forwardTo. */
|
|
6539
|
+
forwardTo: z.ZodOptional<z.ZodString>;
|
|
6540
|
+
/** Ideas to the owner's notes app (agentx_note, src/native/notes-api.ts).
|
|
6541
|
+
* Off by default. */
|
|
6542
|
+
notes: z.ZodDefault<z.ZodObject<{
|
|
6543
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
6544
|
+
folder: z.ZodDefault<z.ZodString>;
|
|
6545
|
+
perAgentPerDay: z.ZodDefault<z.ZodNumber>;
|
|
6546
|
+
}, "strip", z.ZodTypeAny, {
|
|
6547
|
+
enabled: boolean;
|
|
6548
|
+
folder: string;
|
|
6549
|
+
perAgentPerDay: number;
|
|
6550
|
+
}, {
|
|
6551
|
+
enabled?: boolean | undefined;
|
|
6552
|
+
folder?: string | undefined;
|
|
6553
|
+
perAgentPerDay?: number | undefined;
|
|
6554
|
+
}>>;
|
|
6537
6555
|
}, "strip", z.ZodTypeAny, {
|
|
6556
|
+
notes: {
|
|
6557
|
+
enabled: boolean;
|
|
6558
|
+
folder: string;
|
|
6559
|
+
perAgentPerDay: number;
|
|
6560
|
+
};
|
|
6538
6561
|
adapter: "auto" | "none";
|
|
6539
6562
|
mirror: {
|
|
6540
6563
|
enabled: boolean;
|
|
@@ -6543,7 +6566,14 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
6543
6566
|
include: ("card" | "request")[];
|
|
6544
6567
|
answerUrl?: string | undefined;
|
|
6545
6568
|
};
|
|
6569
|
+
forwardTo?: string | undefined;
|
|
6546
6570
|
}, {
|
|
6571
|
+
notes?: {
|
|
6572
|
+
enabled?: boolean | undefined;
|
|
6573
|
+
folder?: string | undefined;
|
|
6574
|
+
perAgentPerDay?: number | undefined;
|
|
6575
|
+
} | undefined;
|
|
6576
|
+
forwardTo?: string | undefined;
|
|
6547
6577
|
adapter?: "auto" | "none" | undefined;
|
|
6548
6578
|
mirror?: {
|
|
6549
6579
|
enabled?: boolean | undefined;
|
|
@@ -9568,6 +9598,11 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
9568
9598
|
lookbackHours: number;
|
|
9569
9599
|
};
|
|
9570
9600
|
native: {
|
|
9601
|
+
notes: {
|
|
9602
|
+
enabled: boolean;
|
|
9603
|
+
folder: string;
|
|
9604
|
+
perAgentPerDay: number;
|
|
9605
|
+
};
|
|
9571
9606
|
adapter: "auto" | "none";
|
|
9572
9607
|
mirror: {
|
|
9573
9608
|
enabled: boolean;
|
|
@@ -9576,6 +9611,7 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
9576
9611
|
include: ("card" | "request")[];
|
|
9577
9612
|
answerUrl?: string | undefined;
|
|
9578
9613
|
};
|
|
9614
|
+
forwardTo?: string | undefined;
|
|
9579
9615
|
};
|
|
9580
9616
|
meshVoices: Record<string, {
|
|
9581
9617
|
system?: string | Record<string, string> | undefined;
|
|
@@ -10713,6 +10749,12 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
10713
10749
|
lookbackHours?: number | undefined;
|
|
10714
10750
|
} | undefined;
|
|
10715
10751
|
native?: {
|
|
10752
|
+
notes?: {
|
|
10753
|
+
enabled?: boolean | undefined;
|
|
10754
|
+
folder?: string | undefined;
|
|
10755
|
+
perAgentPerDay?: number | undefined;
|
|
10756
|
+
} | undefined;
|
|
10757
|
+
forwardTo?: string | undefined;
|
|
10716
10758
|
adapter?: "auto" | "none" | undefined;
|
|
10717
10759
|
mirror?: {
|
|
10718
10760
|
enabled?: boolean | undefined;
|
|
@@ -11819,6 +11861,8 @@ declare class AgentXDaemon {
|
|
|
11819
11861
|
* advertises. Undefined for a name that is no peer of this node. */
|
|
11820
11862
|
private approvalsPeer;
|
|
11821
11863
|
private forwardToWarned?;
|
|
11864
|
+
/** A note for the owner's notes app, sent to the peer that has it. */
|
|
11865
|
+
private forwardNote;
|
|
11822
11866
|
/** Where this node's cards go when `approvals.forwardTo` is set: the
|
|
11823
11867
|
* named peer, or undefined (with one log line per name) when the name
|
|
11824
11868
|
* is no peer, so cards stay here rather than vanish. */
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ba as Tt,Ca as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-XNS5OQ3U.js";import"./chunk-QZ6VBDMX.js";import"./chunk-GTJIKXDB.js";import"./chunk-ATCIRFH6.js";import"./chunk-WGPMUWX7.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-JOHDOEZ4.js";import"./chunk-A76PNG4E.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-IGA3T3ZT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMGB23H5.js";import"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-MNG2AMKZ.js";import"./chunk-X7UQY7CH.js";import"./chunk-5QXRPYOY.js";import"./chunk-PYHR4HXO.js";import"./chunk-KP7KDLZ2.js";import"./chunk-A5GYG56I.js";import{m as lt,n as ct,o as dt,p as mt,pa as yt,q as pt}from"./chunk-Z7GEW2SR.js";import"./chunk-BZ6Y264Z.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-NMYC5RW7.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5TTHN7DP.js";import{s as ut}from"./chunk-6YNRLI6I.js";import"./chunk-E7LPZAXP.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-2MW32M2D.js";import{a as ht}from"./chunk-DWOERPBG.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-6TJNWUMA.js";import"./chunk-SKSYII3K.js";import{f as gt,g as ft}from"./chunk-EIY2HRAS.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-GMMRBTLQ.js";import{j as it,k as rt,l as at}from"./chunk-OWMKQ4HZ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Ja as tt,La as st,Na as ot,Ua as nt}from"./chunk-PXKIPU27.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|