agentix-cli 0.125.1 → 0.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/absorb-eval-5Y5IZWW2.js +2 -0
  2. package/dist/{agent-YJFWFQ6A.js → agent-WJTYM5HR.js} +2 -2
  3. package/dist/{board-dashboard-SPYYHH54.js → board-dashboard-SWJBBMTN.js} +2 -2
  4. package/dist/{board-dashboard-SPYYHH54.js.map → board-dashboard-SWJBBMTN.js.map} +1 -1
  5. package/dist/{chunk-NW7RVE57.js → chunk-2C3X6DVD.js} +2 -2
  6. package/dist/chunk-2W3X6H7Z.js +51 -0
  7. package/dist/chunk-2W3X6H7Z.js.map +1 -0
  8. package/dist/chunk-3PGPN323.js +2 -0
  9. package/dist/chunk-3PGPN323.js.map +1 -0
  10. package/dist/{chunk-CECHWYJ2.js → chunk-4VVHGR7H.js} +1 -1
  11. package/dist/chunk-4VVHGR7H.js.map +1 -0
  12. package/dist/{chunk-UOAJWNRF.js → chunk-D6SWAB5J.js} +6 -6
  13. package/dist/chunk-EO4DEEXL.js +2 -0
  14. package/dist/chunk-EO4DEEXL.js.map +1 -0
  15. package/dist/{chunk-INLKJEEN.js → chunk-FVG2BADS.js} +2 -2
  16. package/dist/{chunk-IS4DA5CR.js → chunk-GAIF3644.js} +4 -4
  17. package/dist/chunk-GAIF3644.js.map +1 -0
  18. package/dist/{chunk-YKYMGIQ5.js → chunk-GUQDPA6R.js} +2 -2
  19. package/dist/{chunk-5RE2B5YQ.js → chunk-JIXNSA67.js} +2 -2
  20. package/dist/{chunk-BN5QMNON.js → chunk-JUIL2EW3.js} +2 -2
  21. package/dist/{chunk-ITATBKUL.js → chunk-LVV7JBHM.js} +2 -2
  22. package/dist/{chunk-FX3D7YON.js → chunk-MCI3DIWW.js} +2 -2
  23. package/dist/{chunk-4WKBK7EQ.js → chunk-O4XEQTEN.js} +2 -2
  24. package/dist/chunk-QX2B4TJU.js +3 -0
  25. package/dist/chunk-QX2B4TJU.js.map +1 -0
  26. package/dist/chunk-USPFUUS3.js +894 -0
  27. package/dist/chunk-USPFUUS3.js.map +1 -0
  28. package/dist/{chunk-VHT7HESZ.js → chunk-VXKNB4AW.js} +2 -2
  29. package/dist/{chunk-5VWOK3GQ.js → chunk-WUDVBPQV.js} +2 -2
  30. package/dist/{chunk-WX47PYHL.js → chunk-YNA5T43U.js} +2 -2
  31. package/dist/chunk-ZQWWMAMJ.js +105 -0
  32. package/dist/chunk-ZQWWMAMJ.js.map +1 -0
  33. package/dist/cli.js +1 -1
  34. package/dist/{context-planner-BKHPKDX5.js → context-planner-3JDA7FNR.js} +2 -2
  35. package/dist/extract-json-7775Q7KO.js +2 -0
  36. package/dist/graph-5ZJ7YACP.js +2 -0
  37. package/dist/hub-53YQQCVA.js +2 -0
  38. package/dist/index.d.ts +45 -1
  39. package/dist/index.js +1 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/load-NK3MIYXP.js +2 -0
  42. package/dist/{program-JNRKGK3U.js → program-WFH65P5R.js} +260 -271
  43. package/dist/program-WFH65P5R.js.map +1 -0
  44. package/dist/promote-MQYJMGGZ.js +2 -0
  45. package/dist/push-bridge-325SXDGN.js +1 -1
  46. package/dist/{query-RV6SHTRN.js → query-DNJONEKC.js} +2 -2
  47. package/dist/registry-5A3SLBVJ.js +2 -0
  48. package/dist/registry-5A3SLBVJ.js.map +1 -0
  49. package/dist/{request-planner-2G73AJ4S.js → request-planner-XYHM26CO.js} +2 -2
  50. package/dist/{review-candidates-S34UICQD.js → review-candidates-XRBAMRBH.js} +2 -2
  51. package/dist/{routing-K2LAUFRL.js → routing-OMIWZKNC.js} +2 -2
  52. package/dist/routing-OMIWZKNC.js.map +1 -0
  53. package/dist/{seat-ZJT5T2NO.js → seat-LKBZ6SDS.js} +2 -2
  54. package/dist/seat-LKBZ6SDS.js.map +1 -0
  55. package/dist/{select-Y23SKHCJ.js → select-BSC3TFMZ.js} +2 -2
  56. package/dist/types-ROL44T62.js +2 -0
  57. package/dist/types-ROL44T62.js.map +1 -0
  58. package/dist/wiki-BT3H2WCD.js +2 -0
  59. package/dist/wiki-BT3H2WCD.js.map +1 -0
  60. package/package.json +1 -1
  61. package/dist/chunk-BFCNSZHN.js +0 -745
  62. package/dist/chunk-BFCNSZHN.js.map +0 -1
  63. package/dist/chunk-CECHWYJ2.js.map +0 -1
  64. package/dist/chunk-IS4DA5CR.js.map +0 -1
  65. package/dist/chunk-XSDUORMZ.js +0 -105
  66. package/dist/chunk-XSDUORMZ.js.map +0 -1
  67. package/dist/program-JNRKGK3U.js.map +0 -1
  68. package/dist/promote-GXZ7BLVG.js +0 -2
  69. package/dist/registry-PPJO5I6J.js +0 -2
  70. package/dist/types-NZOBHQGS.js +0 -2
  71. package/dist/wiki-WJM5XNFS.js +0 -2
  72. /package/dist/{agent-YJFWFQ6A.js.map → absorb-eval-5Y5IZWW2.js.map} +0 -0
  73. /package/dist/{promote-GXZ7BLVG.js.map → agent-WJTYM5HR.js.map} +0 -0
  74. /package/dist/{chunk-NW7RVE57.js.map → chunk-2C3X6DVD.js.map} +0 -0
  75. /package/dist/{chunk-UOAJWNRF.js.map → chunk-D6SWAB5J.js.map} +0 -0
  76. /package/dist/{chunk-INLKJEEN.js.map → chunk-FVG2BADS.js.map} +0 -0
  77. /package/dist/{chunk-YKYMGIQ5.js.map → chunk-GUQDPA6R.js.map} +0 -0
  78. /package/dist/{chunk-5RE2B5YQ.js.map → chunk-JIXNSA67.js.map} +0 -0
  79. /package/dist/{chunk-BN5QMNON.js.map → chunk-JUIL2EW3.js.map} +0 -0
  80. /package/dist/{chunk-ITATBKUL.js.map → chunk-LVV7JBHM.js.map} +0 -0
  81. /package/dist/{chunk-FX3D7YON.js.map → chunk-MCI3DIWW.js.map} +0 -0
  82. /package/dist/{chunk-4WKBK7EQ.js.map → chunk-O4XEQTEN.js.map} +0 -0
  83. /package/dist/{chunk-VHT7HESZ.js.map → chunk-VXKNB4AW.js.map} +0 -0
  84. /package/dist/{chunk-5VWOK3GQ.js.map → chunk-WUDVBPQV.js.map} +0 -0
  85. /package/dist/{chunk-WX47PYHL.js.map → chunk-YNA5T43U.js.map} +0 -0
  86. /package/dist/{context-planner-BKHPKDX5.js.map → context-planner-3JDA7FNR.js.map} +0 -0
  87. /package/dist/{query-RV6SHTRN.js.map → extract-json-7775Q7KO.js.map} +0 -0
  88. /package/dist/{registry-PPJO5I6J.js.map → graph-5ZJ7YACP.js.map} +0 -0
  89. /package/dist/{routing-K2LAUFRL.js.map → hub-53YQQCVA.js.map} +0 -0
  90. /package/dist/{seat-ZJT5T2NO.js.map → load-NK3MIYXP.js.map} +0 -0
  91. /package/dist/{types-NZOBHQGS.js.map → promote-MQYJMGGZ.js.map} +0 -0
  92. /package/dist/{wiki-WJM5XNFS.js.map → query-DNJONEKC.js.map} +0 -0
  93. /package/dist/{request-planner-2G73AJ4S.js.map → request-planner-XYHM26CO.js.map} +0 -0
  94. /package/dist/{review-candidates-S34UICQD.js.map → review-candidates-XRBAMRBH.js.map} +0 -0
  95. /package/dist/{select-Y23SKHCJ.js.map → select-BSC3TFMZ.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{F as rr,K as or,M as ir,a as js,b as qs,d as Gs,f as Ue,l as en,s as tn,u as sr}from"./chunk-ITATBKUL.js";import{a as Bs}from"./chunk-GLQLCBJS.js";import{b as Ws}from"./chunk-6W74CHNW.js";import{a as nr}from"./chunk-W4YR2RO2.js";import{b as Js,c as Zt,d as zs,e as Xs,h as Ys}from"./chunk-5DFUUYEA.js";import{a as Fs}from"./chunk-WX47PYHL.js";import{e as Us,f as Hs}from"./chunk-36AXN6ZB.js";import{a as Yt,b as Ks}from"./chunk-J3SOEFRE.js";import{a as Vt,b as Qs}from"./chunk-SIU6STB2.js";import{e as Vs,i as Zs,j as er,k as tr}from"./chunk-X5C5W3E4.js";import{c as ks,f as As}from"./chunk-INLKJEEN.js";import{a as $s,c as Cs}from"./chunk-MYVHVJWZ.js";import{a as Ms,b as Ps,c as _s,d as Rs,l as Es}from"./chunk-AV7T3SYT.js";import{a as Ds,b as Os}from"./chunk-Y5MFVVTM.js";import{g as Ns,h as Ls}from"./chunk-VHT7HESZ.js";import{a as ke,d as ye}from"./chunk-56KNKUFF.js";import{s as Ts,v as pt,w as vs,y as ue,z as Xt}from"./chunk-BN5QMNON.js";import{a as Fe,b as ve,f as gt}from"./chunk-72SZI2UW.js";import{a as Te,b as Gt}from"./chunk-FCPTN6NF.js";import{c as ls,d as gs}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{D as hs,F as Qt,H as sa,K as ys,O as ra,U as ws,V as zt,W as bs,X as Le,Y as xs,Z as Ss,da as Is,ra as oa}from"./chunk-46JKX6CT.js";import{f as Jt,n as na}from"./chunk-UIBUZ2N3.js";import{g as lt,h as ta}from"./chunk-BRK6M6LA.js";import{a as ps,b as ie,c as fs,d as ms,e as Kt}from"./chunk-2QNT5JDS.js";Xt();gt();var ft="tool-set",ar=["answer","code","full"],dr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ia=.1;function ur(n){return{task:cr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:cr(n.agentPrompt,600)}:{}}}var lr={bundle:ve({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 gr(n,e=ia){let s=n?.bundle?.probabilities;if(!s)return"full";let r=nn(s.answer),o=nn(s.code),i=nn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function pr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>dr.answer.includes(t))?"answer":e.every(t=>dr.code.includes(t))?"code":"full"}function fr(n,e){return ar.indexOf(n)<ar.indexOf(e)}function nn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function cr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var mr=!1;function hr(n,e){let t=pt(ft);if(t!=="off")return t==="active"&&!mr&&(mr=!0,e(`[decisions] seat "${ft}" is set to active, but only shadow is built: it records and changes nothing`)),ue(ft,ur(n),lr,{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=gr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function yr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=pr(r);vs(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}`+(fr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function aa(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function wr(n,e){let t=aa(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 sn(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)`}Xt();gt();var br="session-continuity",xr={continues:Fe("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:Fe("Does the new request refer to something stated earlier in the conversation?")};function Sr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:rn(n.message,1200),previousRequest:n.previousMessage?rn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>rn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ir(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 rn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Tt}from"execa";import{spawn as da}from"node:child_process";import{createHash as ca}from"node:crypto";import{createInterface as ua}from"node:readline";var le=class extends Error{},la=n=>da("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),on=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(),ua({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)+`
1
+ import{F as rr,K as or,M as ir,a as js,b as qs,d as Gs,f as Ue,l as en,s as tn,u as sr}from"./chunk-LVV7JBHM.js";import{a as Bs}from"./chunk-GLQLCBJS.js";import{b as Ws}from"./chunk-6W74CHNW.js";import{e as Vs,i as Zs,j as er,k as tr}from"./chunk-X5C5W3E4.js";import{a as nr}from"./chunk-W4YR2RO2.js";import{b as Js,c as Zt,d as zs,e as Xs,h as Ys}from"./chunk-5DFUUYEA.js";import{a as Fs}from"./chunk-YNA5T43U.js";import{a as ke,d as ye}from"./chunk-56KNKUFF.js";import{g as Ns,h as Ls}from"./chunk-VXKNB4AW.js";import{e as Us,f as Hs}from"./chunk-36AXN6ZB.js";import{a as Yt,b as Ks}from"./chunk-J3SOEFRE.js";import{a as Vt,b as Qs}from"./chunk-SIU6STB2.js";import{c as ks,f as As}from"./chunk-FVG2BADS.js";import{s as Ts,v as pt,w as vs,y as ue,z as Xt}from"./chunk-JUIL2EW3.js";import{a as Fe,b as ve,f as gt}from"./chunk-72SZI2UW.js";import{a as Te,b as Gt}from"./chunk-FCPTN6NF.js";import{a as $s,c as Cs}from"./chunk-MYVHVJWZ.js";import{a as Ms,b as Ps,c as _s,d as Rs,l as Es}from"./chunk-AV7T3SYT.js";import{a as Ds,b as Os}from"./chunk-Y5MFVVTM.js";import{c as ls,d as gs}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{D as hs,F as Qt,H as sa,K as ys,O as ra,U as ws,V as zt,W as bs,X as Le,Y as xs,Z as Ss,da as Is,ra as oa}from"./chunk-46JKX6CT.js";import{f as Jt,n as na}from"./chunk-UIBUZ2N3.js";import{g as lt,h as ta}from"./chunk-BRK6M6LA.js";import{a as ps,b as ie,c as fs,d as ms,e as Kt}from"./chunk-2QNT5JDS.js";Xt();gt();var ft="tool-set",ar=["answer","code","full"],dr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ia=.1;function ur(n){return{task:cr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:cr(n.agentPrompt,600)}:{}}}var lr={bundle:ve({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 gr(n,e=ia){let s=n?.bundle?.probabilities;if(!s)return"full";let r=nn(s.answer),o=nn(s.code),i=nn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function pr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>dr.answer.includes(t))?"answer":e.every(t=>dr.code.includes(t))?"code":"full"}function fr(n,e){return ar.indexOf(n)<ar.indexOf(e)}function nn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function cr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var mr=!1;function hr(n,e){let t=pt(ft);if(t!=="off")return t==="active"&&!mr&&(mr=!0,e(`[decisions] seat "${ft}" is set to active, but only shadow is built: it records and changes nothing`)),ue(ft,ur(n),lr,{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=gr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function yr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=pr(r);vs(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}`+(fr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function aa(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function wr(n,e){let t=aa(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 sn(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)`}Xt();gt();var br="session-continuity",xr={continues:Fe("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:Fe("Does the new request refer to something stated earlier in the conversation?")};function Sr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:rn(n.message,1200),previousRequest:n.previousMessage?rn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>rn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ir(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 rn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Tt}from"execa";import{spawn as da}from"node:child_process";import{createHash as ca}from"node:crypto";import{createInterface as ua}from"node:readline";var le=class extends Error{},la=n=>da("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),on=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(),ua({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()}},an=class{constructor(e=la,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=ca("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[R])=>b.localeCompare(R))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new le("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 b=[...this.entries].find(([,R])=>!R.connection.busy);if(!b)throw new le("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:s,connection:new on(e,this.launchProcess)}}catch{throw new le("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 I=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let E=new Promise((O,P)=>{i.failTurn=P,i.notify=(D,L)=>{if(L?.threadId!==u)return;let F=L.item,j={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...L,type:D.replace("/","."),...F?{item:{...F,type:j[F.type]||F.type}}:{}}),D==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(d=F.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=L.delta,e.onDelta?.(L.delta,c)),D==="thread/tokenUsage/updated"){let H=L.tokenUsage.last;f=H.inputTokens;let W=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-W),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+W,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(L.turn.status==="completed"?O():P(new Error(L.turn.error?.message||`Codex turn ${L.turn.status}`)))}});return E.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await E,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:f,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new le(b.message);return{content:c,codexSessionId:u,usage:l,contextTokens:f,error:b.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(I),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())}}},Tr=new an;import{execFile as Ra}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as Br,readFileSync as jr,rmSync as qr}from"fs";import{join as St}from"path";import{tmpdir as Wr}from"os";function mt(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 ht(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function yt(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 vr=null;function wt(){return vr}function Gu(n){vr=n}function He(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function ga(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 Ae=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},kr=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=He(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=ga(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 Ae(`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 Ae(`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=He(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=He(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=He(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=He(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,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 pa}from"child_process";import{randomUUID as fa}from"crypto";import{existsSync as ma,readFileSync as ha}from"fs";import{resolve as ya}from"path";function wa(n){let e=ya(n,"CLAUDE.md");if(!ma(e))return null;try{let t=ha(e,"utf8");return Es(t)}catch{return null}}var ba=20*60*1e3,xa=5e3,Be=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},je=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Sa(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 Ar=class{constructor(e={}){this.opts=e}spawn(e,t){return new dn(e,t,this.opts)}},dn=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=pa(r,o,{cwd:t.workspace,env:ye(Sa({...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:wa(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=fa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??ba,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Be(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 je(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 I=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${I.length} chars): ${I.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)},xa);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"}}};Kt();na();Gt();import{resolve as $r,join as Cr}from"path";var Ia=4e3;function bt(n){try{let e=Cr($r(n.root),".agentx","db.sqlite"),t=Jt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Te(),r=n.input.command?n.input.command.slice(0,Ia):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${n}`}function Da(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
27
27
  `,l)}};O.stdout?.on("data",T=>{F+=H.write(T);let w=F.split(`
28
28
  `);F=w.pop()||"";for(let _ of w)G(_)}),O.stderr?.on("data",T=>{j+=W.write(T)});let $=await O;if(i&&i.removeEventListener("abort",L),F+=H.end(),F.trim()&&G(F),j+=W.end(),P)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,w;return T.timedOut?w=`OpenCode timed out after ${Math.round(R/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?w=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+j)?w=Fr():w=j.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...X(w),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(R){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(R?.message||"")?Fr():R?.message;return{content:l,...X(E||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{b?.(),I?.release(A)}}async function Ga(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=pe(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:"",...X(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ka(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 A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}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 I=()=>({content:"",...X(`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 A=n.provider||"claude-code",b=s?`${s}
29
29
 
30
- ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-YJFWFQ6A.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-YJFWFQ6A.js"),j=await F(L),H=j.inputTokens,W=j.outputTokens;if((H===void 0||W===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),W=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||W!==void 0?{inputTokens:H||0,outputTokens:W||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let 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 Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
30
+ ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-WJTYM5HR.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-WJTYM5HR.js"),j=await F(L),H=j.inputTokens,W=j.outputTokens;if((H===void 0||W===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),W=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||W!==void 0?{inputTokens:H||0,outputTokens:W||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let 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 Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${$}`:$,F=$,!!T){L+=T;try{i(T,L)}catch{}}},H=!1,W=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?W():o.addEventListener("abort",W,{once:!0}));let G=!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(G=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let w=T.raw.message?.content??[];for(let S of w)S.type==="text"&&typeof S.text=="string"?(I=S.text,j(S.text)):S.type==="tool_use"&&(F="");let _=T.raw.message?.usage;if(_){let S=(_.input_tokens||0)+(_.cache_read_input_tokens||0)+(_.cache_creation_input_tokens||0);S>0&&(E=S)}}if(T.type==="result"){let w=T.raw;if(w.is_error){let _=X(typeof w.result=="string"?w.result:"claude error");A=_.error,b=_.errorKind}else typeof w.result=="string"&&w.result.length>0&&(I=w.result,L||j(w.result));typeof w.session_id=="string"&&(D=w.session_id),w.usage&&(R={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(O=w.num_turns),typeof w.message?.model=="string"?P=w.message.model:typeof w.model=="string"?P=w.model:P=yt(w.modelUsage)||P}}}catch($){if(H)A="task cancelled by operator",b="cancelled";else if(G)if($ instanceof je)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,b="interrupted";else if($ instanceof Be){let T=X(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=T.error,b=T.errorKind}else{let T=X(`persistent claude process error: ${$?.message||String($)}`);A=T.error,b=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",W),null}finally{o&&o.removeEventListener("abort",W)}return H&&!A&&(A="task cancelled by operator",b="cancelled"),{content:H?"":I,error:A,errorKind:b,duration:Date.now()-c,usage:R,contextTokens:E,numTurns:O,billedModel:P,claudeSessionId:D}}function Zr(n){let e=ie(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?_r(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Nr(t.args,n.taskId,n.agentId)}function Xa(n){return ie(n.autonomy)||!!n.personLimits}async function Ya(n,e,t,s,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,c=a&&Rr(a,n.tier)||e.personLimits&&Lr(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?`${ms(a)}
@@ -134,9 +134,9 @@ ${wu}`:n==="codex-cli"?Ti:""}function vi(n,e){return e!=="claude-code"&&e!=="cod
134
134
  `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Dt(K(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Ot,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=Rn(t.context?.chatId),a=this.cloudSessionStore();return bi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Ot,...e.cloudSessions??{}},i=Date.now(),a=ye(Ge(ke(e.workspace),t),e.billing),c=await Ii({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>Si({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Y().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(d){i={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(c){let d=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=i.error?Ue(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Js().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=ie(e.autonomy),a=xs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:xo().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(x=>x.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}=kt(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,x=500;for(;d.activeTasks>=d.def.maxConcurrent;){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(M=>setTimeout(M,x))}}else if(u==="voice"){let g=Date.now(),m=25*6e4,x=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(x);){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(M=>setTimeout(M,500))}f=x,this.voiceClaims.add(x)}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 x=this.messageQueue.pendingCount(e.agentId,u,l);return Y().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Qt(e.context),humanRoot:lt(e.context),person:zt(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: ${x}) behind=${d.runningTasks.map(M=>M.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Gs(m,x)}}}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.queuedAt!==void 0){let g=lo(e.queuedAt);g&&(e.message=`${g}
135
135
  ${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}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let I=zt(this.config.people,e.context);if(e.context&&(I?e.context.person=I.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let A=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:A});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let R=g=>{if(g){b.buffer+=g,b.buffer.length>ki&&(b.buffer=b.buffer.slice(b.buffer.length-ki));for(let m of b.subscribers)try{m(g)}catch{}}},E=Te();e.taskId=E;let O=new Map,P=(g,m,x)=>{try{Y().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:x,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,L=!1,F=()=>{L||(L=!0,D&&P("first-event",D,"ok"))},j;if(t){let g=Mu();j=m=>{F();let x=g(m);if(x&&R(x),Ci(E,e.agentId,m),$i(O,m),In(m,void 0,e.model||d.def.model),r)try{r(m)}catch{}}}else j=g=>{if(F(),Ci(E,e.agentId,g),$i(O,g),In(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,W=H?setTimeout(()=>A.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;W?.unref?.();let G=(d.def.preSpawnTimeoutSec??Iu)*1e3,$=setTimeout(()=>{A.abort(new Error(`timed out before spawn after ${Math.round(G/1e3)}s in step "${p.step??"start"}"`))},G);$.unref?.();let T=()=>{$&&clearTimeout($),$=void 0},w=()=>`task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`,_;A.signal.addEventListener("abort",()=>{let g=Xe(A.signal).message;/^timed out/.test(g)&&(_=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let S=g=>{p.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},v=(g,m,x=0)=>{if(A.signal.aborted)return Promise.reject(Xe(A.signal));S(g),(g==="agent"||g==="workflow-auto-run")&&(T(),D=Date.now());let M=Date.now(),q=wi(m(),yu[g]??0,g);return yi(q,A.signal,x).then(B=>(P(g,M,"ok"),B),B=>{throw P(g,M,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},J=async(g,m,x,M=0)=>{try{return await v(g,m,M)}catch(q){if(q instanceof Re)return x();throw q}},Dn=!1,On=g=>{if(Dn)return;Dn=!0,this.runReleases.delete(p.id),W&&clearTimeout(W),T(),d.activeTasks--;let m=d.runningTasks.findIndex(x=>x.id===p.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let x of b.subscribers)try{x(`
136
136
  [task finished]
137
- `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),xu).unref?.();try{let x=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:x.toISOString(),durationMs:x.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let q=(M.responseText||M.error||"").trim();if(q){let B=q.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:x,ok:M.ok})}}catch(x){this.log(`[${e.agentId}] task history persist failed: ${x?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(x=>{if(x.length===0)return;this.log(`[${e.agentId}] flushing ${x.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:x.length,at:new Date().toISOString()});let q=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let B of x){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then(te=>(Ue(te.error)||q(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw q(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(x=>{Y().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: ${x.message}`)})};this.runReleases.set(p.id,On),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:_i,selectRequestContext:Ri}=await import("./request-planner-2G73AJ4S.js"),Nn=J("request-gate",()=>_i(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Nt=!1;Nn.then(()=>{Nt=!0},()=>{Nt=!0});let k=l,Lt=e.context?.sender||"User",se=d.def.tier==="codex-cli",De=Wo(this.config.session,y,d.def.tier),Ze=Go(this.config.session),Oe=De==="lean"&&Ze.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,k),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${k}`),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}));let et=this.sessions.sessionIdleMs(e.agentId,y,k);e.freshSession||await J("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,k,e.seedHistory),()=>{});let Ei=[...this.sessions.getSession(e.agentId,y,k).messages].reverse().find(g=>g.role==="agent")?.content;hi({agent:e.agentId,channel:y,chatId:k,message:e.message,previousReply:Ei,taskId:E}),this.sessions.addUserMessage(e.agentId,y,k,Lt,e.message);let Ln=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:y,chatId:k,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ln).toISOString(),taskId:E,resumeOrigin:co(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Qt(e.context),...I?{person:I}:{},humanRoot:lt(e.context),pickup:hs(e.context),operator:ys(e.context)});let V,Ft,Fn=this.classifier;if(Fn&&y!=="a2a"&&!se){S("classify");let g=Date.now();Ft=Fn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:k,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(p.intentPath=V.path.slice()),P("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),P("classify",g,"error")})}let Un=async g=>{if(!Ft)return;let m;await Promise.race([Ft,new Promise(x=>{m=setTimeout(x,g),m.unref?.()})]),m&&clearTimeout(m)};await Un(gu);let Se=this.config.workflows?.matching,Ie,Hn,Bn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Bn?.enabled&&(Bn.agents[e.agentId]??!0)&&!i&&lt(e.context))try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=(Se?.suggestThreshold??.65)&&(Hn=sr(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Se.mode} reasons=${m.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&m.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?Ie={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 Di=this.wikiHub.getAgentWiki(e.agentId),jn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),qn=this.memoryStore.buildContext(jn),Wn=this.memoryStore.contextFacts(jn),Oi=this.patternStore.findRelevant(e.message,e.agentId,5),Ni=this.patternStore.buildContext(Oi),Gn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),x=await v("skills",()=>g(d.def.workspace)),M=e.personLimits?.skills??[],q=M.length?x.filter(B=>!M.some(ee=>Le(ee,B.frontmatter.name))):x;Gn=m(q,e.message)}catch{}let N=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,k):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,k):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,k):void 0;if(N&&this.sessions.isSessionStale(e.agentId,y,k,et)&&(this.log(`[${e.agentId}] session stale for ${y}:${k}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}),N=void 0),N&&this.sessions.shouldRotateByTierTwo(e.agentId,y,k)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,k);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${k} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),N=void 0}if(N&&this.sessions.shouldRotateByTurns(e.agentId,y,k)){let g=this.sessions.getTurnCount(e.agentId,y,k);this.log(`[${e.agentId}] max-turns rotation for ${y}:${k} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"max-turns",at:new Date().toISOString()}),N=void 0}if(N&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=wr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,k),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,k),idleMs:et??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${k}: ${sn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"cost");let x=this.sessions.getLastTurnInputTokens(e.agentId,y,k);this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"cost",lastTurnInputTokens:x,at:new Date().toISOString()}),N=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${k}: would ${sn(m)}`)}}if(N&&d.def.tier==="claude-code"){let g=N;await J("rotate",()=>this.maybeRotateForContinuity(e,d,y,k,g),()=>!1)&&(N=void 0)}try{let g=await v("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,k,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",x=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${k} (quality: ${m}%, ${x} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let M=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${M.overallScore} (lexicon=${M.lexiconDecay}, tools=${M.toolShift}, semantic=${M.semanticDrift})`),M.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${M.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Li=process.env.AGENTX_CONTEXT_SURGERY==="1",Fi=se?{maxMessages:8,maxChars:2400}:Li&&vi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ui=!N&&!se?Au(Di,e.agentId):void 0,tt=!N&&!Oe?this.sessions.buildHistoryContext(e.agentId,y,k,Fi):void 0,Hi=N?void 0:this.sessions.getRotationMemo(e.agentId,y,k)??void 0,Kn,Jn=[];if(this.config.procedures?.injection?.enabled&&!N&&!se)try{let g=new ze({baseDir:K(process.cwd(),this.config.procedures.dir)}),m=An(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Kn=$n(m),Jn=m.map(x=>({id:x.procedure.meta.id,title:x.procedure.meta.title}));for(let x of m)this.log(`[${e.agentId}] procedure match ${x.procedure.meta.id} score=${x.score.toFixed(2)} (${x.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,y,k).messages,x=m[0],M=m[m.length-1],q=tt===void 0?`resume=${N?N.slice(0,8):"?"} (no rebuild)`:`fresh history=${tt.length}c/${tt.split(`
137
+ `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),xu).unref?.();try{let x=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:x.toISOString(),durationMs:x.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let q=(M.responseText||M.error||"").trim();if(q){let B=q.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:x,ok:M.ok})}}catch(x){this.log(`[${e.agentId}] task history persist failed: ${x?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(x=>{if(x.length===0)return;this.log(`[${e.agentId}] flushing ${x.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:x.length,at:new Date().toISOString()});let q=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let B of x){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then(te=>(Ue(te.error)||q(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw q(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(x=>{Y().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: ${x.message}`)})};this.runReleases.set(p.id,On),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:_i,selectRequestContext:Ri}=await import("./request-planner-XYHM26CO.js"),Nn=J("request-gate",()=>_i(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Nt=!1;Nn.then(()=>{Nt=!0},()=>{Nt=!0});let k=l,Lt=e.context?.sender||"User",se=d.def.tier==="codex-cli",De=Wo(this.config.session,y,d.def.tier),Ze=Go(this.config.session),Oe=De==="lean"&&Ze.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,k),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${k}`),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}));let et=this.sessions.sessionIdleMs(e.agentId,y,k);e.freshSession||await J("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,k,e.seedHistory),()=>{});let Ei=[...this.sessions.getSession(e.agentId,y,k).messages].reverse().find(g=>g.role==="agent")?.content;hi({agent:e.agentId,channel:y,chatId:k,message:e.message,previousReply:Ei,taskId:E}),this.sessions.addUserMessage(e.agentId,y,k,Lt,e.message);let Ln=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:y,chatId:k,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ln).toISOString(),taskId:E,resumeOrigin:co(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Qt(e.context),...I?{person:I}:{},humanRoot:lt(e.context),pickup:hs(e.context),operator:ys(e.context)});let V,Ft,Fn=this.classifier;if(Fn&&y!=="a2a"&&!se){S("classify");let g=Date.now();Ft=Fn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:k,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(p.intentPath=V.path.slice()),P("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),P("classify",g,"error")})}let Un=async g=>{if(!Ft)return;let m;await Promise.race([Ft,new Promise(x=>{m=setTimeout(x,g),m.unref?.()})]),m&&clearTimeout(m)};await Un(gu);let Se=this.config.workflows?.matching,Ie,Hn,Bn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Bn?.enabled&&(Bn.agents[e.agentId]??!0)&&!i&&lt(e.context))try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=(Se?.suggestThreshold??.65)&&(Hn=sr(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Se.mode} reasons=${m.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&m.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?Ie={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 Di=this.wikiHub.getAgentWiki(e.agentId),jn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),qn=this.memoryStore.buildContext(jn),Wn=this.memoryStore.contextFacts(jn),Oi=this.patternStore.findRelevant(e.message,e.agentId,5),Ni=this.patternStore.buildContext(Oi),Gn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),x=await v("skills",()=>g(d.def.workspace)),M=e.personLimits?.skills??[],q=M.length?x.filter(B=>!M.some(ee=>Le(ee,B.frontmatter.name))):x;Gn=m(q,e.message)}catch{}let N=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,k):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,k):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,k):void 0;if(N&&this.sessions.isSessionStale(e.agentId,y,k,et)&&(this.log(`[${e.agentId}] session stale for ${y}:${k}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}),N=void 0),N&&this.sessions.shouldRotateByTierTwo(e.agentId,y,k)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,k);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${k} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),N=void 0}if(N&&this.sessions.shouldRotateByTurns(e.agentId,y,k)){let g=this.sessions.getTurnCount(e.agentId,y,k);this.log(`[${e.agentId}] max-turns rotation for ${y}:${k} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"max-turns",at:new Date().toISOString()}),N=void 0}if(N&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=wr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,k),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,k),idleMs:et??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${k}: ${sn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"cost");let x=this.sessions.getLastTurnInputTokens(e.agentId,y,k);this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"cost",lastTurnInputTokens:x,at:new Date().toISOString()}),N=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${k}: would ${sn(m)}`)}}if(N&&d.def.tier==="claude-code"){let g=N;await J("rotate",()=>this.maybeRotateForContinuity(e,d,y,k,g),()=>!1)&&(N=void 0)}try{let g=await v("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,k,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",x=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${k} (quality: ${m}%, ${x} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let M=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${M.overallScore} (lexicon=${M.lexiconDecay}, tools=${M.toolShift}, semantic=${M.semanticDrift})`),M.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${M.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Li=process.env.AGENTX_CONTEXT_SURGERY==="1",Fi=se?{maxMessages:8,maxChars:2400}:Li&&vi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ui=!N&&!se?Au(Di,e.agentId):void 0,tt=!N&&!Oe?this.sessions.buildHistoryContext(e.agentId,y,k,Fi):void 0,Hi=N?void 0:this.sessions.getRotationMemo(e.agentId,y,k)??void 0,Kn,Jn=[];if(this.config.procedures?.injection?.enabled&&!N&&!se)try{let g=new ze({baseDir:K(process.cwd(),this.config.procedures.dir)}),m=An(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Kn=$n(m),Jn=m.map(x=>({id:x.procedure.meta.id,title:x.procedure.meta.title}));for(let x of m)this.log(`[${e.agentId}] procedure match ${x.procedure.meta.id} score=${x.score.toFixed(2)} (${x.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,y,k).messages,x=m[0],M=m[m.length-1],q=tt===void 0?`resume=${N?N.slice(0,8):"?"} (no rebuild)`:`fresh history=${tt.length}c/${tt.split(`
138
138
  `).length}L`,B=`[${e.agentId}] ${y}:${k} ${q} | session.messages=${m.length}`+(m.length>0?` first=${x.timestamp.slice(11,19)}(${x.role}:${(x.content||"").slice(0,40).replace(/\n/g," ")}) last=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",B)}catch(g){he.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Qn;if(d.def.contextReferences&&!N)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[M,q]=await v("references",()=>Promise.all([Yt(d.def.workspace),Vt(d.def.workspace)]));if(M.byId.size===0&&q.recipes.length===0){let[B,ee]=await v("references",()=>Promise.all([Yt(process.cwd()),Vt(process.cwd())]));m={refs:B,recipes:ee}}else m={refs:M,recipes:q};this.referencesCache.set(g,m)}let x=Qs({agentId:e.agentId,intentTags:V?.path,message:e.message},m.recipes,m.refs);x.cards.length>0&&(Qn=Ks(x.cards,500*4)),x.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${x.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let zn=Oe?"":this.sessions.getCrossSessionSummary(e.agentId,y,k,e.message),Xn,nt=so(e.message);if(nt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:k,lookbackDays:nt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${nt.lookbackDays}d on this chat (cue-triggered)]`],x=[...g.turns].sort((M,q)=>M.ts.localeCompare(q.ts));for(let M of x){let q=M.ts.slice(11,16)+" "+M.day,B=M.role==="user"?M.senderName||"User":M.senderName||"Agent";m.push(`${q} ${B}: ${M.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]"),Xn=m.join(`
139
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${nt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Bi=se?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Yn,Vn,Zn=!1;Nt||S("request-gate");let me=await Nn;if(me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Bi==="planner"&&!me.active&&!Oe&&y!=="voice"&&y!=="desktop"){try{let{planContext:g}=await import("./context-planner-BKHPKDX5.js"),m=await v("plan-context",()=>g({agentId:e.agentId,channel:y,chatId:k,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Zn=!0,Yn=m.sessionHistory,qn=m.memoryContext,Wn=m.memoryFacts,zn=m.crossChatContext,Vn=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)`)}Zn&&N&&(this.sessions.clearClaudeSessionId(e.agentId,y,k),N=void 0)}let Ut=`${e.agentId}:${y}:${k}`,st=_s(e.message);st&&(st==="default"?(this.activeSouls.delete(Ut),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Ut,st),this.log(`[${e.agentId}] Soul switched to: ${st}`)));let ji=this.activeSouls.get(Ut),qi=Ms(d.def.workspace,ji),Wi=Ps(qi),Gi=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ki=bu(d.def.tier),Ji=Pu(d.def.richMessages,y),Qi=d.def.tier==="claude-code"&&(De!=="lean"||Ko(Ze)),es="";if(d.def.workspace&&!Qi){let g=K(d.def.workspace,"CLAUDE.md");if(ne(g))try{let m=Ye(g,"utf-8");es=`[Project CLAUDE.md]
139
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${nt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Bi=se?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Yn,Vn,Zn=!1;Nt||S("request-gate");let me=await Nn;if(me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Bi==="planner"&&!me.active&&!Oe&&y!=="voice"&&y!=="desktop"){try{let{planContext:g}=await import("./context-planner-3JDA7FNR.js"),m=await v("plan-context",()=>g({agentId:e.agentId,channel:y,chatId:k,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Zn=!0,Yn=m.sessionHistory,qn=m.memoryContext,Wn=m.memoryFacts,zn=m.crossChatContext,Vn=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)`)}Zn&&N&&(this.sessions.clearClaudeSessionId(e.agentId,y,k),N=void 0)}let Ut=`${e.agentId}:${y}:${k}`,st=_s(e.message);st&&(st==="default"?(this.activeSouls.delete(Ut),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Ut,st),this.log(`[${e.agentId}] Soul switched to: ${st}`)));let ji=this.activeSouls.get(Ut),qi=Ms(d.def.workspace,ji),Wi=Ps(qi),Gi=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ki=bu(d.def.tier),Ji=Pu(d.def.richMessages,y),Qi=d.def.tier==="claude-code"&&(De!=="lean"||Ko(Ze)),es="";if(d.def.workspace&&!Qi){let g=K(d.def.workspace,"CLAUDE.md");if(ne(g))try{let m=Ye(g,"utf-8");es=`[Project CLAUDE.md]
140
140
  ${m.length>4e3?m.slice(0,4e3)+`
141
141
 
142
142
  [CLAUDE.md truncated to 4KB]`:m}`}catch{}}let rt=e.context?.runbookPath,Ht=[];if(rt&&ne(rt)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],m=0,x=4e3,M=16e3;for(let q of g){if(m>=M)break;let B=K(rt,q);if(ne(B))try{let ee=Ye(B,"utf-8"),te=ee.length>x?ee.slice(0,x)+`
@@ -148,9 +148,9 @@ ${te}`),m+=te.length}catch{}}}let zi=Ht.length>0?Ht.join(`
148
148
 
149
149
  `)||void 0,jt={channel:y,chatId:k,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:Lt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||Oe||vi(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:se?void 0:Ni||void 0,procedureContext:[Kn,Hn].filter(Boolean).join(`
150
150
 
151
- `)||void 0,references:Qn,skillInjection:Gn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Yn??tt,memoryContext:qn||void 0,crossChatContext:zn||void 0,longMemoryRecall:Xn||void 0,contextOnDemand:Oe&&!N?Yo(y,k):void 0,wikiContext:Ui,handoverNote:this.buildHandoverNote(e.agentId,y,k),rotationMemo:Hi,eventDigest:N?void 0:ku(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=or(y,!N,d.def.richMessages);return g?$u(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},ot=e.model?void 0:As({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!N,sessionIdleMs:N?et:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let ts=ks(d.def.tier,this.config.decisions.routing),ns=ot?.downgraded?Promise.resolve(ot.model):!e.model&&ts&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-K2LAUFRL.js"),m=await v("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!N,sessionIdleMs:N?et:null,cheapModel:ts}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ss=!1;ns.then(()=>{ss=!0});let it=me.active&&me.preprocess?await J("select-context",()=>Ri(jt),()=>({input:jt,excluded:[]})):{input:jt,excluded:[]};it.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${it.excluded.join(", ")}`);let at=ao(it.input,se?{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),Xi=Bs(at,{memory:Wn,procedures:Jn,wikiContext:it.input.wikiContext}),qt=(at?.length??0)+(Bt?.length??0)+(e.message?.length??0),dt={history:at?.length??0,sysPrompt:Bt?.length??0,message:e.message?.length??0},rs=No(e.agentId,y,k);Lo(rs,qt,dt);let os=Fo(rs);os&&this.log(`[${e.agentId}] ${os}`),qt>16e3&&this.log(`[${e.agentId}] large context for ${y}:${k}: ${qt} bytes (history=${dt.history}, sysPrompt=${dt.sysPrompt}, message=${dt.message})`),ss||S("route-model");let is=await ns,as=d.def.tier!=="claude-code"?void 0:De==="lean"?Qo(d.def.workspace,Ze,void 0,y):Xo(d.def.workspace);De==="lean"&&!N&&this.log(`[${e.agentId}] session profile for ${y}: ${Vo(De,Ze,y)}`);let ds=d.def.tier==="claude-code"&&!N?hr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:E},g=>this.log(g)):void 0,Yi={...e,systemPromptAppend:Bt,...as?{claudeArgs:as}:{},...is?{model:is}:{}},re,cs=!1,us=pi({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:d.def.maxExecutionMinutes??20}),Vi=j;j=g=>{us.observe(g),Vi?.(g)};try{let g=this.workflowAutoRunner;if(Ie&&g){let U=Ie;try{let Q=await v("workflow-auto-run",()=>g({workflowId:U.workflowId,agentId:e.agentId,channel:y,chatId:k,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:y,chatId:k,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Ie.workflowId} run=${Q.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:Ie.workflowId,workflowRunId:Q.runId,workflowMatchConfidence:Ie.confidence}},re}catch(Q){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${Q?.message||Q}`)}}let m=()=>{if(d.def.tier!=="claude-code")return null;S("dispatch-gate");let U=d.def.persistentProcess?wt():null,Q=U!=null&&U.hasLive({agentId:e.agentId,channel:y,chatId:k}),ce=!!N||Q,oe=[So(ce),Do(ce,void 0,e.model||d.def.model)].find(ut=>ut&&ut.abort);if(oe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let ut={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let ea of b.subscribers)try{ea(b.buffer)}catch{}}return ut}Ao();let Ne=Oo();return Ne&&this.log(`[${e.agentId}] ${Ne}`),null},x=this.planCloudSession(d.def,e);if(x.route==="local"){let U=m();if(U)return d.errors++,re=U,U}let M=d.def.tier==="claude-code",q=M?t:(U,Q)=>{U&&R(U),t&&t(U,Q)},B=!1,ee=M?s:U=>{U&&(B?R(U):(R(`\u{1F4AD} ${U}`),B=!0)),s&&s(U)},te=()=>{B&&(R(`
151
+ `)||void 0,references:Qn,skillInjection:Gn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Yn??tt,memoryContext:qn||void 0,crossChatContext:zn||void 0,longMemoryRecall:Xn||void 0,contextOnDemand:Oe&&!N?Yo(y,k):void 0,wikiContext:Ui,handoverNote:this.buildHandoverNote(e.agentId,y,k),rotationMemo:Hi,eventDigest:N?void 0:ku(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=or(y,!N,d.def.richMessages);return g?$u(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},ot=e.model?void 0:As({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!N,sessionIdleMs:N?et:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let ts=ks(d.def.tier,this.config.decisions.routing),ns=ot?.downgraded?Promise.resolve(ot.model):!e.model&&ts&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-OMIWZKNC.js"),m=await v("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!N,sessionIdleMs:N?et:null,cheapModel:ts}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ss=!1;ns.then(()=>{ss=!0});let it=me.active&&me.preprocess?await J("select-context",()=>Ri(jt),()=>({input:jt,excluded:[]})):{input:jt,excluded:[]};it.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${it.excluded.join(", ")}`);let at=ao(it.input,se?{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),Xi=Bs(at,{memory:Wn,procedures:Jn,wikiContext:it.input.wikiContext}),qt=(at?.length??0)+(Bt?.length??0)+(e.message?.length??0),dt={history:at?.length??0,sysPrompt:Bt?.length??0,message:e.message?.length??0},rs=No(e.agentId,y,k);Lo(rs,qt,dt);let os=Fo(rs);os&&this.log(`[${e.agentId}] ${os}`),qt>16e3&&this.log(`[${e.agentId}] large context for ${y}:${k}: ${qt} bytes (history=${dt.history}, sysPrompt=${dt.sysPrompt}, message=${dt.message})`),ss||S("route-model");let is=await ns,as=d.def.tier!=="claude-code"?void 0:De==="lean"?Qo(d.def.workspace,Ze,void 0,y):Xo(d.def.workspace);De==="lean"&&!N&&this.log(`[${e.agentId}] session profile for ${y}: ${Vo(De,Ze,y)}`);let ds=d.def.tier==="claude-code"&&!N?hr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:E},g=>this.log(g)):void 0,Yi={...e,systemPromptAppend:Bt,...as?{claudeArgs:as}:{},...is?{model:is}:{}},re,cs=!1,us=pi({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:d.def.maxExecutionMinutes??20}),Vi=j;j=g=>{us.observe(g),Vi?.(g)};try{let g=this.workflowAutoRunner;if(Ie&&g){let U=Ie;try{let Q=await v("workflow-auto-run",()=>g({workflowId:U.workflowId,agentId:e.agentId,channel:y,chatId:k,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:y,chatId:k,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Ie.workflowId} run=${Q.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:Ie.workflowId,workflowRunId:Q.runId,workflowMatchConfidence:Ie.confidence}},re}catch(Q){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${Q?.message||Q}`)}}let m=()=>{if(d.def.tier!=="claude-code")return null;S("dispatch-gate");let U=d.def.persistentProcess?wt():null,Q=U!=null&&U.hasLive({agentId:e.agentId,channel:y,chatId:k}),ce=!!N||Q,oe=[So(ce),Do(ce,void 0,e.model||d.def.model)].find(ut=>ut&&ut.abort);if(oe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let ut={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let ea of b.subscribers)try{ea(b.buffer)}catch{}}return ut}Ao();let Ne=Oo();return Ne&&this.log(`[${e.agentId}] ${Ne}`),null},x=this.planCloudSession(d.def,e);if(x.route==="local"){let U=m();if(U)return d.errors++,re=U,U}let M=d.def.tier==="claude-code",q=M?t:(U,Q)=>{U&&R(U),t&&t(U,Q)},B=!1,ee=M?s:U=>{U&&(B?R(U):(R(`\u{1F4AD} ${U}`),B=!0)),s&&s(U)},te=()=>{B&&(R(`
152
152
  `),B=!1)},Zi=M?q:q?(U,Q)=>{te(),q(U,Q)}:void 0,C=await v("agent",async()=>{if(x.route!=="local"){let U=await this.runCloudSession(d.def,e,x,E);if(U)return U;let Q=m();if(Q)return Q}return eo(d.def,Yi,this.providers,Zi,at,N,j,A.signal,ee)},Su);if(!C.error){let U=Cu(d.def.toolUseRequired,O);if(U){let Q=Array.from(O.entries()).map(([ce,ct])=>`${ce}=${ct}`).join(", ")||"none";C.error=`tool_required_not_called: ${U} (invoked: ${Q})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${Q}`)}}ds&&yr(ds,{toolUses:O,eventsSeen:L,error:C.error,agentId:e.agentId},U=>this.log(U));let Wt=this.interruptedRuns.get(p.id);Wt&&(C.content="",C.error=Wt,C.errorKind="interrupted"),re=C;let de=C.usage?Us(C.usage):void 0;if(cs=!0,Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:y,chatId:k,durationMs:Date.now()-Ln,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Wt?!0:void 0,inputTokens:de?.inputTokens,outputTokens:de?.outputTokens,cacheReadTokens:de?.cacheReadTokens,cacheCreateTokens:de?.cacheCreateTokens,tier2InputTokens:de?.tier2InputTokens,tier2OutputTokens:de?.tier2OutputTokens,tier2CacheReadTokens:de?.tier2CacheReadTokens,tier2CacheCreateTokens:de?.tier2CacheCreateTokens,resumed:!!N,resumeSessionId:N||void 0,jevArm:me.arm,numTurns:C.numTurns,injectedContext:Xi,finalResponse:C.content||void 0,billedModel:C.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let U=C.error?`[error] ${C.error}`:C.content;b.buffer=U;for(let Q of b.subscribers)try{Q(U)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,k,C.content),mi({agent:e.agentId,channel:y,chatId:k,request:e.message,reply:C.content,taskId:E}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,k,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,k,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,k,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,y,k,C.usage,C.contextTokens),C.usage){let oe=C.contextTokens,Ne=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(oe??Ne)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${k}: context=${oe??"n/a"} tokens (cumulative turn total=${Ne}) \u2014 next turn will rotate`)}if(Ds({channel:y,content:`User: ${e.message}`,responseLength:C.content.length}).capture){await Un(pu);try{let oe=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:oe,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
153
153
 
154
154
  Agent: ${C.content}`,meta:vu(V,e.context)})}catch{}Os(e.agentId,e.message,C.content,{channel:y,chatId:k,sender:Lt},this.memoryStore).catch(()=>{}),mo(e.agentId,e.message,C.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||d.def.model,ce=e.context?.channel,ct=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,Q,ce,ct),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${w()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=mt(g.message);return re={content:"",error:ht(m),errorKind:m.kind},re}finally{if(us.stop(),!cs)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:re?.error||(A.signal.aborted?Xe(A.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,at:new Date().toISOString()})}catch{}On(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:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),Ee,this.safe(e.agentId),t);ne(s)||fu(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);hu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),Ee,this.safe(e));if(!ne(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=K(a,l);if(ne(f))try{for(let h of ae(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],I=parseInt(p,10);if(!Number.isFinite(I)||I<i||I>s)continue;let A=Math.floor((s-I)/36e5),b=t-1-A;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),Ee);if(!ne(e))return 0;let t=0;for(let s of ae(e)){let r=K(e,s),o;try{o=ae(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=ae(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ye(K(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=Tu){let t=K(process.cwd(),Ee);if(!ne(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=K(t,o),a;try{a=ae(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{mu(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),Ee,this.safe(e));if(!ne(s))return[];let r=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),c;try{c=ae(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(Ye(K(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),Ee,this.safe(e));if(!ne(s))return null;let r=this.safe(t),o=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ne(a))try{return JSON.parse(Ye(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=nr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||Ue(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=kt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{}}: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}}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);Y().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:ws(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let I=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(I))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${I}`),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=>{Ue(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 Pu(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(`
155
155
  `)}export{Tr as a,Gu as b,kr as c,wa as d,Ar as e,bt as f,rl as g,dl as h,cl as i,fl as j,kt as k,Ua as l,Yr as m,Wa as n,Ga as o,Ka as p,eo as q,At as r,$t as s,pd as t,jl as u,ql as v,bn as w,Y as x,ho as y,Td as z,$d as A,bo as B,ig as C,xo as D,vo as E,Po as F,xg as G,_o as H,Pt as I,kg as J,Ag as K,ze as L,Rc as M,Ec as N,Dc as O,Oc as P,Nc as Q,An as R,wu as S,bu as T,gf as U,pf as V,vu as W,ku as X,Au as Y,En as Z,Ai as _,$i as $,Cu as aa,Ci as ba,Mi as ca,Pu as da};
156
- //# sourceMappingURL=chunk-UOAJWNRF.js.map
156
+ //# sourceMappingURL=chunk-D6SWAB5J.js.map
@@ -0,0 +1,2 @@
1
+ var y=new Map;function S(e){if(!y.has(e))try{y.set(e,new RegExp(e,"i"))}catch{y.set(e,null)}return y.get(e)??null}function E(e,f,p){let i=new Set(p.types.map(n=>n.id));if(e.class&&i.has(e.class))return e.class;let d=f.split("/").slice(0,-1).map(n=>n.toLowerCase()),m=new Set((e.tags??[]).map(n=>n.toLowerCase()));for(let n of p.classify){if(!i.has(n.type))continue;let s=0;if(!(n.legacy&&(s++,!e.type||!n.legacy.includes(e.type)))&&!(n.path&&(s++,!n.path.some(c=>d.includes(c.toLowerCase()))))&&!(n.tags&&(s++,!n.tags.some(c=>m.has(c.toLowerCase()))))){if(n.title){s++;let c=S(n.title);if(!c||!c.test(e.title))continue}if(s>0)return n.type}}return i.has(p.fallback_type)?p.fallback_type:p.types[0].id}function h(e){return e.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/\.md$/,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function W(e){return h(e).replace(/ /g,"-").slice(0,80)||"page"}var v=/\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;function G(e){if(e.meta.date)return e.meta.date;let p=(e.path.split("/").pop()??"").match(/^(\d{4}-\d{2}-\d{2})/);if(p)return p[1];let i=e.meta.title.match(/(\d{4}-\d{2}-\d{2})/);return i?i[1]:(e.meta.created||e.meta.lastUpdated||"").slice(0,10)}function P(e,f){let p=new Map(f.types.map(t=>[t.id,t])),i=new Map,d=new Map,m=new Set;for(let t of e){let r=[t.article.meta.title,...t.article.meta.aliases??[]].map(h).filter(Boolean);if(r.length===0)continue;let o=r.map(g=>i.get(g)).find(Boolean);if(!o){o=W(t.article.meta.title);for(let g=2;m.has(o);g++)o=`${W(t.article.meta.title)}-${g}`;m.add(o),d.set(o,[])}d.get(o).push(t);for(let g of r)i.has(g)||i.set(g,o);let l=h(t.article.path);i.has(l)||i.set(l,o)}let n=new Map;for(let[t,r]of d){let o=new Map;for(let a of r){let u=E(a.article.meta,a.article.path,f),A=a.article.meta.class===u?1e3:u===f.fallback_type?.5:1;o.set(u,(o.get(u)??0)+A)}let l=[...o.entries()].sort((a,u)=>u[1]-a[1])[0][0],g=r[0].article,x=r.map(a=>G(a.article)).filter(Boolean).sort(),I=r.map(a=>a.article.meta.importance).find(Boolean)??f.importance.default;n.set(t,{id:t,type:l,pillar:p.get(l)?.pillar??"topics",title:g.meta.title,pages:r,statements:[],date:x[0]??"",updated:r.map(a=>a.article.meta.lastUpdated||"").sort().pop()??"",importance:r.some(a=>a.article.meta.importance==="major")?"major":I,rolledUpInto:r.map(a=>a.article.meta.rolledUpInto).find(Boolean),sources:[...new Set(r.flatMap(a=>a.article.meta.sources??[]))]})}let s=t=>i.get(h(t)),c=new Map,k=new Map,w=t=>{if(t.from===t.to)return;let r=c.get(t.from)??[];if(t.property==="related"&&r.some(l=>l.to===t.to))return;r.push(t),c.set(t.from,r);let o=k.get(t.to)??[];o.push(t),k.set(t.to,o)};for(let t of n.values())for(let r of t.pages)for(let o of r.article.meta.statements??[]){let l={...o,page:r,target:s(o.value)};t.statements.push(l),l.target&&w({from:t.id,to:l.target,property:o.property,statement:l})}for(let t of n.values())for(let r of t.pages){let o=new Set(r.article.meta.related??[]);for(let l of r.article.content.matchAll(v))o.add(l[1].trim());for(let l of o){let g=s(l);g&&w({from:t.id,to:g,property:"related"})}}for(let t of n.values())t.rolledUpInto&&(t.rolledUpInto=s(t.rolledUpInto));return{ontology:f,entities:n,outgoing:c,incoming:k,names:i}}var M=class{last=null;get(f,p){let i=[];for(let s of f.listAgents([]))for(let c of f.getAgentWiki(s).listAllArticles())i.push({agentId:s,article:c});let d=i.map(s=>s.article),m=this.last;if(m&&m.ontology===p&&m.refs.length===d.length&&m.refs.every((s,c)=>s===d[c]))return m.graph;let n=P(i,p);return this.last={refs:d,ontology:p,graph:n},n}};export{h as a,W as b,P as c,M as d};
2
+ //# sourceMappingURL=chunk-EO4DEEXL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/ontology/classify.ts","../src/wiki/ontology/graph.ts"],"sourcesContent":["// --- Give a wiki page its ontology type (#811) ---\n\nimport type { WikiArticleMeta } from \"../types\"\nimport type { Ontology } from \"./types\"\n\nconst patternCache = new Map<string, RegExp | null>()\n\nfunction titlePattern(src: string): RegExp | null {\n if (!patternCache.has(src)) {\n try {\n patternCache.set(src, new RegExp(src, \"i\"))\n } catch {\n patternCache.set(src, null) // reported by checkOntology; the rule never matches\n }\n }\n return patternCache.get(src) ?? null\n}\n\n/**\n * The page's own `class` when the ontology knows it, else the first\n * classify rule whose every condition matches, else the fallback type.\n * `path` is relative to the agent's wiki, e.g. `clients/example.md`.\n */\nexport function classifyPage(meta: WikiArticleMeta, path: string, o: Ontology): string {\n const known = new Set(o.types.map(t => t.id))\n if (meta.class && known.has(meta.class)) return meta.class\n\n const folders = path.split(\"/\").slice(0, -1).map(f => f.toLowerCase())\n const tags = new Set((meta.tags ?? []).map(t => t.toLowerCase()))\n for (const rule of o.classify) {\n if (!known.has(rule.type)) continue\n let conditions = 0\n if (rule.legacy) {\n conditions++\n if (!meta.type || !rule.legacy.includes(meta.type)) continue\n }\n if (rule.path) {\n conditions++\n if (!rule.path.some(p => folders.includes(p.toLowerCase()))) continue\n }\n if (rule.tags) {\n conditions++\n if (!rule.tags.some(t => tags.has(t.toLowerCase()))) continue\n }\n if (rule.title) {\n conditions++\n const re = titlePattern(rule.title)\n if (!re || !re.test(meta.title)) continue\n }\n if (conditions > 0) return rule.type\n }\n return known.has(o.fallback_type) ? o.fallback_type : o.types[0].id\n}\n","// --- One entity per real thing, across every agent's wiki (#811) ---\n//\n// Agents each keep their own pages, so the same person or server can\n// have several. The graph merges pages that share a name (title or\n// alias) into one entity, gives it a type from the ontology, and turns\n// statements and plain links into edges both ways. It is rebuilt only\n// when a page or the ontology changed.\n\nimport type { WikiArticle } from \"../types\"\nimport type { WikiHub } from \"../hub\"\nimport { classifyPage } from \"./classify\"\nimport type { Importance, Ontology, WikiStatement } from \"./types\"\n\nexport interface GraphPage {\n agentId: string\n article: WikiArticle\n}\n\nexport interface EntityStatement extends WikiStatement {\n /** Entity id of the value when it names a page. */\n target?: string\n page: GraphPage\n}\n\nexport interface Entity {\n id: string\n type: string\n pillar: string\n title: string\n pages: GraphPage[]\n statements: EntityStatement[]\n /** YYYY-MM-DD: the event date, else the first page's creation date. */\n date: string\n updated: string\n importance: Importance\n rolledUpInto?: string\n /** Raw entry ids the pages were written from. */\n sources: string[]\n}\n\nexport interface Edge {\n from: string\n to: string\n property: string\n statement?: EntityStatement\n}\n\nexport interface WikiGraph {\n ontology: Ontology\n entities: Map<string, Entity>\n outgoing: Map<string, Edge[]>\n incoming: Map<string, Edge[]>\n /** Normalised name or path → entity id, for links. */\n names: Map<string, string>\n}\n\nexport function normName(s: string): string {\n return s.normalize(\"NFKD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/\\.md$/, \"\").replace(/[^\\p{L}\\p{N}]+/gu, \" \").trim()\n}\n\nexport function slugify(s: string): string {\n return normName(s).replace(/ /g, \"-\").slice(0, 80) || \"page\"\n}\n\nconst WIKILINK = /\\[\\[([^\\]|#]+)(?:[|#][^\\]]*)?\\]\\]/g\n\nfunction eventDate(a: WikiArticle): string {\n if (a.meta.date) return a.meta.date\n const base = a.path.split(\"/\").pop() ?? \"\"\n const fromPath = base.match(/^(\\d{4}-\\d{2}-\\d{2})/)\n if (fromPath) return fromPath[1]\n const fromTitle = a.meta.title.match(/(\\d{4}-\\d{2}-\\d{2})/)\n if (fromTitle) return fromTitle[1]\n return (a.meta.created || a.meta.lastUpdated || \"\").slice(0, 10)\n}\n\n/** Build the graph from pages. Pure: tests call it directly. */\nexport function buildGraph(pages: GraphPage[], o: Ontology): WikiGraph {\n const typeDef = new Map(o.types.map(t => [t.id, t]))\n const names = new Map<string, string>()\n const groups = new Map<string, GraphPage[]>()\n const usedIds = new Set<string>()\n\n for (const page of pages) {\n const keys = [page.article.meta.title, ...(page.article.meta.aliases ?? [])].map(normName).filter(Boolean)\n if (keys.length === 0) continue\n let id = keys.map(k => names.get(k)).find(Boolean)\n if (!id) {\n id = slugify(page.article.meta.title)\n for (let n = 2; usedIds.has(id); n++) id = `${slugify(page.article.meta.title)}-${n}`\n usedIds.add(id)\n groups.set(id, [])\n }\n groups.get(id)!.push(page)\n for (const k of keys) if (!names.has(k)) names.set(k, id)\n const pathKey = normName(page.article.path)\n if (!names.has(pathKey)) names.set(pathKey, id)\n }\n\n const entities = new Map<string, Entity>()\n for (const [id, group] of groups) {\n const votes = new Map<string, number>()\n for (const p of group) {\n const t = classifyPage(p.article.meta, p.article.path, o)\n // An explicit class outvotes any number of inferred ones.\n const weight = p.article.meta.class === t ? 1000 : t === o.fallback_type ? 0.5 : 1\n votes.set(t, (votes.get(t) ?? 0) + weight)\n }\n const type = [...votes.entries()].sort((a, b) => b[1] - a[1])[0][0]\n const first = group[0].article\n const dated = group.map(p => eventDate(p.article)).filter(Boolean).sort()\n const importance = group.map(p => p.article.meta.importance).find(Boolean) ?? o.importance.default\n entities.set(id, {\n id,\n type,\n pillar: typeDef.get(type)?.pillar ?? \"topics\",\n title: first.meta.title,\n pages: group,\n statements: [],\n date: dated[0] ?? \"\",\n updated: group.map(p => p.article.meta.lastUpdated || \"\").sort().pop() ?? \"\",\n importance: group.some(p => p.article.meta.importance === \"major\") ? \"major\" : importance,\n rolledUpInto: group.map(p => p.article.meta.rolledUpInto).find(Boolean),\n sources: [...new Set(group.flatMap(p => p.article.meta.sources ?? []))],\n })\n }\n\n const resolveName = (s: string): string | undefined => names.get(normName(s))\n const outgoing = new Map<string, Edge[]>()\n const incoming = new Map<string, Edge[]>()\n const addEdge = (e: Edge): void => {\n if (e.from === e.to) return\n const out = outgoing.get(e.from) ?? []\n if (e.property === \"related\" && out.some(x => x.to === e.to)) return\n out.push(e)\n outgoing.set(e.from, out)\n const inc = incoming.get(e.to) ?? []\n inc.push(e)\n incoming.set(e.to, inc)\n }\n\n for (const entity of entities.values()) {\n for (const page of entity.pages) {\n for (const s of page.article.meta.statements ?? []) {\n const st: EntityStatement = { ...s, page, target: resolveName(s.value) }\n entity.statements.push(st)\n if (st.target) addEdge({ from: entity.id, to: st.target, property: s.property, statement: st })\n }\n }\n }\n // Plain links after typed ones, so a typed edge wins over \"related\".\n for (const entity of entities.values()) {\n for (const page of entity.pages) {\n const linked = new Set(page.article.meta.related ?? [])\n for (const m of page.article.content.matchAll(WIKILINK)) linked.add(m[1].trim())\n for (const name of linked) {\n const to = resolveName(name)\n if (to) addEdge({ from: entity.id, to, property: \"related\" })\n }\n }\n }\n for (const e of entities.values()) {\n if (e.rolledUpInto) e.rolledUpInto = resolveName(e.rolledUpInto)\n }\n return { ontology: o, entities, outgoing, incoming, names }\n}\n\n/** Builds from a hub, reusing the last graph while no page changed. */\nexport class GraphCache {\n private last: { refs: WikiArticle[]; ontology: Ontology; graph: WikiGraph } | null = null\n\n get(hub: WikiHub, o: Ontology): WikiGraph {\n const pages: GraphPage[] = []\n for (const agentId of hub.listAgents([])) {\n for (const article of hub.getAgentWiki(agentId).listAllArticles()) pages.push({ agentId, article })\n }\n // The store hands back the same objects while files are unchanged.\n const refs = pages.map(p => p.article)\n const last = this.last\n if (last && last.ontology === o && last.refs.length === refs.length && last.refs.every((r, i) => r === refs[i])) {\n return last.graph\n }\n const graph = buildGraph(pages, o)\n this.last = { refs, ontology: o, graph }\n return graph\n }\n}\n"],"mappings":"AAKA,IAAMA,EAAe,IAAI,IAEzB,SAASC,EAAaC,EAA4B,CAChD,GAAI,CAACF,EAAa,IAAIE,CAAG,EACvB,GAAI,CACFF,EAAa,IAAIE,EAAK,IAAI,OAAOA,EAAK,GAAG,CAAC,CAC5C,MAAE,CACAF,EAAa,IAAIE,EAAK,IAAI,CAC5B,CAEF,OAAOF,EAAa,IAAIE,CAAG,GAAK,IAClC,CAOO,SAASC,EAAaC,EAAuBC,EAAcC,EAAqB,CACrF,IAAMC,EAAQ,IAAI,IAAID,EAAE,MAAM,IAAIE,GAAKA,EAAE,EAAE,CAAC,EAC5C,GAAIJ,EAAK,OAASG,EAAM,IAAIH,EAAK,KAAK,EAAG,OAAOA,EAAK,MAErD,IAAMK,EAAUJ,EAAK,MAAM,GAAG,EAAE,MAAM,EAAG,EAAE,EAAE,IAAIK,GAAKA,EAAE,YAAY,CAAC,EAC/DC,EAAO,IAAI,KAAKP,EAAK,MAAQ,CAAC,GAAG,IAAII,GAAKA,EAAE,YAAY,CAAC,CAAC,EAChE,QAAWI,KAAQN,EAAE,SAAU,CAC7B,GAAI,CAACC,EAAM,IAAIK,EAAK,IAAI,EAAG,SAC3B,IAAIC,EAAa,EACjB,GAAI,EAAAD,EAAK,SACPC,IACI,CAACT,EAAK,MAAQ,CAACQ,EAAK,OAAO,SAASR,EAAK,IAAI,KAE/C,EAAAQ,EAAK,OACPC,IACI,CAACD,EAAK,KAAK,KAAKE,GAAKL,EAAQ,SAASK,EAAE,YAAY,CAAC,CAAC,KAExD,EAAAF,EAAK,OACPC,IACI,CAACD,EAAK,KAAK,KAAKJ,GAAKG,EAAK,IAAIH,EAAE,YAAY,CAAC,CAAC,IAEpD,IAAII,EAAK,MAAO,CACdC,IACA,IAAME,EAAKd,EAAaW,EAAK,KAAK,EAClC,GAAI,CAACG,GAAM,CAACA,EAAG,KAAKX,EAAK,KAAK,EAAG,SAEnC,GAAIS,EAAa,EAAG,OAAOD,EAAK,MAElC,OAAOL,EAAM,IAAID,EAAE,aAAa,EAAIA,EAAE,cAAgBA,EAAE,MAAM,CAAC,EAAE,EACnE,CCIO,SAASU,EAASC,EAAmB,CAC1C,OAAOA,EAAE,UAAU,MAAM,EAAE,QAAQ,SAAU,EAAE,EAAE,YAAY,EAAE,QAAQ,QAAS,EAAE,EAAE,QAAQ,mBAAoB,GAAG,EAAE,KAAK,CAC5H,CAEO,SAASC,EAAQD,EAAmB,CACzC,OAAOD,EAASC,CAAC,EAAE,QAAQ,KAAM,GAAG,EAAE,MAAM,EAAG,EAAE,GAAK,MACxD,CAEA,IAAME,EAAW,qCAEjB,SAASC,EAAUC,EAAwB,CACzC,GAAIA,EAAE,KAAK,KAAM,OAAOA,EAAE,KAAK,KAE/B,IAAMC,GADOD,EAAE,KAAK,MAAM,GAAG,EAAE,IAAI,GAAK,IAClB,MAAM,sBAAsB,EAClD,GAAIC,EAAU,OAAOA,EAAS,CAAC,EAC/B,IAAMC,EAAYF,EAAE,KAAK,MAAM,MAAM,qBAAqB,EAC1D,OAAIE,EAAkBA,EAAU,CAAC,GACzBF,EAAE,KAAK,SAAWA,EAAE,KAAK,aAAe,IAAI,MAAM,EAAG,EAAE,CACjE,CAGO,SAASG,EAAWC,EAAoBC,EAAwB,CACrE,IAAMC,EAAU,IAAI,IAAID,EAAE,MAAM,IAAI,GAAK,CAAC,EAAE,GAAI,CAAC,CAAC,CAAC,EAC7CE,EAAQ,IAAI,IACZC,EAAS,IAAI,IACbC,EAAU,IAAI,IAEpB,QAAWC,KAAQN,EAAO,CACxB,IAAMO,EAAO,CAACD,EAAK,QAAQ,KAAK,MAAO,GAAIA,EAAK,QAAQ,KAAK,SAAW,CAAC,CAAE,EAAE,IAAIf,CAAQ,EAAE,OAAO,OAAO,EACzG,GAAIgB,EAAK,SAAW,EAAG,SACvB,IAAIC,EAAKD,EAAK,IAAIE,GAAKN,EAAM,IAAIM,CAAC,CAAC,EAAE,KAAK,OAAO,EACjD,GAAI,CAACD,EAAI,CACPA,EAAKf,EAAQa,EAAK,QAAQ,KAAK,KAAK,EACpC,QAASI,EAAI,EAAGL,EAAQ,IAAIG,CAAE,EAAGE,IAAKF,EAAK,GAAGf,EAAQa,EAAK,QAAQ,KAAK,KAAK,KAAKI,IAClFL,EAAQ,IAAIG,CAAE,EACdJ,EAAO,IAAII,EAAI,CAAC,CAAC,EAEnBJ,EAAO,IAAII,CAAE,EAAG,KAAKF,CAAI,EACzB,QAAWG,KAAKF,EAAWJ,EAAM,IAAIM,CAAC,GAAGN,EAAM,IAAIM,EAAGD,CAAE,EACxD,IAAMG,EAAUpB,EAASe,EAAK,QAAQ,IAAI,EACrCH,EAAM,IAAIQ,CAAO,GAAGR,EAAM,IAAIQ,EAASH,CAAE,EAGhD,IAAMI,EAAW,IAAI,IACrB,OAAW,CAACJ,EAAIK,CAAK,IAAKT,EAAQ,CAChC,IAAMU,EAAQ,IAAI,IAClB,QAAWC,KAAKF,EAAO,CACrB,IAAMG,EAAIC,EAAaF,EAAE,QAAQ,KAAMA,EAAE,QAAQ,KAAMd,CAAC,EAElDiB,EAASH,EAAE,QAAQ,KAAK,QAAUC,EAAI,IAAOA,IAAMf,EAAE,cAAgB,GAAM,EACjFa,EAAM,IAAIE,GAAIF,EAAM,IAAIE,CAAC,GAAK,GAAKE,CAAM,EAE3C,IAAMC,EAAO,CAAC,GAAGL,EAAM,QAAQ,CAAC,EAAE,KAAK,CAAC,EAAGM,IAAMA,EAAE,CAAC,EAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAC5DC,EAAQR,EAAM,CAAC,EAAE,QACjBS,EAAQT,EAAM,IAAIE,GAAKpB,EAAUoB,EAAE,OAAO,CAAC,EAAE,OAAO,OAAO,EAAE,KAAK,EAClEQ,EAAaV,EAAM,IAAIE,GAAKA,EAAE,QAAQ,KAAK,UAAU,EAAE,KAAK,OAAO,GAAKd,EAAE,WAAW,QAC3FW,EAAS,IAAIJ,EAAI,CACf,GAAAA,EACA,KAAAW,EACA,OAAQjB,EAAQ,IAAIiB,CAAI,GAAG,QAAU,SACrC,MAAOE,EAAM,KAAK,MAClB,MAAOR,EACP,WAAY,CAAC,EACb,KAAMS,EAAM,CAAC,GAAK,GAClB,QAAST,EAAM,IAAIE,GAAKA,EAAE,QAAQ,KAAK,aAAe,EAAE,EAAE,KAAK,EAAE,IAAI,GAAK,GAC1E,WAAYF,EAAM,KAAKE,GAAKA,EAAE,QAAQ,KAAK,aAAe,OAAO,EAAI,QAAUQ,EAC/E,aAAcV,EAAM,IAAIE,GAAKA,EAAE,QAAQ,KAAK,YAAY,EAAE,KAAK,OAAO,EACtE,QAAS,CAAC,GAAG,IAAI,IAAIF,EAAM,QAAQE,GAAKA,EAAE,QAAQ,KAAK,SAAW,CAAC,CAAC,CAAC,CAAC,CACxE,CAAC,EAGH,IAAMS,EAAehC,GAAkCW,EAAM,IAAIZ,EAASC,CAAC,CAAC,EACtEiC,EAAW,IAAI,IACfC,EAAW,IAAI,IACfC,EAAWC,GAAkB,CACjC,GAAIA,EAAE,OAASA,EAAE,GAAI,OACrB,IAAMC,EAAMJ,EAAS,IAAIG,EAAE,IAAI,GAAK,CAAC,EACrC,GAAIA,EAAE,WAAa,WAAaC,EAAI,KAAKC,GAAKA,EAAE,KAAOF,EAAE,EAAE,EAAG,OAC9DC,EAAI,KAAKD,CAAC,EACVH,EAAS,IAAIG,EAAE,KAAMC,CAAG,EACxB,IAAME,EAAML,EAAS,IAAIE,EAAE,EAAE,GAAK,CAAC,EACnCG,EAAI,KAAKH,CAAC,EACVF,EAAS,IAAIE,EAAE,GAAIG,CAAG,CACxB,EAEA,QAAWC,KAAUpB,EAAS,OAAO,EACnC,QAAWN,KAAQ0B,EAAO,MACxB,QAAWxC,KAAKc,EAAK,QAAQ,KAAK,YAAc,CAAC,EAAG,CAClD,IAAM2B,EAAsB,CAAE,GAAGzC,EAAG,KAAAc,EAAM,OAAQkB,EAAYhC,EAAE,KAAK,CAAE,EACvEwC,EAAO,WAAW,KAAKC,CAAE,EACrBA,EAAG,QAAQN,EAAQ,CAAE,KAAMK,EAAO,GAAI,GAAIC,EAAG,OAAQ,SAAUzC,EAAE,SAAU,UAAWyC,CAAG,CAAC,EAKpG,QAAWD,KAAUpB,EAAS,OAAO,EACnC,QAAWN,KAAQ0B,EAAO,MAAO,CAC/B,IAAME,EAAS,IAAI,IAAI5B,EAAK,QAAQ,KAAK,SAAW,CAAC,CAAC,EACtD,QAAW6B,KAAK7B,EAAK,QAAQ,QAAQ,SAASZ,CAAQ,EAAGwC,EAAO,IAAIC,EAAE,CAAC,EAAE,KAAK,CAAC,EAC/E,QAAWC,KAAQF,EAAQ,CACzB,IAAMG,EAAKb,EAAYY,CAAI,EACvBC,GAAIV,EAAQ,CAAE,KAAMK,EAAO,GAAI,GAAAK,EAAI,SAAU,SAAU,CAAC,GAIlE,QAAWT,KAAKhB,EAAS,OAAO,EAC1BgB,EAAE,eAAcA,EAAE,aAAeJ,EAAYI,EAAE,YAAY,GAEjE,MAAO,CAAE,SAAU3B,EAAG,SAAAW,EAAU,SAAAa,EAAU,SAAAC,EAAU,MAAAvB,CAAM,CAC5D,CAGO,IAAMmC,EAAN,KAAiB,CACd,KAA6E,KAErF,IAAIC,EAActC,EAAwB,CACxC,IAAMD,EAAqB,CAAC,EAC5B,QAAWwC,KAAWD,EAAI,WAAW,CAAC,CAAC,EACrC,QAAWE,KAAWF,EAAI,aAAaC,CAAO,EAAE,gBAAgB,EAAGxC,EAAM,KAAK,CAAE,QAAAwC,EAAS,QAAAC,CAAQ,CAAC,EAGpG,IAAMC,EAAO1C,EAAM,IAAIe,GAAKA,EAAE,OAAO,EAC/B4B,EAAO,KAAK,KAClB,GAAIA,GAAQA,EAAK,WAAa1C,GAAK0C,EAAK,KAAK,SAAWD,EAAK,QAAUC,EAAK,KAAK,MAAM,CAACC,EAAGC,IAAMD,IAAMF,EAAKG,CAAC,CAAC,EAC5G,OAAOF,EAAK,MAEd,IAAMG,EAAQ/C,EAAWC,EAAOC,CAAC,EACjC,YAAK,KAAO,CAAE,KAAAyC,EAAM,SAAUzC,EAAG,MAAA6C,CAAM,EAChCA,CACT,CACF","names":["patternCache","titlePattern","src","classifyPage","meta","path","o","known","t","folders","f","tags","rule","conditions","p","re","normName","s","slugify","WIKILINK","eventDate","a","fromPath","fromTitle","buildGraph","pages","o","typeDef","names","groups","usedIds","page","keys","id","k","n","pathKey","entities","group","votes","p","t","classifyPage","weight","type","b","first","dated","importance","resolveName","outgoing","incoming","addEdge","e","out","x","inc","entity","st","linked","m","name","to","GraphCache","hub","agentId","article","refs","last","r","i","graph"]}
@@ -1,2 +1,2 @@
1
- import{y as l,z as T}from"./chunk-BN5QMNON.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
- //# sourceMappingURL=chunk-INLKJEEN.js.map
1
+ import{y as l,z as T}from"./chunk-JUIL2EW3.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
+ //# sourceMappingURL=chunk-FVG2BADS.js.map
@@ -1,4 +1,4 @@
1
- import{Aa as iu,D as Un,Ea as ou,F as Ed,Fa as qn,Ga as fi,Ha as au,Ia as cu,J as Cd,Ja as lu,Ka as du,L as Pd,Ma as uu,N as Md,O as ui,P as _d,Q as Ge,R as Od,S as Gn,Ta as hu,U as hi,Ua as gu,V as Dd,W as pi,X as Ye,Y as Bd,Z as qd,a as ql,aa as Qe,b as si,ba as Vd,bb as yi,ca as Jd,cb as wi,da as Xd,ea as Kd,eb as pu,f as ri,fa as zd,g as Vl,ga as Yd,h as Jl,i as Fe,ia as me,j as Xl,ja as Wn,k as Kl,ka as mi,la as Qd,m as zl,ma as Wt,na as Zd,o as Yl,oa as Ae,p as ld,pa as eu,q as dd,qa as tu,r as ud,ra as nu,s as hd,sa as Hn,t as gd,ta as Bn,u as pd,ua as su,v as md,va as ru,w as fd,x as yd,y as li}from"./chunk-4WKBK7EQ.js";import{d as Wl,g as Hl,h as Bl}from"./chunk-5RE2B5YQ.js";import{m as Zl,n as ed,o as oi,p as xe,r as td,s as pe}from"./chunk-S2GAEH2F.js";import{c as Hd}from"./chunk-BGG3ZSMW.js";import{a as Ql}from"./chunk-ZVP6GB4G.js";import{d as nd}from"./chunk-XGOBZCYC.js";import{g as sd}from"./chunk-LQE73AZR.js";import{b as rd,c as id}from"./chunk-2D3RYIDU.js";import{i as wd,m as di,n as bd,p as kd,q as vd,r as Sd,s as $d,t as Id,u as Td}from"./chunk-WEPON4FP.js";import{f as ai,g as od,h as Ln,i as ft,k as Ue,m as ad,n as cd,o as ci,p as Fn}from"./chunk-AKLZ4YO2.js";import{a as xd}from"./chunk-PPUN7YHA.js";import{a as Ad,b as Rd}from"./chunk-VZLIBDLH.js";import{b as Nd,c as jd,d as gi,e as Ld,f as Fd,g as Ud,h as Gd,i as Wd}from"./chunk-EKJG63EJ.js";import{o as ii}from"./chunk-YKYMGIQ5.js";import{b as jn}from"./chunk-EMGB23H5.js";import{A as Uc,B as Gc,C as Wc,D as ae,E as Bc,F as qc,G as Vc,H as Jc,I as Xc,J as Kc,K as zc,L as Al,M as Rl,N as El,O as Cl,P as Pl,Q as Ml,U as Dl,a as gc,b as Vr,c as mc,ca as Nl,d as $c,e as Ic,f as Ft,h as Xr,i as Kr,j as zr,k as Yr,l as Tc,s as xc,t as Ec,u as Ut,v as Cc,w as _c,x as B,z as Fc}from"./chunk-UOAJWNRF.js";import{A as Sl,B as $l,C as Il,D as Tl,E as xl,G as _l,M as Ol,a as Ac,c as Pc,d as Mc,e as ze,f as De,l as Yc,m as Qc,o as dl,p as ul,q as ml,r as fl,s as yl,t as wl,v as ni,w as On,x as bl,y as kl,z as vl}from"./chunk-ITATBKUL.js";import{b as il,c as ol,d as ei,f as Mn,g as al,h as cl,i as ll,j as Gt,k as _n}from"./chunk-GLQLCBJS.js";import{a as Qr,b as Rc}from"./chunk-6W74CHNW.js";import{A as jl,B as Dn,C as Ll,h as _a,n as Oa,o as Pr}from"./chunk-5VWOK3GQ.js";import{b as Ca}from"./chunk-SFQUP3BP.js";import{a as Le}from"./chunk-Y4CYQV7G.js";import{a as Fl,b as Nn,c as Ul,d as Gl}from"./chunk-LLNPKE7H.js";import{a as pt,b as mt}from"./chunk-SHEUCITK.js";import{a as Zc,b as Zr,c as el,d as tl,e as nl,i as sl}from"./chunk-76Z4VHDX.js";import{b as Hc}from"./chunk-W4YR2RO2.js";import{b as oe,d as gt,f as En,g as Cn,i as le,j as rl,k as Ne,l as je,m as pl,s as ti}from"./chunk-5DFUUYEA.js";import{a as hl,b as gl}from"./chunk-WMTGAVPW.js";import{d as Oc,e as Dc,f as Nc,g as jc,h as Lc,j as Pn}from"./chunk-X5C5W3E4.js";import{c as hc}from"./chunk-MYVHVJWZ.js";import{d as fc,e as yc,f as Jr,g as Rn,h as wc,i as bc,j as kc,k as vc,q as Sc}from"./chunk-AV7T3SYT.js";import{b as pc}from"./chunk-56KNKUFF.js";import{d as Da,e as nw,m as lc,n as hw,q as dc,v as uc,y as ht,z as An}from"./chunk-BN5QMNON.js";import{a as Ke,b as Lt,f as qr}from"./chunk-72SZI2UW.js";import{a as Mr,b as tw}from"./chunk-FCPTN6NF.js";import{a as vn,b as ew}from"./chunk-7I7IEX4S.js";import{b as Pa,e as Ma}from"./chunk-JHCI6XCJ.js";import{e as Ve}from"./chunk-DSYKYZMT.js";import{$ as Hr,A as Qa,B as Ur,C as Gr,E as Wr,G as Za,H as ec,J as xn,K as tc,L as nc,M as sc,N as rc,O as cw,R as ic,U as oc,V as ac,Z as lw,ba as dw,d as ut,e as ja,f as Or,g as sw,h as Sn,i as Dr,j as $n,l as Je,m as Nr,n as La,o as rw,oa as Br,p as In,pa as cc,q as iw,r as Tn,ra as uw,s as Fa,t as ow,w as za,x as Ya}from"./chunk-46JKX6CT.js";import{a as Wa,b as Ha,c as Ba,e as qa,f as Lr,g as Va,h as Ja,i as Fr,j as Xa,k as Ka,n as aw}from"./chunk-UIBUZ2N3.js";import{e as Xe,f as Ua,g as Ga,h as jr}from"./chunk-BRK6M6LA.js";import{b as _r,e as Na}from"./chunk-2QNT5JDS.js";import{d as dt}from"./chunk-QIJLFPWE.js";import{existsSync as $i,readFileSync as Ii}from"fs";var mu=["answer","narration","line"];function fu(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function yu(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!mu.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${mu.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:p,done:f}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:p}}:{status:200,body:{item:p,played:await f}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:bi(i);case"front":return r.front(i)?{status:200,body:r.view()}:bi(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:bi(i)}default:return{status:404,body:{error:"Not found"}}}}function wu(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{Aa as iu,D as Un,Ea as ou,F as Ed,Fa as qn,Ga as fi,Ha as au,Ia as cu,J as Cd,Ja as lu,Ka as du,L as Pd,Ma as uu,N as Md,O as ui,P as _d,Q as Ge,R as Od,S as Gn,Ta as hu,U as hi,Ua as gu,V as Dd,W as pi,X as Ye,Y as Bd,Z as qd,a as ql,aa as Qe,b as si,ba as Vd,bb as yi,ca as Jd,cb as wi,da as Xd,ea as Kd,eb as pu,f as ri,fa as zd,g as Vl,ga as Yd,h as Jl,i as Fe,ia as me,j as Xl,ja as Wn,k as Kl,ka as mi,la as Qd,m as zl,ma as Wt,na as Zd,o as Yl,oa as Ae,p as ld,pa as eu,q as dd,qa as tu,r as ud,ra as nu,s as hd,sa as Hn,t as gd,ta as Bn,u as pd,ua as su,v as md,va as ru,w as fd,x as yd,y as li}from"./chunk-O4XEQTEN.js";import{d as Wl,g as Hl,h as Bl}from"./chunk-JIXNSA67.js";import{a as Ql}from"./chunk-ZVP6GB4G.js";import{m as Zl,n as ed,o as oi,p as xe,r as td,s as pe}from"./chunk-S2GAEH2F.js";import{a as Ad,b as Rd}from"./chunk-VZLIBDLH.js";import{b as Nd,c as jd,d as gi,e as Ld,f as Fd,g as Ud,h as Gd,i as Wd}from"./chunk-EKJG63EJ.js";import{c as Hd}from"./chunk-BGG3ZSMW.js";import{d as nd}from"./chunk-XGOBZCYC.js";import{g as sd}from"./chunk-LQE73AZR.js";import{b as rd,c as id}from"./chunk-2D3RYIDU.js";import{i as wd,m as di,n as bd,p as kd,q as vd,r as Sd,s as $d,t as Id,u as Td}from"./chunk-WEPON4FP.js";import{f as ai,g as od,h as Ln,i as ft,k as Ue,m as ad,n as cd,o as ci,p as Fn}from"./chunk-AKLZ4YO2.js";import{a as xd}from"./chunk-PPUN7YHA.js";import{a as Le}from"./chunk-Y4CYQV7G.js";import{a as Fl,b as Nn,c as Ul,d as Gl}from"./chunk-LLNPKE7H.js";import{a as pt,b as mt}from"./chunk-SHEUCITK.js";import{o as ii}from"./chunk-GUQDPA6R.js";import{b as jn}from"./chunk-EMGB23H5.js";import{A as Uc,B as Gc,C as Wc,D as ae,E as Bc,F as qc,G as Vc,H as Jc,I as Xc,J as Kc,K as zc,L as Al,M as Rl,N as El,O as Cl,P as Pl,Q as Ml,U as Dl,a as gc,b as Vr,c as mc,ca as Nl,d as $c,e as Ic,f as Ft,h as Xr,i as Kr,j as zr,k as Yr,l as Tc,s as xc,t as Ec,u as Ut,v as Cc,w as _c,x as B,z as Fc}from"./chunk-D6SWAB5J.js";import{A as Sl,B as $l,C as Il,D as Tl,E as xl,G as _l,M as Ol,a as Ac,c as Pc,d as Mc,e as ze,f as De,l as Yc,m as Qc,o as dl,p as ul,q as ml,r as fl,s as yl,t as wl,v as ni,w as On,x as bl,y as kl,z as vl}from"./chunk-LVV7JBHM.js";import{b as il,c as ol,d as ei,f as Mn,g as al,h as cl,i as ll,j as Gt,k as _n}from"./chunk-GLQLCBJS.js";import{a as Qr,b as Rc}from"./chunk-6W74CHNW.js";import{A as jl,B as Dn,C as Ll,h as _a,n as Oa,o as Pr}from"./chunk-WUDVBPQV.js";import{b as Ca}from"./chunk-SFQUP3BP.js";import{d as Oc,e as Dc,f as Nc,g as jc,h as Lc,j as Pn}from"./chunk-X5C5W3E4.js";import{a as Zc,b as Zr,c as el,d as tl,e as nl,i as sl}from"./chunk-76Z4VHDX.js";import{b as Hc}from"./chunk-W4YR2RO2.js";import{b as oe,d as gt,f as En,g as Cn,i as le,j as rl,k as Ne,l as je,m as pl,s as ti}from"./chunk-5DFUUYEA.js";import{a as hl,b as gl}from"./chunk-WMTGAVPW.js";import{b as pc}from"./chunk-56KNKUFF.js";import{d as Da,e as nw,m as lc,n as hw,q as dc,v as uc,y as ht,z as An}from"./chunk-JUIL2EW3.js";import{a as Ke,b as Lt,f as qr}from"./chunk-72SZI2UW.js";import{a as Mr,b as tw}from"./chunk-FCPTN6NF.js";import{c as hc}from"./chunk-MYVHVJWZ.js";import{d as fc,e as yc,f as Jr,g as Rn,h as wc,i as bc,j as kc,k as vc,q as Sc}from"./chunk-AV7T3SYT.js";import{a as vn,b as ew}from"./chunk-7I7IEX4S.js";import{b as Pa,e as Ma}from"./chunk-JHCI6XCJ.js";import{e as Ve}from"./chunk-DSYKYZMT.js";import{$ as Hr,A as Qa,B as Ur,C as Gr,E as Wr,G as Za,H as ec,J as xn,K as tc,L as nc,M as sc,N as rc,O as cw,R as ic,U as oc,V as ac,Z as lw,ba as dw,d as ut,e as ja,f as Or,g as sw,h as Sn,i as Dr,j as $n,l as Je,m as Nr,n as La,o as rw,oa as Br,p as In,pa as cc,q as iw,r as Tn,ra as uw,s as Fa,t as ow,w as za,x as Ya}from"./chunk-46JKX6CT.js";import{a as Wa,b as Ha,c as Ba,e as qa,f as Lr,g as Va,h as Ja,i as Fr,j as Xa,k as Ka,n as aw}from"./chunk-UIBUZ2N3.js";import{e as Xe,f as Ua,g as Ga,h as jr}from"./chunk-BRK6M6LA.js";import{b as _r,e as Na}from"./chunk-2QNT5JDS.js";import{d as dt}from"./chunk-QIJLFPWE.js";import{existsSync as $i,readFileSync as Ii}from"fs";var mu=["answer","narration","line"];function fu(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function yu(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!mu.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${mu.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:p,done:f}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:p}}:{status:200,body:{item:p,played:await f}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:bi(i);case"front":return r.front(i)?{status:200,body:r.view()}:bi(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:bi(i)}default:return{status:404,body:{error:"Not found"}}}}function wu(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var bi=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as Ti}from"path";dw();var gw={name:"agentx",version:"0.1.0"},pw=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],mw="2024-11-05";function fw(r){return typeof r=="string"&&pw.includes(r)?r:mw}var yw={tools:{},elicitation:{form:{}}},ww=0;async function bu(r,e){let t=++ww;return Ze({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Ht.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Ht.has(`elicit-${t}`)&&(Ht.delete(`elicit-${t}`),n(null))},6e4)})}var Ht=new Map,bw="http://localhost:18800",ki;function kw(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=Ti(process.cwd(),r);if(!$i(e))continue;let t=JSON.parse(Ii(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return bw}function J(){return ki===void 0&&(ki=kw()),ki}var vi;function vw(r){try{let e=Ti(process.cwd(),".env");if(!$i(e))return"";for(let t of Ii(e,"utf-8").split(`
3
3
  `)){let n=t.trim().replace(/^export\s+/,"");if(!n.startsWith(`${r}=`))continue;let s=n.slice(r.length+1).trim();return/^(["']).*\1$/.test(s)?s.slice(1,-1):s}}catch{}return""}function Sw(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=vw("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=Ti(process.cwd(),t);if(!$i(n))continue;let s=JSON.parse(Ii(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function $w(){return vi===void 0&&(vi=Sw()),vi}var X=(r,e)=>{let t=$w();if(!t)return fetch(r,e);let n=new Headers(e?.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${t}`),fetch(r,{...e,headers:n})};function Si(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function Iw(){let r=process.env.AGENTX_AGENT_ID,e=Si();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await X(`${J()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var Tw=/\x1B\[[0-9;]*[A-Za-z]/g;function yt(r){return r.replace(Tw,"")}async function xw(r,e,t){let n=await X(`${J()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:Aw(i,!!s.hasMore)}]}}function Aw(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
4
4
  ${o.join(`
@@ -35,7 +35,7 @@ Open it with your Read tool.`}]}}case"agentx_health":{let s=await(await X(`${J()
35
35
  `)}]}}case"agentx_attach_answer":{let n=process.env.CLAUDE_CODE_SESSION_ID;if(!n)return{content:[{type:"text",text:"Not running inside a Claude Code session \u2014 attach mode is unavailable here."}]};let s=await X(`${J()}/attach/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,text:String(e.text??"")})}),i=await s.json();if(!s.ok)return{content:[{type:"text",text:`Could not answer: ${i?.error??s.status}`}]};let o=i.pending>0?` ${i.pending} still queued.`:"";return{content:[{type:"text",text:`Sent to ${i.item?.channel}.${o}`}]}}case"agentx_events":{let n=process.env.AGENTX_AGENT_ID||e.agentId;if(!n)return{content:[{type:"text",text:"Error: agentId is required (no AGENTX_AGENT_ID in this session)."}]};let s=new URLSearchParams;typeof e.since=="string"&&e.since&&s.set("since",e.since),typeof e.limit=="number"&&s.set("limit",String(e.limit));let i=await X(`${J()}/agents/${encodeURIComponent(n)}/events?${s}`,{signal:AbortSignal.timeout(1e4)}),o=await i.json().catch(()=>({}));if(!i.ok)return{content:[{type:"text",text:`Error: ${o.error||i.statusText}`}]};let{formatEventLine:a}=await import("./subscriptions-RYVPHVIV.js");return{content:[{type:"text",text:Ew(n,o,a)}]}}case"agentx_crons":{let s=await(await X(`${J()}/crons/health`)).json(),i=`Healthy: ${s.healthy}, Failing: ${s.failing}, Disabled: ${s.disabled}, Missed: ${s.missed}`,o=(s.jobs||[]).map(a=>` ${a.id}: ${a.status}${a.consecutiveErrors?` (${a.consecutiveErrors} errors)`:""}${a.lastError?` \u2014 ${a.lastError.slice(0,100)}`:""}`).join(`
36
36
  `);return{content:[{type:"text",text:`${i}
37
37
 
38
- ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-YRANRFHO.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await X(`${J()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-5JTCSRTW.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J(),fetch:X})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-FZEC5FQX.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J(),fetch:X})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-AIOLNUF7.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-WJM5XNFS.js"),{agenticQuery:i}=await import("./query-RV6SHTRN.js"),{resolve:o}=await import("path"),a=e.wiki_dir||o(process.cwd(),".agentx/wiki"),c=new s(a,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:k}=await import("fs");for(let S of c.listAgents()){let $=o(c.getAgentWiki(S).baseDir,"_index.md");if(k($)){l=S;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let d=c.getAgentWiki(l),u=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,p=await Iw(),f=await i(n,d,l,{maxHops:u,messagePath:p?.path,...p?.graphWeight!==void 0?{graphWeight:p.graphWeight}:{}});if(f.status!=="ok")return{content:[{type:"text",text:`Query returned status "${f.status}"${f.error?`: ${f.error}`:""}`}]};let g=f.citations.map(k=>` - ${k.title} [${k.type||"?"}] (${k.path})`).join(`
38
+ ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-YRANRFHO.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await X(`${J()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-5JTCSRTW.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J(),fetch:X})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-FZEC5FQX.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J(),fetch:X})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-AIOLNUF7.js");return{content:[{type:"text",text:await n(e,{daemonUrl:J()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-BT3H2WCD.js"),{agenticQuery:i}=await import("./query-DNJONEKC.js"),{resolve:o}=await import("path"),a=e.wiki_dir||o(process.cwd(),".agentx/wiki"),c=new s(a,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:k}=await import("fs");for(let S of c.listAgents()){let $=o(c.getAgentWiki(S).baseDir,"_index.md");if(k($)){l=S;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let d=c.getAgentWiki(l),u=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,p=await Iw(),f=await i(n,d,l,{maxHops:u,messagePath:p?.path,...p?.graphWeight!==void 0?{graphWeight:p.graphWeight}:{}});if(f.status!=="ok")return{content:[{type:"text",text:`Query returned status "${f.status}"${f.error?`: ${f.error}`:""}`}]};let g=f.citations.map(k=>` - ${k.title} [${k.type||"?"}] (${k.path})`).join(`
39
39
  `),b=f.walked.length;return{content:[{type:"text",text:`${f.answer}
40
40
 
41
41
  Citations (${b} article${b===1?"":"s"} walked):
@@ -521,7 +521,7 @@ ${l}`)}let S={agentId:o,message:k,context:{channel:b,sender:g?"opencode":"openai
521
521
 
522
522
  `)}}function Dh(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Nh(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
523
523
 
524
- `)}function jh(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);zi(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function zi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Zt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Zt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Zt.levelOrder[e]<Zt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Qt=Zt;dt(Qt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Mk,statSync as _k}from"fs";var It={version:"0.125.1",commit:"77c1258",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ok(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Fh(){let r=null;try{r=_k(Mk(process.argv[1])).mtimeMs}catch{}let e=oh().version;return Ok(It,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Dk}from"crypto";var bs=class{constructor(e=new _c){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Nk.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Lk(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Dk(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=jk(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Nk=["run","task","signal","mesh","channel","status"];function jk(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Lk(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Uh(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as ks,timingSafeEqual as Gh}from"crypto";var vs=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(y[k]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let p=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),g=p&&f?.triggers?.[p]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,p,i,c),g&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:g,entityRef:{kind:"webhook",id:`${l}:${i}:${p??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:p,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${p??"\u2014"}] -> workflow=${g} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:p,workflow:g,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${p}/${g}]: ${y.message}`)}let b=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(b?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:b.node,status:"accepted"}),this.mesh.sendTask(b.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${b.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${b.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
524
+ `)}function jh(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);zi(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function zi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Zt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Zt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Zt.levelOrder[e]<Zt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Qt=Zt;dt(Qt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Mk,statSync as _k}from"fs";var It={version:"0.126.0",commit:"d0cf730",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ok(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Fh(){let r=null;try{r=_k(Mk(process.argv[1])).mtimeMs}catch{}let e=oh().version;return Ok(It,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Dk}from"crypto";var bs=class{constructor(e=new _c){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Nk.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Lk(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Dk(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=jk(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Nk=["run","task","signal","mesh","channel","status"];function jk(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Lk(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Uh(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as ks,timingSafeEqual as Gh}from"crypto";var vs=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(y[k]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let p=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),g=p&&f?.triggers?.[p]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,p,i,c),g&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:g,entityRef:{kind:"webhook",id:`${l}:${i}:${p??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:p,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${p??"\u2014"}] -> workflow=${g} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:p,workflow:g,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${p}/${g}]: ${y.message}`)}let b=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(b?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:b.node,status:"accepted"}),this.mesh.sendTask(b.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${b.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${b.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
525
525
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
526
526
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",p=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${p?`, ${p}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
527
527
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+ks("sha256",a).update(t).digest("hex");return Tt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Tt(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let p=ks("sha256",a).update(`${u.t}.${t}`).digest("hex");return Tt(p,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let p=parseInt(u,10);if(!Number.isFinite(p))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-p;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let g="POST",b=i||e["x-original-uri"]||e["x-forwarded-path"]||"",y=e["x-forwarded-host"],k=e.host,S=e["x-forwarded-proto"]||"https",$=new Set;y&&b&&$.add(`${S}://${y}${b}`),k&&b&&$.add(`https://${k}${b}`),k&&b&&$.add(`http://${k}${b}`),b&&$.add(b),$.add("");for(let P of $){let D=ks("sha256",a).update(`${g}${P}${t}${u}`).digest("base64");if(d.length===D.length&&Gh(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${$.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let p=ks("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return Tt(p,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Tt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Tt(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function Tt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Gh(t,n)?null:"signature mismatch"}aw();tw();qa();function Fk(r){return{insertTaskHistory:r.prepare(`
@@ -1151,4 +1151,4 @@ data: ${JSON.stringify(V)}
1151
1151
  `)}catch{}},j=setInterval(()=>{try{t.write(`: ping
1152
1152
 
1153
1153
  `)}catch{}},15e3);j.unref?.();let L=new AbortController;t.on("close",()=>{t.writableEnded||L.abort()});try{for await(let U of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:L.signal,vouchOwner:v}))E(U.event,U.data)}catch(U){E("error",{error:U?.message??String(U)})}finally{clearInterval(j);try{t.end()}catch{}}break}let A=h.context,M=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(Py(h,!0)==="callback"){let E=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:A});if(!("track"in E)){let j=br(E);this.json(t,j.status,j.body);break}}if(h.async===!0){let E=A?.channel,j=A?.chatId;if(!E||!j){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let L=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:L,deliverTo:`${E}:${j}`,note:"result will be delivered to the originating chat when the peer finishes"});let U=h.peer,V=h.agent,ye=this.mesh;(async()=>{let H=Date.now(),q;try{q=await ye.sendTask(U,h.message,V,{vouchOwner:v,context:A,senderAgentId:M}),this.log(`[mesh/task async ${L}] ${U}/${V??"default"} finished in ${Date.now()-H}ms`)}catch(Y){q=`Delegation to ${U}/${V??"default"} failed: ${Y?.message??Y}`,this.log(`[mesh/task async ${L}] failed: ${Y?.message??Y}`)}try{await this.router.sendOutbound({channel:E,chatId:j,text:q,agentId:A?.agentId??M,accountId:A?.accountId})}catch(Y){this.log(`[mesh/task async ${L}] delivery failed: ${Y?.message??Y}`)}})();break}let _=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:A,senderAgentId:M,vouchOwner:v});this.json(t,200,{response:_});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await W(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=await this.webrtc.handleOutgoing(m);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await W(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=this.webrtc.handleIncoming(m);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await W(e),m=h.callId,w=h.target,v=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!w||!v){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:w,agentId:v});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(m=>({urls:m})),...h.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:h.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let m=this.config.agents[h.id]||{},w=typeof m.description=="string"&&m.description.trim()||xT(m.systemPrompt)||`Agent "${h.name}" (${h.tier})`,v=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:w,tags:[h.tier,...v],color:he(h.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,v=m?h.getAgentEntries(m):h.getSharedStore().listEntries({after:w});this.json(t,200,{nodeId:this.config.node.id,count:v.length,entries:v.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let v=h.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:v.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),m=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!m||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=h.getAgentWiki(m).readArticle(w);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),v=h.listByStatus(m,w);this.json(t,200,{nodeId:this.config.node.id,status:m,count:v.length,classifications:v});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await W(e);await Lh(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=pm(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=ug();if(e==="json")return this.registry.getTodayUsage();let t=dg(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!Nt(n)))try{let s=te(n,".claude","skills");Qy(s,{recursive:!0});let i=te(s,mm);if(!Nt(i))xa(i,Eo(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=ym(kn(i,"utf-8"),e);o&&(xa(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!Nt(n))continue;let s=this.config.workflows.enabled&&this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0),i=Kc(fc(t),this.config.requests.enabled||s?Xc():null);try{switch(zc(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Jp(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await ne(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let p=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${p}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:p}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(g=>g.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(g=>g.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(p=>p.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await ne(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-325SXDGN.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return nd(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await ne(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-325SXDGN.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let p of l)!p.id||s.has(p.id)||(s.add(p.id),i.push({...p,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let p=await u.json();Array.isArray(p.chats)&&a(p.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await ne(e)}catch{s={}}try{let i=await gm({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Aa=Ra;dt(Aa,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function xT(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function ne(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function AT(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function W(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}ew();function K2(r){typeof r=="string"&&(vn.error(r),process.exit(1)),r instanceof Error&&(vn.error(r.message),process.exit(1)),vn.error("Something went wrong. Please try again."),process.exit(1)}export{UT as a,xi as b,et as c,qt as d,Xt as e,rt as f,ns as g,oh as h,eg as i,Kk as j,zk as k,ig as l,We as m,ot as n,cg as o,at as p,AE as q,RE as r,Is as s,mC as t,$S as u,So as v,RP as w,EP as x,CP as y,nm as z,t0 as A,DP as B,NP as C,rn as D,Ct as E,on as F,cM as G,Om as H,V0 as I,e_ as J,Bs as K,Wo as L,Ho as M,Ks as N,he as O,If as P,Qs as Q,H$ as R,jf as S,q$ as T,Gf as U,tr as V,pn as W,ir as X,ar as Y,Jf as Z,sa as _,qe as $,Ie as aa,ty as ba,ny as ca,sy as da,ry as ea,Ar as fa,Hy as ga,$a as ha,qy as ia,pT as ja,wN as ka,Aa as la,K2 as ma};
1154
- //# sourceMappingURL=chunk-IS4DA5CR.js.map
1154
+ //# sourceMappingURL=chunk-GAIF3644.js.map