agentix-cli 0.209.1 → 0.209.2

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 (159) hide show
  1. package/dist/{App-IIRTJERA.js → App-SWJJHYRX.js} +2 -2
  2. package/dist/{ChatApp-6KKF4LEH.js → ChatApp-CPUCPJLP.js} +2 -2
  3. package/dist/{absorb-eval-TUJ5NT6O.js → absorb-eval-WKLAV4ZX.js} +2 -2
  4. package/dist/{adapter-OEPJK3RA.js → adapter-XXUKXA5L.js} +2 -2
  5. package/dist/{agent-BOU3OKAD.js → agent-3U23E65W.js} +2 -2
  6. package/dist/{board-dashboard-FSQBTYYV.js → board-dashboard-5BPWMIUP.js} +4 -4
  7. package/dist/{chunk-3S7ZOYP7.js → chunk-2KLR4RWJ.js} +2 -2
  8. package/dist/{chunk-2YKGPMLS.js → chunk-2OW4DTHI.js} +2 -2
  9. package/dist/{chunk-LCVBPN2T.js → chunk-3HT5A67F.js} +98 -109
  10. package/dist/chunk-3HT5A67F.js.map +1 -0
  11. package/dist/{chunk-7PNHK54L.js → chunk-6WU5VEVY.js} +2 -2
  12. package/dist/{chunk-DBODYTBR.js → chunk-7BCGVPF4.js} +2 -2
  13. package/dist/{chunk-OCKOQ3M2.js → chunk-7X4BZ5VS.js} +3 -3
  14. package/dist/{chunk-76H4PAOZ.js → chunk-7YEXKWYP.js} +2 -2
  15. package/dist/{chunk-MM7CVLQ4.js → chunk-B3TH5GYM.js} +2 -2
  16. package/dist/{chunk-YOIZOUSY.js → chunk-BIK7QFDR.js} +2 -2
  17. package/dist/{chunk-SXCRQMNL.js → chunk-CWZ4UN7R.js} +2 -2
  18. package/dist/{chunk-PL5CJYNG.js → chunk-DAT6RZ5Q.js} +2 -2
  19. package/dist/{chunk-7YKVNEQ6.js → chunk-GMP2IB4E.js} +2 -2
  20. package/dist/{chunk-EKQND7TT.js → chunk-IGSZ6IZ7.js} +2 -2
  21. package/dist/{chunk-44CTJ3Q7.js → chunk-K7JD6Y4L.js} +2 -2
  22. package/dist/{chunk-KPYBNLA2.js → chunk-KSO2DLVR.js} +2 -2
  23. package/dist/chunk-KWWBDLE6.js +13 -0
  24. package/dist/chunk-KWWBDLE6.js.map +1 -0
  25. package/dist/chunk-LIY5CHUV.js +4 -0
  26. package/dist/chunk-LIY5CHUV.js.map +1 -0
  27. package/dist/{chunk-6WZV65AF.js → chunk-LW6UWMN6.js} +2 -2
  28. package/dist/{chunk-EDWOZ54V.js → chunk-MOA6SIUK.js} +2 -2
  29. package/dist/{chunk-TQSU3X3J.js → chunk-NBIOOD7J.js} +2 -2
  30. package/dist/{chunk-PB6WBFNR.js → chunk-ORBWUTVG.js} +2 -2
  31. package/dist/{chunk-D2FURI7U.js → chunk-QZ5HG3G5.js} +2 -2
  32. package/dist/{chunk-G72NZCOM.js → chunk-RAZKIONL.js} +2 -2
  33. package/dist/{chunk-UXOKTRDR.js → chunk-RPRJT4EH.js} +2 -2
  34. package/dist/{chunk-LS6COERI.js → chunk-S6HKRVBX.js} +2 -2
  35. package/dist/{chunk-ROLSAEXB.js → chunk-SJMVSADX.js} +2 -2
  36. package/dist/{chunk-R6O45GIS.js → chunk-VIC4Q4HD.js} +2 -2
  37. package/dist/{chunk-T2P6QX4W.js → chunk-VYZ4X65I.js} +2 -2
  38. package/dist/{chunk-ZLYZBZ6P.js → chunk-XMPJV6WS.js} +2 -2
  39. package/dist/{chunk-PLIG3TGT.js → chunk-XWXQGOZR.js} +2 -2
  40. package/dist/{chunk-YXJV4ACW.js → chunk-Y2GFVSLP.js} +6 -6
  41. package/dist/{chunk-KT4CZ7GY.js → chunk-YFN5DE56.js} +3 -3
  42. package/dist/{chunk-KT4CZ7GY.js.map → chunk-YFN5DE56.js.map} +1 -1
  43. package/dist/cli.js +1 -1
  44. package/dist/client-NG226UN4.js +2 -0
  45. package/dist/{config-LLC2SVQY.js → config-BFWKCNWV.js} +2 -2
  46. package/dist/config-mutate-Z3WK32EO.js +2 -0
  47. package/dist/config-mutator-TZRAR5GG.js +2 -0
  48. package/dist/{contributions-PJ56BN7H.js → contributions-4HEMQ3JO.js} +2 -2
  49. package/dist/decision-approvals-NJS2ARAF.js +2 -0
  50. package/dist/{doctor-GUOMJIP2.js → doctor-RBPFWIQJ.js} +2 -2
  51. package/dist/{follow-up-tool-WJDVBIKK.js → follow-up-tool-M6NPAVCR.js} +2 -2
  52. package/dist/hub-RNAZKK6J.js +2 -0
  53. package/dist/index.d.ts +23 -0
  54. package/dist/index.js +1 -1
  55. package/dist/index.js.map +1 -1
  56. package/dist/{org-tool-DSNS2U6J.js → org-tool-WKGZVVTS.js} +2 -2
  57. package/dist/owner-decisions-D3MBTX4D.js +2 -0
  58. package/dist/{program-TFUYZJXY.js → program-OBQZUXYI.js} +266 -264
  59. package/dist/{program-TFUYZJXY.js.map → program-OBQZUXYI.js.map} +1 -1
  60. package/dist/{promote-JFNEREPV.js → promote-DMPFCAC3.js} +2 -2
  61. package/dist/push-bridge-T5HZZRA2.js +1 -1
  62. package/dist/{query-AZV6567L.js → query-KL7IAGDI.js} +2 -2
  63. package/dist/{query-settings-NVR6KLT6.js → query-settings-ASNC2APT.js} +2 -2
  64. package/dist/registry-YOZ2J3I5.js +2 -0
  65. package/dist/{request-planner-63YQLEPP.js → request-planner-4GT4JGV2.js} +2 -2
  66. package/dist/{review-candidates-MMCISAK2.js → review-candidates-FHXSOGXE.js} +2 -2
  67. package/dist/routing-73DPZ65Q.js +2 -0
  68. package/dist/schedule-tool-XTEBWOCZ.js +2 -0
  69. package/dist/scheduler-C7OK3NCA.js +2 -0
  70. package/dist/{seat-JXZWBSGZ.js → seat-SMBKX2K7.js} +2 -2
  71. package/dist/{select-FSV56KVJ.js → select-NPU6TCWK.js} +2 -2
  72. package/dist/self-HICJTWYO.js +2 -0
  73. package/dist/{set-enabled-53DEYHY3.js → set-enabled-CB5HS7PG.js} +2 -2
  74. package/dist/{sprint-tool-PYRQIJKM.js → sprint-tool-J2354376.js} +2 -2
  75. package/dist/{tool-O73Q2WWD.js → tool-LW5PURCD.js} +2 -2
  76. package/dist/{tool-YEH3GUG6.js → tool-NXBLFMPT.js} +2 -2
  77. package/dist/{tool-4N5XR4XV.js → tool-OAEBT36R.js} +2 -2
  78. package/dist/{tool-JKDVJJD4.js → tool-TVKMQB3M.js} +2 -2
  79. package/dist/wiki-XJZI4D7Z.js +2 -0
  80. package/dist/wiki-XJZI4D7Z.js.map +1 -0
  81. package/dist/wiki-enrich-M7C5UVI7.js +2 -0
  82. package/dist/wiki-enrich-M7C5UVI7.js.map +1 -0
  83. package/dist/workspace-setup-GTSXWYU4.js +1 -1
  84. package/package.json +1 -1
  85. package/dist/chunk-LCVBPN2T.js.map +0 -1
  86. package/dist/client-MAH6EO3E.js +0 -2
  87. package/dist/config-mutate-2AGZLP25.js +0 -2
  88. package/dist/config-mutator-REAOL7IJ.js +0 -2
  89. package/dist/hub-YOXHLMFE.js +0 -2
  90. package/dist/registry-FE6NJMV3.js +0 -2
  91. package/dist/routing-MLJJ3R3V.js +0 -2
  92. package/dist/schedule-tool-TVM4RJ35.js +0 -2
  93. package/dist/scheduler-S3KOAAFU.js +0 -2
  94. package/dist/self-CICDOU3F.js +0 -2
  95. package/dist/wiki-GP52MJ6Y.js +0 -2
  96. package/dist/wiki-enrich-M7YDGFIY.js +0 -2
  97. /package/dist/{App-IIRTJERA.js.map → App-SWJJHYRX.js.map} +0 -0
  98. /package/dist/{ChatApp-6KKF4LEH.js.map → ChatApp-CPUCPJLP.js.map} +0 -0
  99. /package/dist/{absorb-eval-TUJ5NT6O.js.map → absorb-eval-WKLAV4ZX.js.map} +0 -0
  100. /package/dist/{adapter-OEPJK3RA.js.map → adapter-XXUKXA5L.js.map} +0 -0
  101. /package/dist/{agent-BOU3OKAD.js.map → agent-3U23E65W.js.map} +0 -0
  102. /package/dist/{board-dashboard-FSQBTYYV.js.map → board-dashboard-5BPWMIUP.js.map} +0 -0
  103. /package/dist/{chunk-3S7ZOYP7.js.map → chunk-2KLR4RWJ.js.map} +0 -0
  104. /package/dist/{chunk-2YKGPMLS.js.map → chunk-2OW4DTHI.js.map} +0 -0
  105. /package/dist/{chunk-7PNHK54L.js.map → chunk-6WU5VEVY.js.map} +0 -0
  106. /package/dist/{chunk-DBODYTBR.js.map → chunk-7BCGVPF4.js.map} +0 -0
  107. /package/dist/{chunk-OCKOQ3M2.js.map → chunk-7X4BZ5VS.js.map} +0 -0
  108. /package/dist/{chunk-76H4PAOZ.js.map → chunk-7YEXKWYP.js.map} +0 -0
  109. /package/dist/{chunk-MM7CVLQ4.js.map → chunk-B3TH5GYM.js.map} +0 -0
  110. /package/dist/{chunk-YOIZOUSY.js.map → chunk-BIK7QFDR.js.map} +0 -0
  111. /package/dist/{chunk-SXCRQMNL.js.map → chunk-CWZ4UN7R.js.map} +0 -0
  112. /package/dist/{chunk-PL5CJYNG.js.map → chunk-DAT6RZ5Q.js.map} +0 -0
  113. /package/dist/{chunk-7YKVNEQ6.js.map → chunk-GMP2IB4E.js.map} +0 -0
  114. /package/dist/{chunk-EKQND7TT.js.map → chunk-IGSZ6IZ7.js.map} +0 -0
  115. /package/dist/{chunk-44CTJ3Q7.js.map → chunk-K7JD6Y4L.js.map} +0 -0
  116. /package/dist/{chunk-KPYBNLA2.js.map → chunk-KSO2DLVR.js.map} +0 -0
  117. /package/dist/{chunk-6WZV65AF.js.map → chunk-LW6UWMN6.js.map} +0 -0
  118. /package/dist/{chunk-EDWOZ54V.js.map → chunk-MOA6SIUK.js.map} +0 -0
  119. /package/dist/{chunk-TQSU3X3J.js.map → chunk-NBIOOD7J.js.map} +0 -0
  120. /package/dist/{chunk-PB6WBFNR.js.map → chunk-ORBWUTVG.js.map} +0 -0
  121. /package/dist/{chunk-D2FURI7U.js.map → chunk-QZ5HG3G5.js.map} +0 -0
  122. /package/dist/{chunk-G72NZCOM.js.map → chunk-RAZKIONL.js.map} +0 -0
  123. /package/dist/{chunk-UXOKTRDR.js.map → chunk-RPRJT4EH.js.map} +0 -0
  124. /package/dist/{chunk-LS6COERI.js.map → chunk-S6HKRVBX.js.map} +0 -0
  125. /package/dist/{chunk-ROLSAEXB.js.map → chunk-SJMVSADX.js.map} +0 -0
  126. /package/dist/{chunk-R6O45GIS.js.map → chunk-VIC4Q4HD.js.map} +0 -0
  127. /package/dist/{chunk-T2P6QX4W.js.map → chunk-VYZ4X65I.js.map} +0 -0
  128. /package/dist/{chunk-ZLYZBZ6P.js.map → chunk-XMPJV6WS.js.map} +0 -0
  129. /package/dist/{chunk-PLIG3TGT.js.map → chunk-XWXQGOZR.js.map} +0 -0
  130. /package/dist/{chunk-YXJV4ACW.js.map → chunk-Y2GFVSLP.js.map} +0 -0
  131. /package/dist/{client-MAH6EO3E.js.map → client-NG226UN4.js.map} +0 -0
  132. /package/dist/{config-LLC2SVQY.js.map → config-BFWKCNWV.js.map} +0 -0
  133. /package/dist/{config-mutate-2AGZLP25.js.map → config-mutate-Z3WK32EO.js.map} +0 -0
  134. /package/dist/{config-mutator-REAOL7IJ.js.map → config-mutator-TZRAR5GG.js.map} +0 -0
  135. /package/dist/{contributions-PJ56BN7H.js.map → contributions-4HEMQ3JO.js.map} +0 -0
  136. /package/dist/{doctor-GUOMJIP2.js.map → decision-approvals-NJS2ARAF.js.map} +0 -0
  137. /package/dist/{hub-YOXHLMFE.js.map → doctor-RBPFWIQJ.js.map} +0 -0
  138. /package/dist/{follow-up-tool-WJDVBIKK.js.map → follow-up-tool-M6NPAVCR.js.map} +0 -0
  139. /package/dist/{promote-JFNEREPV.js.map → hub-RNAZKK6J.js.map} +0 -0
  140. /package/dist/{org-tool-DSNS2U6J.js.map → org-tool-WKGZVVTS.js.map} +0 -0
  141. /package/dist/{query-AZV6567L.js.map → owner-decisions-D3MBTX4D.js.map} +0 -0
  142. /package/dist/{registry-FE6NJMV3.js.map → promote-DMPFCAC3.js.map} +0 -0
  143. /package/dist/{routing-MLJJ3R3V.js.map → query-KL7IAGDI.js.map} +0 -0
  144. /package/dist/{query-settings-NVR6KLT6.js.map → query-settings-ASNC2APT.js.map} +0 -0
  145. /package/dist/{schedule-tool-TVM4RJ35.js.map → registry-YOZ2J3I5.js.map} +0 -0
  146. /package/dist/{request-planner-63YQLEPP.js.map → request-planner-4GT4JGV2.js.map} +0 -0
  147. /package/dist/{review-candidates-MMCISAK2.js.map → review-candidates-FHXSOGXE.js.map} +0 -0
  148. /package/dist/{scheduler-S3KOAAFU.js.map → routing-73DPZ65Q.js.map} +0 -0
  149. /package/dist/{seat-JXZWBSGZ.js.map → schedule-tool-XTEBWOCZ.js.map} +0 -0
  150. /package/dist/{self-CICDOU3F.js.map → scheduler-C7OK3NCA.js.map} +0 -0
  151. /package/dist/{wiki-GP52MJ6Y.js.map → seat-SMBKX2K7.js.map} +0 -0
  152. /package/dist/{select-FSV56KVJ.js.map → select-NPU6TCWK.js.map} +0 -0
  153. /package/dist/{wiki-enrich-M7YDGFIY.js.map → self-HICJTWYO.js.map} +0 -0
  154. /package/dist/{set-enabled-53DEYHY3.js.map → set-enabled-CB5HS7PG.js.map} +0 -0
  155. /package/dist/{sprint-tool-PYRQIJKM.js.map → sprint-tool-J2354376.js.map} +0 -0
  156. /package/dist/{tool-O73Q2WWD.js.map → tool-LW5PURCD.js.map} +0 -0
  157. /package/dist/{tool-YEH3GUG6.js.map → tool-NXBLFMPT.js.map} +0 -0
  158. /package/dist/{tool-4N5XR4XV.js.map → tool-OAEBT36R.js.map} +0 -0
  159. /package/dist/{tool-JKDVJJD4.js.map → tool-TVKMQB3M.js.map} +0 -0
@@ -1,68 +1,68 @@
1
- import{Ba as Eo,Da as Oo,G as bo,N as Ut,O as xo,V as Ht,X as So,a as to,b as no,d as Nn,f as We,ha as Io,i as mo,ia as To,j as fo,ja as ko,k as Bt,la as vo,ma as Ao,n as Ft,na as $o,oa as Co,q as ho,r as yo,ra as Mo,sa as Ro,v as wo,va as _o,wa as Po}from"./chunk-UXOKTRDR.js";import{b as so}from"./chunk-MEFPXHQJ.js";import{a as eo}from"./chunk-VJVXEVZ7.js";import{b as oo,d as Un,e as ao,f as st,i as co}from"./chunk-MM7CVLQ4.js";import{a as Bn,b as ro}from"./chunk-J3SOEFRE.js";import{a as Fn,b as io}from"./chunk-SIU6STB2.js";import{e as uo,i as lo,j as go,k as po}from"./chunk-X5C5W3E4.js";import{a as Hn}from"./chunk-W4YR2RO2.js";import{h as Zr,i as Vr}from"./chunk-BE64IJWM.js";import{a as Or,c as Dr}from"./chunk-MYVHVJWZ.js";import{a as Lr,b as Nr,c as Br,d as Fr,l as jr,q as Wr}from"./chunk-3AHYZLGE.js";import{a as Ur,b as Hr}from"./chunk-LY4G7PCW.js";import{a as qr,b as Jr}from"./chunk-DPG6VHPX.js";import{c as Gr}from"./chunk-BERWTVG2.js";import{a as Kr,b as Ln}from"./chunk-A7JSRDJL.js";import{d as zr}from"./chunk-HPRLRD4P.js";import{a as Yr}from"./chunk-SXCRQMNL.js";import{g as Qr,h as Xr}from"./chunk-ROLSAEXB.js";import{c as fr,d as hr}from"./chunk-AHWWJ7AF.js";import{c as Rr,f as _r}from"./chunk-LS6COERI.js";import{s as Cr,v as Nt,w as Mr,y as Se,z as Dn}from"./chunk-6WZV65AF.js";import{a as nt,b as He,f as Lt}from"./chunk-72SZI2UW.js";import{a as Ue,b as _n}from"./chunk-FCPTN6NF.js";import{d as Er}from"./chunk-7IW25T4K.js";import{e as je,h as Pr,i as _e}from"./chunk-QUFIUXMQ.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{Ma as Sr,Pa as On,Ra as Rc,Sb as Pc,Ua as Ir,Za as _c,db as Tr,eb as Dt,fb as kr,gb as tt,hb as vr,ib as Ar,ob as $r}from"./chunk-KT4CZ7GY.js";import{f as xr,g as et,h as Cc}from"./chunk-KEUW6YLL.js";import{j as En,r as Mc}from"./chunk-UEEB3UTU.js";import{a as yr,b as me,c as wr,d as br,e as Pn}from"./chunk-VQRY4IDI.js";Dn();Lt();var jt="tool-set",Do=["answer","code","full"],Lo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Ec=.1;function Bo(n){return{task:No(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:No(n.agentPrompt,600)}:{}}}var Fo={bundle:He({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 Uo(n,e=Ec){let s=n?.bundle?.probabilities;if(!s)return"full";let r=jn(s.answer),o=jn(s.code),i=jn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Ho(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Lo.answer.includes(t))?"answer":e.every(t=>Lo.code.includes(t))?"code":"full"}function jo(n,e){return Do.indexOf(n)<Do.indexOf(e)}function jn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function No(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Wo=!1;function qo(n,e){let t=Nt(jt);if(t!=="off")return t==="active"&&!Wo&&(Wo=!0,e(`[decisions] seat "${jt}" is set to active, but only shadow is built: it records and changes nothing`)),Se(jt,Bo(n),Fo,{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=Uo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Go(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Ho(r);Mr(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}`+(jo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Oc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ko(n,e){let t=Oc(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 Wn(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)`}Dn();Lt();var Jo="session-continuity",zo={continues:nt("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:nt("Does the new request refer to something stated earlier in the conversation?")};function Qo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:qn(n.message,1200),previousRequest:n.previousMessage?qn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>qn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Xo(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 qn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function Yo(n,e){let t=Er(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function Zm(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=Yo(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function Vm(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:Yo(n,e).token}var Zo=null;function ef(n){Zo=n}function Wt(n,e){let t;try{t=Zo?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as Yt}from"execa";import{spawn as Dc}from"node:child_process";import{createHash as Lc}from"node:crypto";import{createInterface as Nc}from"node:readline";var Ie=class extends Error{},Bc=n=>Dc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),Gn=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(),Nc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
- `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Kn=class{constructor(e=Bc,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=Lc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[E])=>x.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Ie("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,E])=>!E.connection.busy);if(!x)throw new Ie("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new Gn(e,this.launchProcess)}}catch{throw new Ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=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 x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let H=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=M.delta,e.onDelta?.(M.delta,d)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return H.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await H,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Ie(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Vo=new Kn;import{execFile as iu}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as yi,readFileSync as wi,rmSync as bi}from"fs";import{join as Qt}from"path";import{tmpdir as xi}from"os";function qt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Gt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Kt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var Pe=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var ei=null;function rt(){return ei}function uf(n){ei=n}function fe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Fc(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 qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},ti=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=fe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Fc(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 qe(`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 qe(`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=fe(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=fe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let d=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);d<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:d})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let d=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${d}`),i.kill(`closed idle (${d})`).catch(c=>{this.cfg.log(`[process-registry] closing ${o} failed: ${c?.message||c}`)})}return r.map(o=>o.handle.key)}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();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=fe(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,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let d=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${d})`),this.cfg.log(`[process-registry] killed stale ${t}${d}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let d=this.handleWorkspace.get(t);if(d){let c=null;try{c=this.cfg.currentWorkspaceHash(s.key,d)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(c!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=c??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Uc}from"child_process";import{randomUUID as Hc}from"crypto";import{existsSync as jc,readFileSync as Wc}from"fs";import{resolve as qc}from"path";function Gc(n){let e=qc(n,"CLAUDE.md");if(!jc(e))return null;try{let t=Wc(e,"utf8");return Wr(t)}catch{return null}}var Kc=20*60*1e3,Jc=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function zc(n,e){return n.AGENTX_AGENT_ID=e.agentId,Wt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var ni=class{constructor(e={}){this.opts=e}spawn(e,t){return new Jn(e,t,this.opts)}},Jn=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=Uc(r,o,{cwd:t.workspace,env:_e(zc({...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:Gc(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new Pe;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),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=Hc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
- `);let d=e.deadlineMs??Kc,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new ot(d)),l=!1,p=null;try{for(;;){let f=c-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{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)},Jc);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
- `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};Pn();Mc();_n();import{resolve as si,join as ri}from"path";var Qc=4e3;function Jt(n){try{let e=ri(si(n.root),".agentx","db.sqlite"),t=En({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ue(),r=n.input.command?n.input.command.slice(0,Qc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
1
+ import{Ba as Do,Da as Lo,G as So,N as Ut,O as Io,V as Ht,X as To,a as to,b as no,d as Bn,f as We,ha as ko,i as ho,ia as vo,j as yo,ja as Ao,k as Bt,la as $o,ma as Co,n as Ft,na as Mo,oa as Ro,q as wo,r as bo,ra as _o,sa as Po,v as xo,va as Eo,wa as Oo}from"./chunk-RPRJT4EH.js";import{b as so}from"./chunk-MEFPXHQJ.js";import{a as jn}from"./chunk-W4YR2RO2.js";import{a as eo}from"./chunk-VJVXEVZ7.js";import{b as oo,d as Hn,e as ao,f as st,i as co}from"./chunk-B3TH5GYM.js";import{a as Fn,b as ro}from"./chunk-J3SOEFRE.js";import{a as Un,b as io}from"./chunk-SIU6STB2.js";import{e as uo,i as lo,j as go,k as po}from"./chunk-X5C5W3E4.js";import{d as mo}from"./chunk-KWWBDLE6.js";import{f as fo}from"./chunk-LIY5CHUV.js";import{h as Zr,i as Vr}from"./chunk-BE64IJWM.js";import{a as Or,c as Dr}from"./chunk-MYVHVJWZ.js";import{a as Lr,b as Nr,c as Br,d as Fr,l as jr,q as Wr}from"./chunk-3AHYZLGE.js";import{a as Ur,b as Hr}from"./chunk-LY4G7PCW.js";import{a as qr,b as Jr}from"./chunk-DPG6VHPX.js";import{c as Gr}from"./chunk-BERWTVG2.js";import{a as Kr,b as Nn}from"./chunk-A7JSRDJL.js";import{d as zr}from"./chunk-HPRLRD4P.js";import{a as Yr}from"./chunk-CWZ4UN7R.js";import{g as Qr,h as Xr}from"./chunk-SJMVSADX.js";import{c as fr,d as hr}from"./chunk-AHWWJ7AF.js";import{c as Rr,f as _r}from"./chunk-S6HKRVBX.js";import{s as Cr,v as Nt,w as Mr,y as Se,z as Ln}from"./chunk-LW6UWMN6.js";import{a as nt,b as He,f as Lt}from"./chunk-72SZI2UW.js";import{a as Ue,b as Pn}from"./chunk-FCPTN6NF.js";import{d as Er}from"./chunk-7IW25T4K.js";import{e as je,h as Pr,i as _e}from"./chunk-QUFIUXMQ.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{Ma as Sr,Pa as Dn,Ra as _c,Sb as Ec,Ua as Ir,Za as Pc,db as Tr,eb as Dt,fb as kr,gb as tt,hb as vr,ib as Ar,ob as $r}from"./chunk-YFN5DE56.js";import{f as xr,g as et,h as Mc}from"./chunk-KEUW6YLL.js";import{j as On,r as Rc}from"./chunk-UEEB3UTU.js";import{a as yr,b as me,c as wr,d as br,e as En}from"./chunk-VQRY4IDI.js";Ln();Lt();var jt="tool-set",No=["answer","code","full"],Bo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Oc=.1;function Uo(n){return{task:Fo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Fo(n.agentPrompt,600)}:{}}}var Ho={bundle:He({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 jo(n,e=Oc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Wn(s.answer),o=Wn(s.code),i=Wn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Wo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Bo.answer.includes(t))?"answer":e.every(t=>Bo.code.includes(t))?"code":"full"}function qo(n,e){return No.indexOf(n)<No.indexOf(e)}function Wn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Fo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Go=!1;function Ko(n,e){let t=Nt(jt);if(t!=="off")return t==="active"&&!Go&&(Go=!0,e(`[decisions] seat "${jt}" is set to active, but only shadow is built: it records and changes nothing`)),Se(jt,Uo(n),Ho,{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=jo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Jo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Wo(r);Mr(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}`+(qo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Dc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function zo(n,e){let t=Dc(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 qn(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)`}Ln();Lt();var Qo="session-continuity",Xo={continues:nt("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:nt("Does the new request refer to something stated earlier in the conversation?")};function Yo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Gn(n.message,1200),previousRequest:n.previousMessage?Gn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Gn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Zo(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 Gn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function Vo(n,e){let t=Er(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function Zm(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=Vo(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function Vm(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:Vo(n,e).token}var ei=null;function ef(n){ei=n}function Wt(n,e){let t;try{t=ei?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as Yt}from"execa";import{spawn as Lc}from"node:child_process";import{createHash as Nc}from"node:crypto";import{createInterface as Bc}from"node:readline";var Ie=class extends Error{},Fc=n=>Lc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),Kn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Bc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
+ `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Jn=class{constructor(e=Fc,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=Nc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[E])=>x.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Ie("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,E])=>!E.connection.busy);if(!x)throw new Ie("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new Kn(e,this.launchProcess)}}catch{throw new Ie("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,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=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 x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let H=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return H.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await H,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Ie(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ti=new Jn;import{execFile as au}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as bi,readFileSync as xi,rmSync as Si}from"fs";import{join as Qt}from"path";import{tmpdir as Ii}from"os";function qt(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 Gt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Kt(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 Pe=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var ni=null;function rt(){return ni}function uf(n){ni=n}function fe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Uc(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 qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},si=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=fe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Uc(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 qe(`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 qe(`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=fe(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=fe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}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();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=fe(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,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Hc}from"child_process";import{randomUUID as jc}from"crypto";import{existsSync as Wc,readFileSync as qc}from"fs";import{resolve as Gc}from"path";function Kc(n){let e=Gc(n,"CLAUDE.md");if(!Wc(e))return null;try{let t=qc(e,"utf8");return Wr(t)}catch{return null}}var Jc=20*60*1e3,zc=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Qc(n,e){return n.AGENTX_AGENT_ID=e.agentId,Wt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var ri=class{constructor(e={}){this.opts=e}spawn(e,t){return new zn(e,t,this.opts)}},zn=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=Hc(r,o,{cwd:t.workspace,env:_e(Qc({...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:Kc(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();background=new Pe;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),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=jc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
+ `);let c=e.deadlineMs??Jc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new ot(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{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)},zc);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
+ `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}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"}}};En();Rc();Pn();import{resolve as oi,join as ii}from"path";var Xc=4e3;function Jt(n){try{let e=ii(oi(n.root),".agentx","db.sqlite"),t=On({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ue(),r=n.input.command?n.input.command.slice(0,Xc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
5
5
  (id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
6
6
  verdict, effective_action, mode, severity, approver, ms)
7
7
  VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
8
8
  @verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:s,ts:Date.now(),agent_id:n.input.agentId??null,task_id:n.taskId??null,tool:n.input.tool,command:r,resolved_target:n.verdict.resolvedTarget,matched_rule:n.verdict.ruleId,verdict:n.verdict.action,effective_action:n.verdict.effectiveAction,mode:n.mode,severity:n.verdict.severity,approver:n.approver??null,ms:n.ms??null}),s}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
9
- `),null}}function vf(n){let e=ri(si(n.root),".agentx","db.sqlite"),t=En({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}Pn();var Xc=50,Yc=6*60*60*1e3,zt=null,Ge=new Map;function Mf(n){zt=n===null?null:String(n)}function ii(){return zt}function Zc(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function ai(n,e,t){if(!me(n))return{args:[]};if(!zt)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Zc(zt,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function di(n,e){return!me(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Vc(n){for(let[e,t]of Ge)n-t.at>Yc&&Ge.delete(e)}function eu(n,e){let t=Date.now();Vc(t);let s=Ge.get(n)??{at:t,blocks:[]};s.blocks.length<Xc&&s.blocks.push(e),s.at=t,Ge.set(n,s)}function ci(n){if(!n)return[];let e=Ge.get(n);return Ge.delete(n),e?.blocks??[]}function tu(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`[agentx-autonomy] read-only call allowed at autonomy "${n}"`}})}function oi(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function Rf(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0,o=typeof n.tool_input?.action=="string"?n.tool_input.action:void 0;try{let i=yr.safeParse(e.level),a=i.success?wr(i.data,{tool:t,command:s,filePath:r,action:o}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(a.allowed)return{stdout:i.success&&i.data==="report"?tu(i.data):"",blocked:null};let d=i.success?i.data:"report",c=a.ruleId??"autonomy",u=a.reason??"blocked",l={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:c,reason:u},p={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:u,resolvedTarget:null};return Jt({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:p,mode:"enforce",taskId:e.taskId??null}),e.taskId&&eu(e.taskId,l),{stdout:oi(`[agentx-autonomy] Blocked: this routine runs at autonomy "${d}" and ${u} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(i){return{stdout:oi(`[agentx-autonomy] Guard error (fail-closed): ${i?.message??i}`),blocked:null}}}Ar();var nu=6*60*60*1e3,at=new Map;function su(n){for(let[e,t]of at)n-t.at>nu&&at.delete(e)}function ui(n,e){let t=Date.now();su(t),at.set(n,{at:t,limits:e})}function li(n){at.delete(n)}function ru(n,e,t){let s=new URLSearchParams({person:"1",task:e,...t?{agent:t}:{}}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function gi(n,e,t){let s=ii();if(!s)return{error:"this person's tool and skill limits cannot be enforced: guard hook endpoint is not configured"};let r={matcher:"*",hooks:[{type:"command",command:ru(s,e,t),timeout:15}]},o=[...n],i=o.indexOf("--settings");if(i===-1)return o.push("--settings",JSON.stringify({hooks:{PreToolUse:[r]}})),{args:o};let a=JSON.parse(o[i+1]);return a.hooks=a.hooks??{},a.hooks.PreToolUse=[...a.hooks.PreToolUse??[],r],o[i+1]=JSON.stringify(a),{args:o}}function pi(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function zn(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function ou(n,e,t){if(n.tools.some(s=>tt(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>tt(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function Df(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?at.get(e.taskId):void 0;if(!r)return{stdout:zn("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=ou(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,d={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Jt({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:d,mode:"enforce",taskId:e.taskId??null}),{stdout:zn(`[agentx-people] Blocked: ${a} here (set by the owner). Do not work around it. Finish what you can without it and say in your answer what was not done and why.`),blocked:{personId:o.personId,tool:t,skill:i.skill,reason:a}}}catch(r){return{stdout:zn(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var au=5e3;function Z(n){let e=qt(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
- `)}return{error:Gt(e),errorKind:e.kind}}function Si(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Xt(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function mi(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function Te(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let d of r.peers){let c=d.handle?` (mention: ${d.handle})`:"",u=d.role?` \u2014 ${d.role}`:"";o.push(`\u2022 ${d.name}${c}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
9
+ `),null}}function vf(n){let e=ii(oi(n.root),".agentx","db.sqlite"),t=On({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}En();var Yc=50,Zc=6*60*60*1e3,zt=null,Ge=new Map;function Mf(n){zt=n===null?null:String(n)}function di(){return zt}function Vc(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function ci(n,e,t){if(!me(n))return{args:[]};if(!zt)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Vc(zt,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function ui(n,e){return!me(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function eu(n){for(let[e,t]of Ge)n-t.at>Zc&&Ge.delete(e)}function tu(n,e){let t=Date.now();eu(t);let s=Ge.get(n)??{at:t,blocks:[]};s.blocks.length<Yc&&s.blocks.push(e),s.at=t,Ge.set(n,s)}function li(n){if(!n)return[];let e=Ge.get(n);return Ge.delete(n),e?.blocks??[]}function nu(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`[agentx-autonomy] read-only call allowed at autonomy "${n}"`}})}function ai(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function Rf(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0,o=typeof n.tool_input?.action=="string"?n.tool_input.action:void 0;try{let i=yr.safeParse(e.level),a=i.success?wr(i.data,{tool:t,command:s,filePath:r,action:o}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(a.allowed)return{stdout:i.success&&i.data==="report"?nu(i.data):"",blocked:null};let c=i.success?i.data:"report",d=a.ruleId??"autonomy",u=a.reason??"blocked",l={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:d,reason:u},p={matched:!0,action:"deny",effectiveAction:"deny",ruleId:d,severity:"high",message:u,resolvedTarget:null};return Jt({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:p,mode:"enforce",taskId:e.taskId??null}),e.taskId&&tu(e.taskId,l),{stdout:ai(`[agentx-autonomy] Blocked: this routine runs at autonomy "${c}" and ${u} (rule: ${d}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(i){return{stdout:ai(`[agentx-autonomy] Guard error (fail-closed): ${i?.message??i}`),blocked:null}}}Ar();var su=6*60*60*1e3,at=new Map;function ru(n){for(let[e,t]of at)n-t.at>su&&at.delete(e)}function gi(n,e){let t=Date.now();ru(t),at.set(n,{at:t,limits:e})}function pi(n){at.delete(n)}function ou(n,e,t){let s=new URLSearchParams({person:"1",task:e,...t?{agent:t}:{}}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function mi(n,e,t){let s=di();if(!s)return{error:"this person's tool and skill limits cannot be enforced: guard hook endpoint is not configured"};let r={matcher:"*",hooks:[{type:"command",command:ou(s,e,t),timeout:15}]},o=[...n],i=o.indexOf("--settings");if(i===-1)return o.push("--settings",JSON.stringify({hooks:{PreToolUse:[r]}})),{args:o};let a=JSON.parse(o[i+1]);return a.hooks=a.hooks??{},a.hooks.PreToolUse=[...a.hooks.PreToolUse??[],r],o[i+1]=JSON.stringify(a),{args:o}}function fi(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function Qn(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function iu(n,e,t){if(n.tools.some(s=>tt(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>tt(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function Df(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?at.get(e.taskId):void 0;if(!r)return{stdout:Qn("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=iu(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,c={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Jt({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:c,mode:"enforce",taskId:e.taskId??null}),{stdout:Qn(`[agentx-people] Blocked: ${a} here (set by the owner). Do not work around it. Finish what you can without it and say in your answer what was not done and why.`),blocked:{personId:o.personId,tool:t,skill:i.skill,reason:a}}}catch(r){return{stdout:Qn(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var du=5e3;function Z(n){let e=qt(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
+ `)}return{error:Gt(e),errorKind:e.kind}}function Ti(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Xt(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function hi(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function Te(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
11
11
  `))}return e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
12
- `)}function Ii(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let d=r||n.model;return d&&a.push("--model",d),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Qn(n,e){return!e||e.trim().length===0?n:`[System]
12
+ `)}function ki(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let c=r||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Xn(n,e){return!e||e.trim().length===0?n:`[System]
13
13
  ${e.trim()}
14
14
 
15
15
  [User]
16
- ${n}`}function du(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Qn(e,s)),o}function cu(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function fi(n){return JSON.stringify(n)}function Ti(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${fi(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(fi).join(",")}]`]}function ki(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Ti()),i||a.push("--color","never");let d=s||n.model;return d&&a.push("--model",d),n.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Qn(e,r)),a}function Zt(n,e){let t=je(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),ct(t,e)}function ct(n,e){return n.AGENTX_AGENT_ID=e.agentId,Wt(n,e.agentId),n.AGENTX_GUARD="required",e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function vi(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),n}function Vt(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function uu(n,e){let t=Zt(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:Ur(a)}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...s,mcp:r}),t}function lu(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function he(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Xn(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object"){let s=he(t.cached_input_tokens,t.cachedInputTokens),r=he(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:he(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:he(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:he(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Xn(s,e+1);if(r)return r}}function Ai(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function Yn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=Yn(t,e+1);if(s)return s}}}function gu(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
17
- `))if(i.trim())try{let a=JSON.parse(i);t=Xn(a)||t,s=Ai(a)||s,r=Yn(a)||r,o=$i(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function $i(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return hi(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return hi(e)}}}function hi(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function pu(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function Zn(n,e,t,s,r){let o=pu(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
18
- `)}function mu(n){try{let e=JSON.parse(n);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function fu(n){try{let e=JSON.parse(n),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||Kt(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function Ci(n,e,t,s,r){let o=Date.now(),i=Te(n,e,t),a=Ri(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=Ii(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(Zn(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:l,stderr:p,exitCode:f,killed:h}=await new Promise(x=>{let E=_e(vi(ct(je(n.workspace),e),e),n.billing),H=!1,b=iu("claude",d,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...E,HOME:E.HOME||"/home/"+(E.USER||"user")}},(_,R,M)=>{x({stdout:R||"",stderr:M||"",exitCode:_?_.code??1:0,killed:H})});if(b.stdin?.end(),r){let _=()=>{H=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{b.kill("SIGTERM")}catch{}setTimeout(()=>{try{b.killed||b.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?_():r.addEventListener("abort",_,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&f!==0){let x,E=Date.now()-o;return f===143&&E<u-au?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(E/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:E}:(f===143?x=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:f==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?x=Si():x=p?.trim()||`Claude Code exited with code ${f}`,{content:"",...Z(x),duration:Date.now()-o})}let y=mu(l);if(y)return{content:"",...Z(y),duration:Date.now()-o};let A=fu(l);return{content:A.text,duration:Date.now()-o,claudeSessionId:A.sessionId,usage:A.usage,numTurns:A.numTurns,costUsd:A.costUsd,billedModel:A.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function Mi(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let d=Te(n,e,s),c=Ri(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let u=Ii(n,d,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...c.args]);Zn(e.agentId,n,e.model,r,"stream");let l="",p="",f="",h=L=>{let N=p&&!f?`
16
+ ${n}`}function cu(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Xn(e,s)),o}function uu(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function yi(n){return JSON.stringify(n)}function vi(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${yi(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(yi).join(",")}]`]}function Ai(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...vi()),i||a.push("--color","never");let c=s||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Xn(e,r)),a}function Zt(n,e){let t=je(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),ct(t,e)}function ct(n,e){return n.AGENTX_AGENT_ID=e.agentId,Wt(n,e.agentId),n.AGENTX_GUARD="required",e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function $i(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),n}function Vt(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function lu(n,e){let t=Zt(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:Ur(a)}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...s,mcp:r}),t}function gu(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function he(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Yn(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object"){let s=he(t.cached_input_tokens,t.cachedInputTokens),r=he(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:he(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:he(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:he(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Yn(s,e+1);if(r)return r}}function Ci(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function Zn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=Zn(t,e+1);if(s)return s}}}function pu(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
17
+ `))if(i.trim())try{let a=JSON.parse(i);t=Yn(a)||t,s=Ci(a)||s,r=Zn(a)||r,o=Mi(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Mi(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return wi(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return wi(e)}}}function wi(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function mu(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function Vn(n,e,t,s,r){let o=mu(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
18
+ `)}function fu(n){try{let e=JSON.parse(n);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function hu(n){try{let e=JSON.parse(n),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||Kt(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function Ri(n,e,t,s,r){let o=Date.now(),i=Te(n,e,t),a=Pi(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=ki(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(Vn(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:l,stderr:p,exitCode:f,killed:h}=await new Promise(x=>{let E=_e($i(ct(je(n.workspace),e),e),n.billing),H=!1,b=au("claude",c,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...E,HOME:E.HOME||"/home/"+(E.USER||"user")}},(_,R,M)=>{x({stdout:R||"",stderr:M||"",exitCode:_?_.code??1:0,killed:H})});if(b.stdin?.end(),r){let _=()=>{H=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{b.kill("SIGTERM")}catch{}setTimeout(()=>{try{b.killed||b.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?_():r.addEventListener("abort",_,{once:!0})}});if(h)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&f!==0){let x,E=Date.now()-o;return f===143&&E<u-du?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(E/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:E}:(f===143?x=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:f==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?x=Ti():x=p?.trim()||`Claude Code exited with code ${f}`,{content:"",...Z(x),duration:Date.now()-o})}let y=fu(l);if(y)return{content:"",...Z(y),duration:Date.now()-o};let A=hu(l);return{content:A.text,duration:Date.now()-o,claudeSessionId:A.sessionId,usage:A.usage,numTurns:A.numTurns,costUsd:A.costUsd,billedModel:A.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function _i(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=Te(n,e,s),d=Pi(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let u=ki(n,c,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...d.args]);Vn(e.agentId,n,e.model,r,"stream");let l="",p="",f="",h=L=>{let N=p&&!f?`
19
19
 
20
20
  `:"";f+=L,l=p+(p?`
21
21
 
22
- `:"")+f,t(N+L,l)},y=new Pe,A=!1,x,E,H,b,_,R,M;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),N=_e(vi(ct(je(n.workspace),e),e),n.billing),j=Yt("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:N,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},J=new Promise(Q=>{q=Q}),$=!1,v;if(i){let Q=()=>{$=!0,v=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{j.kill("SIGTERM")}catch{}setTimeout(()=>{try{j.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?Q():i.addEventListener("abort",Q,{once:!0})}let S="",B=new dt("utf8");j.stdout&&j.stdout.on("data",Q=>{S+=B.write(Q);let re=S.split(`
22
+ `:"")+f,t(N+L,l)},y=new Pe,A=!1,x,E,H,b,_,R,M;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),N=_e($i(ct(je(n.workspace),e),e),n.billing),j=Yt("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:N,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},J=new Promise(Q=>{q=Q}),$=!1,v;if(i){let Q=()=>{$=!0,v=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{j.kill("SIGTERM")}catch{}setTimeout(()=>{try{j.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?Q():i.addEventListener("abort",Q,{once:!0})}let S="",B=new dt("utf8");j.stdout&&j.stdout.on("data",Q=>{S+=B.write(Q);let re=S.split(`
23
23
  `);S=re.pop()||"";for(let oe of re)if(oe.trim())try{let D=JSON.parse(oe);if(o)try{o(D)}catch{}if(D.type==="assistant"&&D.message?.usage){let te=D.message.usage,ne=(te.input_tokens||0)+(te.cache_read_input_tokens||0)+(te.cache_creation_input_tokens||0);ne>0&&(b=ne)}if(D.type==="assistant"&&D.message?.content){for(let te of D.message.content)if(te.type==="text"&&te.text){let ne=te.text.slice(f.length);ne&&h(ne)}}if(D.type==="content_block_delta"&&D.delta?.text&&h(D.delta.text),y.observe(D),D.type==="result"&&D.result){if(D.is_error&&typeof D.result=="string")M=D.result;else{let te=(typeof D.result=="string",D.result);if(typeof te=="string"&&te.length>f.length){let ne=te.slice(f.length);ne&&h(ne)}}D.usage&&(E={inputTokens:D.usage.input_tokens||0,outputTokens:D.usage.output_tokens||0,cacheReadTokens:D.usage.cache_read_input_tokens||0,cacheCreateTokens:D.usage.cache_creation_input_tokens||0}),typeof D.model=="string"?x=D.model:x=Kt(D.modelUsage)||x,typeof D.session_id=="string"&&(H=D.session_id),typeof D.num_turns=="number"&&(_=D.num_turns),typeof D.total_cost_usd=="number"&&(R=D.total_cost_usd)}D.type==="result"&&(y.pending===0?q():(A||process.stderr.write(`[claude-stream] agent=${e.agentId} task=${e.taskId??"?"} turn ended with ${y.pending} background task(s) running; the task stays open until they end
24
24
  `),A=!0,f&&(p=l,f=""))),D.type==="system"&&D.subtype==="init"&&(typeof D.model=="string"&&(x=D.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${D.apiKeySource} version=${D.claude_code_version} model=${D.model} permMode=${D.permissionMode}
25
25
  `))}catch{oe.trim()&&!oe.startsWith("{")&&h(oe+`
26
- `)}});let W=await Iu(j,J),P=B.end();if(P&&(S+=P),$)return{content:"",error:v||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!l&&W.stdout&&(l=typeof W.stdout=="string"?W.stdout:""),W.exitCode!==0&&!l){let Q=typeof W.stderr=="string"?W.stderr:"",re=W,oe;return re.timedOut?oe=`Claude Code timed out after ${Math.round(L/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:re.signal?oe=Q.trim()||`Claude Code killed by signal ${re.signal}`:re.code==="ENOENT"||/ENOENT|spawn claude/i.test((re.shortMessage||"")+" "+Q)?oe=Si():oe=Q.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...Z(oe),duration:Date.now()-a}}return M?{content:"",...Z(M),duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,billedModel:x,claudeSessionId:H}:{content:l,duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,costUsd:R,billedModel:x,claudeSessionId:H}}catch(L){return{content:l||"",...Z(L.message),duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,billedModel:x,claudeSessionId:H}}}async function hu(n,e,t,s){let r=Date.now(),o=Te(n,e,t),i=yi(Qt(xi(),"agentx-codex-")),a=Qt(i,"last-message.txt"),d=ki(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let c=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await Yt("codex",d,{cwd:e.cwd??n.workspace,timeout:c,reject:!1,env:Zt(n,e),extendEnv:!1,stdin:"ignore"}),l=gu(u.stdout);if(u.exitCode!==0||l.apiError){let f=u,h;return f.timedOut?h=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?h=l.apiError:f.signal?h=u.stderr.trim()||`Codex CLI killed by signal ${f.signal}`:f.code==="ENOENT"||/ENOENT|spawn codex/i.test((f.shortMessage||"")+" "+u.stderr)?h=Xt():h=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${f.exitCode??"unknown"}`,{content:"",...Z(h),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let p="";try{p=wi(a,"utf8").trim()}catch{}return p||(p=u.stdout.trim()),{content:p,duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}catch(c){let u=/ENOENT|spawn codex/i.test(c?.message||"")?Xt():c?.message;return{content:"",...Z(u||"Codex CLI failed"),duration:Date.now()-r}}finally{bi(i,{recursive:!0,force:!0})}}async function yu(n,e,t,s,r,o){let i=Date.now(),a=Te(n,e,s),d=yi(Qt(xi(),"agentx-codex-")),c=Qt(d,"last-message.txt"),u=ki(n,a,!0,e.model,e.systemPromptAppend,c,r),l="",p,f,h,y;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),x=Yt("codex",u,{cwd:e.cwd??n.workspace,timeout:A,reject:!1,env:Zt(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let E="",H="",b=!1,_=new dt("utf8"),R=new dt("utf8"),M=Math.min(A,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,N=()=>{L&&clearTimeout(L),L=setTimeout(()=>{b=!0,x.kill("SIGTERM",{forceKillAfterTimeout:5e3})},M)};N(),x.stderr?.on("data",v=>{N(),H+=R.write(v),H.length>16e3&&(H=H.slice(-16e3))}),x.stdout?.on("data",v=>{N(),E+=_.write(v);let S=E.split(`
27
- `);E=S.pop()||"";for(let B of S)if(B.trim())try{let W=JSON.parse(B);if(o)try{o(W)}catch{}p=Xn(W)||p,f=Ai(W)||f,h=Yn(W)||h,y=$i(W)||y;let P=lu(W);if(P&&P!==l){let Q=P.startsWith(l)?P.slice(l.length):P;l=P.startsWith(l)?P:l+P,Q&&t(Q,l)}}catch{l+=B+`
26
+ `)}});let W=await Tu(j,J),P=B.end();if(P&&(S+=P),$)return{content:"",error:v||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!l&&W.stdout&&(l=typeof W.stdout=="string"?W.stdout:""),W.exitCode!==0&&!l){let Q=typeof W.stderr=="string"?W.stderr:"",re=W,oe;return re.timedOut?oe=`Claude Code timed out after ${Math.round(L/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:re.signal?oe=Q.trim()||`Claude Code killed by signal ${re.signal}`:re.code==="ENOENT"||/ENOENT|spawn claude/i.test((re.shortMessage||"")+" "+Q)?oe=Ti():oe=Q.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...Z(oe),duration:Date.now()-a}}return M?{content:"",...Z(M),duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,billedModel:x,claudeSessionId:H}:{content:l,duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,costUsd:R,billedModel:x,claudeSessionId:H}}catch(L){return{content:l||"",...Z(L.message),duration:Date.now()-a,usage:E,contextTokens:b,numTurns:_,billedModel:x,claudeSessionId:H}}}async function yu(n,e,t,s){let r=Date.now(),o=Te(n,e,t),i=bi(Qt(Ii(),"agentx-codex-")),a=Qt(i,"last-message.txt"),c=Ai(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let d=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await Yt("codex",c,{cwd:e.cwd??n.workspace,timeout:d,reject:!1,env:Zt(n,e),extendEnv:!1,stdin:"ignore"}),l=pu(u.stdout);if(u.exitCode!==0||l.apiError){let f=u,h;return f.timedOut?h=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?h=l.apiError:f.signal?h=u.stderr.trim()||`Codex CLI killed by signal ${f.signal}`:f.code==="ENOENT"||/ENOENT|spawn codex/i.test((f.shortMessage||"")+" "+u.stderr)?h=Xt():h=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${f.exitCode??"unknown"}`,{content:"",...Z(h),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let p="";try{p=xi(a,"utf8").trim()}catch{}return p||(p=u.stdout.trim()),{content:p,duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Xt():d?.message;return{content:"",...Z(u||"Codex CLI failed"),duration:Date.now()-r}}finally{Si(i,{recursive:!0,force:!0})}}async function wu(n,e,t,s,r,o){let i=Date.now(),a=Te(n,e,s),c=bi(Qt(Ii(),"agentx-codex-")),d=Qt(c,"last-message.txt"),u=Ai(n,a,!0,e.model,e.systemPromptAppend,d,r),l="",p,f,h,y;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),x=Yt("codex",u,{cwd:e.cwd??n.workspace,timeout:A,reject:!1,env:Zt(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let E="",H="",b=!1,_=new dt("utf8"),R=new dt("utf8"),M=Math.min(A,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,N=()=>{L&&clearTimeout(L),L=setTimeout(()=>{b=!0,x.kill("SIGTERM",{forceKillAfterTimeout:5e3})},M)};N(),x.stderr?.on("data",v=>{N(),H+=R.write(v),H.length>16e3&&(H=H.slice(-16e3))}),x.stdout?.on("data",v=>{N(),E+=_.write(v);let S=E.split(`
27
+ `);E=S.pop()||"";for(let B of S)if(B.trim())try{let W=JSON.parse(B);if(o)try{o(W)}catch{}p=Yn(W)||p,f=Ci(W)||f,h=Zn(W)||h,y=Mi(W)||y;let P=gu(W);if(P&&P!==l){let Q=P.startsWith(l)?P.slice(l.length):P;l=P.startsWith(l)?P:l+P,Q&&t(Q,l)}}catch{l+=B+`
28
28
  `,t(B+`
29
- `,l)}});let j=await x;L&&clearTimeout(L);let q=_.end();q&&(E+=q);let J=R.end();if(J&&(H+=J),j.exitCode!==0&&!l||y){let v=H||(typeof j.stderr=="string"?j.stderr:""),S=j,B;return b?B=`Codex CLI produced no output for ${Math.round(M/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:S.timedOut?B=`Codex CLI timed out after ${Math.round(A/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?B=y:S.signal?B=v.trim()||`Codex CLI killed by signal ${S.signal}`:S.code==="ENOENT"||/ENOENT|spawn codex/i.test((S.shortMessage||"")+" "+v)?B=Xt():B=v.trim()||`Codex CLI exited with code ${S.exitCode??"unknown"}`,{content:"",...Z(B),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}let $="";try{$=wi(c,"utf8").trim()}catch{}if($&&$!==l){let v=$.startsWith(l)?$.slice(l.length):$;l=$,v&&t(v,l)}return{content:l,duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}catch(A){let x=/ENOENT|spawn codex/i.test(A?.message||"")?Xt():A?.message;return{content:l,...Z(x||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}finally{bi(d,{recursive:!0,force:!0})}}async function wu(n,e,t,s,r,o,i,a){let d=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let c=Te(n,e,s),u=du(n,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",p,f=e.freshSession?void 0:r,h,y,A=!0,x;try{let E=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),H=uu(n,e);if(n.persistentProcess)try{y=await Dr.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:H,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",y.url),H=y.env,o?.({type:"opencode.ready",reused:y.reused,startupMs:Date.now()-d})}catch(v){if(!(v instanceof Or))throw v;v.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:v.message})}if(i?.aborted)throw new Error("task cancelled by operator");let b=Yt("opencode",u,{cwd:e.cwd??n.workspace,timeout:E,reject:!1,env:H,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let _=!1,R,M=()=>{y?.invalidate(),_=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{b.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",M,{once:!0}),x=()=>i?.removeEventListener("abort",M),i?.aborted&&M();let L="",N="",j=new dt("utf8"),q=new dt("utf8"),J=v=>{if(v.trim())try{let S=JSON.parse(v);try{o?.(S)}catch{}typeof S.sessionID=="string"&&(f=S.sessionID);let B=S.type==="text"&&typeof S.part?.text=="string"?S.part.text:void 0;B&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-d,reused:y?.reused??!1}),l+=B,t?.(B,l));let W=S.type==="reasoning"&&typeof S.part?.text=="string"?S.part.text:void 0;W&&a?.(W);let P=S.type==="step_finish"?S.part?.tokens:void 0;P&&(p={inputTokens:he(P.input),outputTokens:he(P.output),cacheReadTokens:he(P.cache?.read),cacheCreateTokens:he(P.cache?.write)}),h=cu(S)||h}catch{l+=v+`
29
+ `,l)}});let j=await x;L&&clearTimeout(L);let q=_.end();q&&(E+=q);let J=R.end();if(J&&(H+=J),j.exitCode!==0&&!l||y){let v=H||(typeof j.stderr=="string"?j.stderr:""),S=j,B;return b?B=`Codex CLI produced no output for ${Math.round(M/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:S.timedOut?B=`Codex CLI timed out after ${Math.round(A/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?B=y:S.signal?B=v.trim()||`Codex CLI killed by signal ${S.signal}`:S.code==="ENOENT"||/ENOENT|spawn codex/i.test((S.shortMessage||"")+" "+v)?B=Xt():B=v.trim()||`Codex CLI exited with code ${S.exitCode??"unknown"}`,{content:"",...Z(B),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}let $="";try{$=xi(d,"utf8").trim()}catch{}if($&&$!==l){let v=$.startsWith(l)?$.slice(l.length):$;l=$,v&&t(v,l)}return{content:l,duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}catch(A){let x=/ENOENT|spawn codex/i.test(A?.message||"")?Xt():A?.message;return{content:l,...Z(x||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:f,codexSessionId:h||r}}finally{Si(c,{recursive:!0,force:!0})}}async function bu(n,e,t,s,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=Te(n,e,s),u=cu(n,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",p,f=e.freshSession?void 0:r,h,y,A=!0,x;try{let E=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),H=lu(n,e);if(n.persistentProcess)try{y=await Dr.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:H,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",y.url),H=y.env,o?.({type:"opencode.ready",reused:y.reused,startupMs:Date.now()-c})}catch(v){if(!(v instanceof Or))throw v;v.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:v.message})}if(i?.aborted)throw new Error("task cancelled by operator");let b=Yt("opencode",u,{cwd:e.cwd??n.workspace,timeout:E,reject:!1,env:H,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let _=!1,R,M=()=>{y?.invalidate(),_=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{b.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",M,{once:!0}),x=()=>i?.removeEventListener("abort",M),i?.aborted&&M();let L="",N="",j=new dt("utf8"),q=new dt("utf8"),J=v=>{if(v.trim())try{let S=JSON.parse(v);try{o?.(S)}catch{}typeof S.sessionID=="string"&&(f=S.sessionID);let B=S.type==="text"&&typeof S.part?.text=="string"?S.part.text:void 0;B&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:y?.reused??!1}),l+=B,t?.(B,l));let W=S.type==="reasoning"&&typeof S.part?.text=="string"?S.part.text:void 0;W&&a?.(W);let P=S.type==="step_finish"?S.part?.tokens:void 0;P&&(p={inputTokens:he(P.input),outputTokens:he(P.output),cacheReadTokens:he(P.cache?.read),cacheCreateTokens:he(P.cache?.write)}),h=uu(S)||h}catch{l+=v+`
30
30
  `,t?.(v+`
31
31
  `,l)}};b.stdout?.on("data",v=>{L+=j.write(v);let S=L.split(`
32
- `);L=S.pop()||"";for(let B of S)J(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let $=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=mi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-d,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let H=/ENOENT|spawn opencode/i.test(E?.message||"")?mi():E?.message;return{content:l,...Z(H||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(A)}}async function bu(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Te(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function xu(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{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?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let A=n.provider||"claude-code",x=s?`${s}
32
+ `);L=S.pop()||"";for(let B of S)J(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let $=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=hi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let H=/ENOENT|spawn opencode/i.test(E?.message||"")?hi():E?.message;return{content:l,...Z(H||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(A)}}async function xu(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Te(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Su(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{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?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",x=s?`${s}
33
33
 
34
- ${e.message}`:e.message,E=e.context?.sender,H=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&H?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Fr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-BOU3OKAD.js"),$="",v,S,B,W;for await(let P of J(M)){if(d)try{d(P)}catch{}if(P.type==="text_delta")$+=P.text,r(P.text,$);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-c}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-BOU3OKAD.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var Su=1e3;async function Iu(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"}),Su),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 Tu(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Vt(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&Zn(e.agentId,n,e.model,s,"persistent");let h=Te(n,e,t),y="",A,x,E,H,b,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
34
+ ${e.message}`:e.message,E=e.context?.sender,H=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&H?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Fr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-3U23E65W.js"),$="",v,S,B,W;for await(let P of J(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")$+=P.text,r(P.text,$);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-3U23E65W.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var Iu=1e3;async function Tu(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"}),Iu),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 ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Vt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=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}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&Vn(e.agentId,n,e.model,s,"persistent");let h=Te(n,e,t),y="",A,x,E,H,b,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
35
35
  `)?`
36
36
 
37
- ${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(H=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");A=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(E={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(b=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Kt(S.modelUsage)||_}}}catch($){if(j)A="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);A=v.error,x=v.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",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!A&&(A="task cancelled by operator",x="cancelled"),{content:j?"":y,error:A,errorKind:x,duration:Date.now()-d,usage:E,contextTokens:H,numTurns:b,billedModel:_,claudeSessionId:R}}function Ri(n){let e=me(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?ai(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:gi(t.args,n.taskId,n.agentId)}function ku(n){return me(n.autonomy)||!!n.personLimits}async function vu(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,d=a&&di(a,n.tier)||e.personLimits&&pi(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${br(a)}
37
+ ${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(H=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");A=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(E={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(b=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Kt(S.modelUsage)||_}}}catch($){if(j)A="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);A=v.error,x=v.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",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!A&&(A="task cancelled by operator",x="cancelled"),{content:j?"":y,error:A,errorKind:x,duration:Date.now()-c,usage:E,contextTokens:H,numTurns:b,billedModel:_,claudeSessionId:R}}function Pi(n){let e=me(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?ci(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:mi(t.args,n.taskId,n.agentId)}function vu(n){return me(n.autonomy)||!!n.personLimits}async function Au(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,c=a&&ui(a,n.tier)||e.personLimits&&fi(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?`${br(a)}
38
38
 
39
- ${e.message}`:e.message},l=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${l} task=${c} via=spawn (persistent process bypassed)
40
- `),e.personLimits&&ui(c,e.personLimits);try{let p=t?await Mi(n,u,t,s,r,o,i):await Ci(n,u,s,r,i);if(!a)return p;let f=ci(c);return{...p,autonomy:a,...f.length?{autonomyBlocks:f}:{}}}finally{e.personLimits&&li(c)}}async function _i(n,e,t,s,r,o,i,a,d){if(ku(e))return vu(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let c=await Tu(n,e,r,o,i,a,s);if(c!==null)return c}return s?Mi(n,e,s,r,o,i,a):Ci(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let c=await Vo.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:Zt(n,e),args:Ti(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Qn(Te(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...c,...c.error?Z(c.error):{}}}catch(c){if(!(c instanceof Ie))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?yu(n,e,s,r,o,i):hu(n,e,r,o);case"opencode":return wu(n,e,s,r,o,i,a,d);case"sdk":{let c=n.provider||"claude",u=t[c]?.apiKey;return u?bu(n,e,u,r):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=n.provider||"claude-code",u=t[c],l=u?.apiKey;return xu(n,e,l,r,s,{thinking:u?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ke,writeFileSync as Pi,mkdirSync as Au,existsSync as en,readdirSync as Vn}from"fs";import{resolve as Je}from"path";var es=12e3,ut=30,$u=720,Cu=40,Mu=18e4,Ru="[Compacted conversation summary",_u=7*864e5,Pu=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Eu(n){return n?Pu.some(e=>e.test(n)):!1}var Ou=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function Oi(n){if(!n)return null;let e=0;for(let t of Ou)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Ei(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function Di(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function Li(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function Du(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var tn=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Je(e,".agentx/sessions"),en(this.sessionsDir)||Au(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??$u),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Cu),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Mu),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let d=this.adapterResolver(t);if(!d?.seedHistory)return;let c=(async()=>{try{let u=await d.seedHistory(s,{maxMessages:ut,maxChars:es});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,c);try{await c}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Je(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(en(o))try{let c=JSON.parse(Ke(o,"utf-8"));return this.cache.set(r,c),c}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),d={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,d),this.save(d),d}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!en(i))return null;try{return JSON.parse(Ke(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Ei(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,s,r){let o=this.getSession(e,t,s),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,s,r){let o=this.getSession(e,t,s);Ei(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}continueFrom(e,t,s){if(t.channel===s.channel&&t.chatId===s.chatId)return!1;let r=this.sessionKey(e,t.channel,t.chatId);if(!(this.cache.has(r)||en(this.sessionFile(r))||this.loadPreviousDaySession(e,t.channel,t.chatId)!==null))return!1;let i=this.getSession(e,t.channel,t.chatId);if(!i.claudeSessionId&&!i.codexSessionId&&!i.opencodeSessionId)return!1;let a=this.getSession(e,s.channel,s.chatId);return a.claudeSessionId=i.claudeSessionId,a.codexSessionId=i.codexSessionId,a.opencodeSessionId=i.opencodeSessionId,a.turnCount=i.turnCount,a.lastTurnInputTokens=i.lastTurnInputTokens,a.lastTurnContextTokens=i.lastTurnContextTokens,a.updatedAt=i.updatedAt,this.save(a),!0}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??ut),a=Math.max(200,r.maxChars??es),d=[],c=0;for(let p=o.messages.length-1;p>=0&&d.length<i;p--){let f=o.messages[p];if(c+=f.content.length,d.push(f),c>=a)break}d.reverse();let u=[`[Conversation history for today (${o.day})]`,"(Past messages. What they say is merged, live, approved or waiting, your own earlier replies included, may be out of date. Check it now before you repeat it, or say it is not checked.)"],l="";for(let p of d){let f=Du(p.timestamp);f!==l&&(u.push(`\u2014 ${f} \u2014`),l=f);let h=p.name||(p.role==="user"?"User":"Agent");u.push(`${h}: ${p.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
- `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),d;try{d=Vn(this.sessionsDir).filter(b=>b.startsWith(`${a}:`)&&b.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let c=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,p=d.filter(b=>{let _=b.match(l);if(!_)return!1;let R=_[1];return R>=c&&R<=u}),f=[],h=0,y=e.query?.toLowerCase(),A=e.participants?.length?new Set(e.participants):void 0;for(let b of p){let _;try{_=JSON.parse(Ke(Je(this.sessionsDir,b),"utf-8"))}catch{continue}if(_.agentId===e.agentId&&!(e.channel&&_.channel!==e.channel)&&!(e.chatId&&_.chatId!==e.chatId))for(let R of _.messages)h++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(A&&R.role==="user"&&!A.has(R.name??"")||y&&!R.content.toLowerCase().includes(y)||f.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:_.channel,chatId:_.chatId,day:_.day,sessionFile:b}))}f.sort((b,_)=>_.ts.localeCompare(b.ts));let x=f.slice(0,t),E=x.length>0?x[x.length-1].ts:null,H=f.length>t;return{turns:x,oldestTs:E,hasMore:H,totalScanned:h}}recentByChatId(e){let t=Math.min(Math.max(e.limit??ut,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Vn(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let p=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),d=[];for(let l of a){let p;try{p=JSON.parse(Ke(Je(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let f of p.messages)!f.timestamp||f.timestamp<s||d.push({ts:f.timestamp,role:f.role,senderName:f.name??"",content:f.content,agentId:p.agentId,sessionFile:l})}let c=new Set,u=[];for(let l of d){let p=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;c.has(p)||(c.add(p),u.push(l))}return u.sort((l,p)=>l.ts.localeCompare(p.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!Eu(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Vn(this.sessionsDir).filter(c=>c.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&c.includes(o)&&c.endsWith(".json")),d=[];for(let c of a)try{let u=JSON.parse(Ke(Je(this.sessionsDir,c),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),f=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,h=l.map(y=>` [${y.timestamp.slice(11,16)}] ${y.name||y.role}: ${y.content.slice(0,200)}`);d.push(`From ${f} (${u.channel}):
39
+ ${e.message}`:e.message},l=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${l} task=${d} via=spawn (persistent process bypassed)
40
+ `),e.personLimits&&gi(d,e.personLimits);try{let p=t?await _i(n,u,t,s,r,o,i):await Ri(n,u,s,r,i);if(!a)return p;let f=li(d);return{...p,autonomy:a,...f.length?{autonomyBlocks:f}:{}}}finally{e.personLimits&&pi(d)}}async function Ei(n,e,t,s,r,o,i,a,c){if(vu(e))return Au(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let d=await ku(n,e,r,o,i,a,s);if(d!==null)return d}return s?_i(n,e,s,r,o,i,a):Ri(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let d=await ti.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:Zt(n,e),args:vi(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Xn(Te(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...d,...d.error?Z(d.error):{}}}catch(d){if(!(d instanceof Ie))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?wu(n,e,s,r,o,i):yu(n,e,r,o);case"opencode":return bu(n,e,s,r,o,i,a,c);case"sdk":{let d=n.provider||"claude",u=t[d]?.apiKey;return u?xu(n,e,u,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=n.provider||"claude-code",u=t[d],l=u?.apiKey;return Su(n,e,l,r,s,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ke,writeFileSync as Oi,mkdirSync as $u,existsSync as en,readdirSync as es}from"fs";import{resolve as Je}from"path";var ts=12e3,ut=30,Cu=720,Mu=40,Ru=18e4,_u="[Compacted conversation summary",Pu=7*864e5,Eu=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Ou(n){return n?Eu.some(e=>e.test(n)):!1}var Du=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function Li(n){if(!n)return null;let e=0;for(let t of Du)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Di(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function Ni(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function Bi(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function Lu(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var tn=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Je(e,".agentx/sessions"),en(this.sessionsDir)||$u(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Cu),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Mu),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Ru),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let u=await c.seedHistory(s,{maxMessages:ut,maxChars:ts});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Je(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(en(o))try{let d=JSON.parse(Ke(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!en(i))return null;try{return JSON.parse(Ke(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Di(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,s,r){let o=this.getSession(e,t,s),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,s,r){let o=this.getSession(e,t,s);Di(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}continueFrom(e,t,s){if(t.channel===s.channel&&t.chatId===s.chatId)return!1;let r=this.sessionKey(e,t.channel,t.chatId);if(!(this.cache.has(r)||en(this.sessionFile(r))||this.loadPreviousDaySession(e,t.channel,t.chatId)!==null))return!1;let i=this.getSession(e,t.channel,t.chatId);if(!i.claudeSessionId&&!i.codexSessionId&&!i.opencodeSessionId)return!1;let a=this.getSession(e,s.channel,s.chatId);return a.claudeSessionId=i.claudeSessionId,a.codexSessionId=i.codexSessionId,a.opencodeSessionId=i.opencodeSessionId,a.turnCount=i.turnCount,a.lastTurnInputTokens=i.lastTurnInputTokens,a.lastTurnContextTokens=i.lastTurnContextTokens,a.updatedAt=i.updatedAt,this.save(a),!0}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??ut),a=Math.max(200,r.maxChars??ts),c=[],d=0;for(let p=o.messages.length-1;p>=0&&c.length<i;p--){let f=o.messages[p];if(d+=f.content.length,c.push(f),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`,"(Past messages. What they say is merged, live, approved or waiting, your own earlier replies included, may be out of date. Check it now before you repeat it, or say it is not checked.)"],l="";for(let p of c){let f=Lu(p.timestamp);f!==l&&(u.push(`\u2014 ${f} \u2014`),l=f);let h=p.name||(p.role==="user"?"User":"Agent");u.push(`${h}: ${p.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
+ `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=es(this.sessionsDir).filter(b=>b.startsWith(`${a}:`)&&b.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,p=c.filter(b=>{let _=b.match(l);if(!_)return!1;let R=_[1];return R>=d&&R<=u}),f=[],h=0,y=e.query?.toLowerCase(),A=e.participants?.length?new Set(e.participants):void 0;for(let b of p){let _;try{_=JSON.parse(Ke(Je(this.sessionsDir,b),"utf-8"))}catch{continue}if(_.agentId===e.agentId&&!(e.channel&&_.channel!==e.channel)&&!(e.chatId&&_.chatId!==e.chatId))for(let R of _.messages)h++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(A&&R.role==="user"&&!A.has(R.name??"")||y&&!R.content.toLowerCase().includes(y)||f.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:_.channel,chatId:_.chatId,day:_.day,sessionFile:b}))}f.sort((b,_)=>_.ts.localeCompare(b.ts));let x=f.slice(0,t),E=x.length>0?x[x.length-1].ts:null,H=f.length>t;return{turns:x,oldestTs:E,hasMore:H,totalScanned:h}}recentByChatId(e){let t=Math.min(Math.max(e.limit??ut,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=es(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let p=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),c=[];for(let l of a){let p;try{p=JSON.parse(Ke(Je(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let f of p.messages)!f.timestamp||f.timestamp<s||c.push({ts:f.timestamp,role:f.role,senderName:f.name??"",content:f.content,agentId:p.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let p=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(p)||(d.add(p),u.push(l))}return u.sort((l,p)=>l.ts.localeCompare(p.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!Ou(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=es(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(Ke(Je(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),f=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,h=l.map(y=>` [${y.timestamp.slice(11,16)}] ${y.name||y.role}: ${y.content.slice(0,200)}`);c.push(`From ${f} (${u.channel}):
42
42
  ${h.join(`
43
- `)}`)}catch{}return d.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...d,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
44
- `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:d}=await import("./compaction-COUQNMWL.js");if(!i(o.messages))return{compacted:!1};let c=await a(o.messages,e,r,{channel:t,chatId:s});return c.compactedCount===0?{compacted:!1}:(o.messages=d(o.messages,c),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:c.qualityScore,lostEntities:c.lostEntities,drift:c.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(Ru)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,s){let r=this.getSession(e,t,s);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Je(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Pi(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>_u?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>ut&&(e.messages=e.messages.slice(-ut));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>es&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Re.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);Pi(t,JSON.stringify(e,null,2))}catch{}}};var Ni="_capture-runs.jsonl",Lu=1e6;function ts(n,e,t){try{zr(n,e,Lu)}catch(s){t(`[wiki-capture] could not record a capture outcome in ${n}: ${String(s?.message??s)}`)}}function Bi(n,e,t,s,r=new Date){let o=t.reason??"filtered";s(`[${e}] not captured in the wiki: ${o}`),ts(n,{at:r.toISOString(),agent:e,outcome:"skipped",reason:o},s)}function Fi(n,e,t,s,r=()=>new Date){try{t()}catch(o){return s(`[${e}] wiki entry not written: ${String(o?.message??o)}`),ts(n,{at:r().toISOString(),agent:e,outcome:"failed"},s),!1}return ts(n,{at:r().toISOString(),agent:e,outcome:"captured"},s),!0}function ph(n,e){let t={total:0,captured:0,skipped:0,failed:0,skippedBy:{}};for(let s of n.split(`
45
- `)){if(!s)continue;let r;try{r=JSON.parse(s)}catch{continue}if(!(!r||typeof r.at!="string"||e&&r.at<e)&&!(r.outcome!=="captured"&&r.outcome!=="skipped"&&r.outcome!=="failed")&&(t.total++,t[r.outcome]++,r.outcome==="skipped")){let o=r.reason||"filtered";t.skippedBy[o]=(t.skippedBy[o]??0)+1}}return t}var nn=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(d=>d>r),i=t-6e4,a=o.filter(d=>d>i);if(a.length>=this.maxPerMinute){let d=a[0],c=Math.max(50,d+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:c}}if(o.length>=this.maxPerHour){let d=o[0],c=Math.max(1e3,d+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:c}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),d=Math.min(i.waitMs??1e3,a,5e3);await new Promise(c=>setTimeout(c,d))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};function Nu(n){return n.split(`
46
- `).map(e=>{if(!Kr(e))return e;let t=e.match(/^(\s*[-*•]\s*)(.*)$/);return t?`${t[1]}${Ln}${t[2]}`:`${Ln}${e}`}).join(`
47
- `)}var Bu={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},Ui=4;function qi(n,e=Bu){let t=Uu(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*Ui;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Ui,d=Hi(i.content,a,i.keep);if(r+d.length>o){let c=o-r;c>100&&s.push(Hi(d,c,i.keep));break}s.push(d),r+=d.length}return s.join(`
43
+ `)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
44
+ `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-COUQNMWL.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:s});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(_u)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,s){let r=this.getSession(e,t,s);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Je(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ke(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Oi(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>Pu?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>ut&&(e.messages=e.messages.slice(-ut));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>ts&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Re.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);Oi(t,JSON.stringify(e,null,2))}catch{}}};var Fi="_capture-runs.jsonl",Nu=1e6;function ns(n,e,t){try{zr(n,e,Nu)}catch(s){t(`[wiki-capture] could not record a capture outcome in ${n}: ${String(s?.message??s)}`)}}function Ui(n,e,t,s,r=new Date){let o=t.reason??"filtered";s(`[${e}] not captured in the wiki: ${o}`),ns(n,{at:r.toISOString(),agent:e,outcome:"skipped",reason:o},s)}function Hi(n,e,t,s,r=()=>new Date){try{t()}catch(o){return s(`[${e}] wiki entry not written: ${String(o?.message??o)}`),ns(n,{at:r().toISOString(),agent:e,outcome:"failed"},s),!1}return ns(n,{at:r().toISOString(),agent:e,outcome:"captured"},s),!0}function ph(n,e){let t={total:0,captured:0,skipped:0,failed:0,skippedBy:{}};for(let s of n.split(`
45
+ `)){if(!s)continue;let r;try{r=JSON.parse(s)}catch{continue}if(!(!r||typeof r.at!="string"||e&&r.at<e)&&!(r.outcome!=="captured"&&r.outcome!=="skipped"&&r.outcome!=="failed")&&(t.total++,t[r.outcome]++,r.outcome==="skipped")){let o=r.reason||"filtered";t.skippedBy[o]=(t.skippedBy[o]??0)+1}}return t}var nn=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};function Bu(n){return n.split(`
46
+ `).map(e=>{if(!Kr(e))return e;let t=e.match(/^(\s*[-*•]\s*)(.*)$/);return t?`${t[1]}${Nn}${t[2]}`:`${Nn}${e}`}).join(`
47
+ `)}var Fu={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},ji=4;function Ki(n,e=Fu){let t=Hu(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*ji;for(let i of t){if(!i.content)continue;let a=i.maxTokens*ji,c=Wi(i.content,a,i.keep);if(r+c.length>o){let d=o-r;d>100&&s.push(Wi(c,d,i.keep));break}s.push(c),r+=c.length}return s.join(`
48
48
 
49
- `)}function Hi(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
49
+ `)}function Wi(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
50
50
  `,r=n.indexOf(`
51
- `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=Wi(n,i);if(!ji.test(a.slice(0,a.indexOf(`
52
- `)+1||void 0))){let d=u=>n.slice(0,n.length-u.length).match(Fu)?.pop(),c=d(a);if(c&&c.length+1<i/2){a=Wi(n,i-c.length-1);let u=ji.test(a.slice(0,a.indexOf(`
53
- `)+1||void 0))?"":d(a);u&&(a=u+`
54
- `+a)}}return o+s+a}var ji=/^— \d\d:\d\d —(\n|$)/,Fu=/^— \d\d:\d\d —$/gm;function Wi(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
55
- `);return s>=0&&s<e/2?t.slice(s+1):t}function Uu(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(Hu(n,t("channel",200))),s.push(ju(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
56
- `)[0],tags:["identity",n.agentId]}),n.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:n.bootstrapContext,tags:["bootstrap","identity","personality"]}),n.references&&s.push({name:"references",priority:4.7,maxTokens:t("references",500),content:n.references,tags:["references","verified","deterministic"]}),n.intent&&n.intent.path.length>0){let i=[`[Intent path: ${n.intent.pathLabel}${n.intent.status==="pending"?" (pending approval)":""}]`],a=n.intent.path[n.intent.path.length-1],d=n.intent.axes?.[a];if(d&&Object.keys(d).length){let c=Object.entries(d).map(([u,l])=>` ${u}: ${l}`).join(`
57
- `);i.push(c)}n.intent.leaf?.input&&i.push(` input: ${n.intent.leaf.input}`),s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
58
- `),tags:["intent",...n.intent.path]})}else{let i=Wu(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
51
+ `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=Gi(n,i);if(!qi.test(a.slice(0,a.indexOf(`
52
+ `)+1||void 0))){let c=u=>n.slice(0,n.length-u.length).match(Uu)?.pop(),d=c(a);if(d&&d.length+1<i/2){a=Gi(n,i-d.length-1);let u=qi.test(a.slice(0,a.indexOf(`
53
+ `)+1||void 0))?"":c(a);u&&(a=u+`
54
+ `+a)}}return o+s+a}var qi=/^— \d\d:\d\d —(\n|$)/,Uu=/^— \d\d:\d\d —$/gm;function Gi(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
55
+ `);return s>=0&&s<e/2?t.slice(s+1):t}function Hu(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(ju(n,t("channel",200))),s.push(Wu(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
56
+ `)[0],tags:["identity",n.agentId]}),n.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:n.bootstrapContext,tags:["bootstrap","identity","personality"]}),n.references&&s.push({name:"references",priority:4.7,maxTokens:t("references",500),content:n.references,tags:["references","verified","deterministic"]}),n.intent&&n.intent.path.length>0){let i=[`[Intent path: ${n.intent.pathLabel}${n.intent.status==="pending"?" (pending approval)":""}]`],a=n.intent.path[n.intent.path.length-1],c=n.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,l])=>` ${u}: ${l}`).join(`
57
+ `);i.push(d)}n.intent.leaf?.input&&i.push(` input: ${n.intent.leaf.input}`),s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
58
+ `),tags:["intent",...n.intent.path]})}else{let i=qu(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
59
59
  `),tags:["artifacts",...n.mediaType?["media"]:[]]}),n.skillInjection&&s.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:n.skillInjection,tags:["skills","auto-inject"]}),n.patternContext&&s.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:n.patternContext,tags:["patterns","behavioral","self-improving"]}),n.procedureContext&&s.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:n.procedureContext,tags:["procedures","sop"]}),n.workflowRunContext&&s.push({name:"workflow-run",priority:6.55,maxTokens:t("workflow-run",200),content:n.workflowRunContext,tags:["workflow","plan"]}),n.memoryContext&&s.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:n.memoryContext,tags:["memory","persistent"]}),n.ownerDecisions&&s.push({name:"owner-decisions",priority:2.7,maxTokens:t("owner-decisions",1500),content:n.ownerDecisions,tags:["owner","decisions","wiki"]});let o=n.groupHistory||n.sessionHistory;if(o&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"],keep:"tail"}),n.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:n.crossChatContext,tags:["history","cross-chat"]}),n.contextOnDemand&&s.push({name:"on-demand",priority:7,maxTokens:t("on-demand",150),content:n.contextOnDemand,tags:["history","on-demand","lean"]}),n.longMemoryRecall&&s.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:n.longMemoryRecall,tags:["history","long-memory"]}),n.handoverNote){let i=[`[Handover] You are taking over this conversation from ${n.handoverNote.fromAgent}.`];n.handoverNote.summary&&i.push(`Operator summary: ${n.handoverNote.summary}`),i.push(`Handover time: ${n.handoverNote.at}`),s.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
60
- `),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts, and owner decisions made after it win over it: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner. Usage limits, resets, holds and this machine: call agentx_node:]`,Nu(n.rotationMemo.memo)].join(`
61
- `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function Hu(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(n.channel==="a2a"?`Chat ID: ${n.chatId} (use this verbatim in /recall; /send with channel "a2a" messages the other agent in this chat)`:`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
62
- `),tags:r,rules:s}}function ju(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
63
- `),tags:s}}function Wu(n){let e=[],t=n.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var qu="resumeDelivery";function wh(n){if(!n||n.kind!=="direct"||!n.context||n.context[qu]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var Gu=32e3;function Gi(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Gu?e:null}catch{return null}}function bh(n){if(!n)return null;try{let e=JSON.parse(n);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}var ss={enabled:!0,maxContinuations:1};function Sh(n){return n?.enabled?n.maxContinuations:0}var Ku=2*6e4,Ju=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function zu(n,e){if(!n||e!=="timeout")return null;let t=n.match(Ju);return t?Number(t[2]):null}function Ki(n){let e=zu(n.error,n.errorKind);if(e===null||n.viaMesh)return{action:"none"};let t=n.settings;if(!t.enabled)return{action:"report",minutes:e,reason:"continuing after the time limit is turned off"};if(n.continuation>=t.maxContinuations)return{action:"report",minutes:e,reason:t.maxContinuations===0?"continuing after the time limit is turned off":`already continued ${n.continuation===1?"once":`${n.continuation} times`}`};if((n.channel??"").toLowerCase().split("@")[0]==="cron")return{action:"report",minutes:e,reason:"scheduled job: the next scheduled run covers it"};if(n.workflowRunId||(n.chatId??"").startsWith("workflow:"))return{action:"report",minutes:e,reason:"workflow step: the workflow engine owns retries"};if(n.callerGone)return{action:"report",minutes:e,reason:"nobody is waiting for the answer any more"};let r;if(n.timeoutMinutes&&n.timeoutMinutes>0){let o=n.timeoutMinutes*6e4-n.elapsedMs;if(o<Ku)return{action:"report",minutes:e,reason:"the caller's own time limit leaves no time to continue"};r=o/6e4}return{action:"continue",minutes:e,continuation:n.continuation+1,...r?{timeoutMinutes:r}:{}}}function Ji(n,e){return`${n} It was not continued (${e}).`}var ns=15,Qu=160;function zi(n,e,t){let s=[`[Continued after the time limit] You worked on this request for ${n} min, your time limit, and were stopped before you finished.`];return e.length===0?s.push("No tool calls were recorded for that run."):(s.push(`You had already made these tool calls (${e.length}):`),e.slice(0,ns).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,Qu);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>ns&&s.push(`\u2026and ${e.length-ns} more.`),s.push("Before repeating anything that changes the outside world \u2014 posting a comment or message, pushing, merging, deploying, sending \u2014 check whether it already happened.")),s.push(t?"This is your last run for it. Finish the request if you can; if you can't, say what is done, what is left and what is blocking it. Don't start long work you can't finish.":"Carry on from where you stopped and finish the request below.",""),s.join(`
64
- `)}function Qi(n){return new Date(n).toISOString().slice(11,16)}function Xi(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Qi(n)} UTC, running at ${Qi(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var sn=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(d=>`[${d.sender}, ${new Date(d.timestamp).toISOString().slice(11,16)}]: ${d.text}`).join(`
65
- `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(d=>d.queuedAt??d.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};var Xu=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,Yu=String.raw`(?=[\w.-]*[A-Za-z])(?![\w-]*\.(?:ts|js|mjs|cjs|tsx|jsx|md|py|go|rs|json|ya?ml|txt|sh|html|css)\b)[\w.-]+`,Yi=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,Zi=new RegExp(String.raw`(?<![\w/.-])((?:${Xu}\/)+${Yu})([#!])(\d+)\b`,"g");function rn(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(Yi.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${Zi.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function Zu(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(Yi)){let s=rn(t[0]);s&&e.add(s)}for(let t of n.matchAll(Zi))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function kh(n){let e=n.context&&typeof n.context=="object"?n.context:null;return rn(n.home)??rn(e?.home)}var Vu="[agentx:same-home]";function Vi(n,e,t){if(!e.length)return null;for(let s of n){if(s.channel===t.channel&&s.chatId===t.chatId)continue;let r=s.homes?.find(i=>e.includes(i));if(!r)continue;let o=s.startedAt.toISOString().slice(11,16);return`${Vu} Another run of yours is already working on ${r} (started ${o}Z, chat ${s.channel}:${s.chatId??"?"}). Coordinate with it or stop: do not redo or overwrite its work. Keep what is not committed in a branch, not in a shared folder.`}return null}function ea(n){let e=rn(n.home),t=Zu(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as el,writeFileSync as ta,appendFileSync as tl,mkdirSync as nl,existsSync as na}from"fs";import{resolve as rs}from"path";var sa=50,sl="claude-haiku-4-5-20251001",rl=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
60
+ `),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts, and owner decisions made after it win over it: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner. Usage limits, resets, holds and this machine: call agentx_node:]`,Bu(n.rotationMemo.memo)].join(`
61
+ `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function ju(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(n.channel==="a2a"?`Chat ID: ${n.chatId} (use this verbatim in /recall; /send with channel "a2a" messages the other agent in this chat)`:`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
62
+ `),tags:r,rules:s}}function Wu(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
63
+ `),tags:s}}function qu(n){let e=[],t=n.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var Gu="resumeDelivery";function wh(n){if(!n||n.kind!=="direct"||!n.context||n.context[Gu]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var Ku=32e3;function Ji(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Ku?e:null}catch{return null}}function bh(n){if(!n)return null;try{let e=JSON.parse(n);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}var rs={enabled:!0,maxContinuations:1};function Sh(n){return n?.enabled?n.maxContinuations:0}var Ju=2*6e4,zu=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function Qu(n,e){if(!n||e!=="timeout")return null;let t=n.match(zu);return t?Number(t[2]):null}function zi(n){let e=Qu(n.error,n.errorKind);if(e===null||n.viaMesh)return{action:"none"};let t=n.settings;if(!t.enabled)return{action:"report",minutes:e,reason:"continuing after the time limit is turned off"};if(n.continuation>=t.maxContinuations)return{action:"report",minutes:e,reason:t.maxContinuations===0?"continuing after the time limit is turned off":`already continued ${n.continuation===1?"once":`${n.continuation} times`}`};if((n.channel??"").toLowerCase().split("@")[0]==="cron")return{action:"report",minutes:e,reason:"scheduled job: the next scheduled run covers it"};if(n.workflowRunId||(n.chatId??"").startsWith("workflow:"))return{action:"report",minutes:e,reason:"workflow step: the workflow engine owns retries"};if(n.callerGone)return{action:"report",minutes:e,reason:"nobody is waiting for the answer any more"};let r;if(n.timeoutMinutes&&n.timeoutMinutes>0){let o=n.timeoutMinutes*6e4-n.elapsedMs;if(o<Ju)return{action:"report",minutes:e,reason:"the caller's own time limit leaves no time to continue"};r=o/6e4}return{action:"continue",minutes:e,continuation:n.continuation+1,...r?{timeoutMinutes:r}:{}}}function Qi(n,e){return`${n} It was not continued (${e}).`}var ss=15,Xu=160;function Xi(n,e,t){let s=[`[Continued after the time limit] You worked on this request for ${n} min, your time limit, and were stopped before you finished.`];return e.length===0?s.push("No tool calls were recorded for that run."):(s.push(`You had already made these tool calls (${e.length}):`),e.slice(0,ss).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,Xu);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>ss&&s.push(`\u2026and ${e.length-ss} more.`),s.push("Before repeating anything that changes the outside world \u2014 posting a comment or message, pushing, merging, deploying, sending \u2014 check whether it already happened.")),s.push(t?"This is your last run for it. Finish the request if you can; if you can't, say what is done, what is left and what is blocking it. Don't start long work you can't finish.":"Carry on from where you stopped and finish the request below.",""),s.join(`
64
+ `)}function Yi(n){return new Date(n).toISOString().slice(11,16)}function Zi(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Yi(n)} UTC, running at ${Yi(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var sn=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
65
+ `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};var Yu=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,Zu=String.raw`(?=[\w.-]*[A-Za-z])(?![\w-]*\.(?:ts|js|mjs|cjs|tsx|jsx|md|py|go|rs|json|ya?ml|txt|sh|html|css)\b)[\w.-]+`,Vi=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,ea=new RegExp(String.raw`(?<![\w/.-])((?:${Yu}\/)+${Zu})([#!])(\d+)\b`,"g");function rn(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(Vi.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${ea.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function Vu(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(Vi)){let s=rn(t[0]);s&&e.add(s)}for(let t of n.matchAll(ea))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function kh(n){let e=n.context&&typeof n.context=="object"?n.context:null;return rn(n.home)??rn(e?.home)}var el="[agentx:same-home]";function ta(n,e,t){if(!e.length)return null;for(let s of n){if(s.channel===t.channel&&s.chatId===t.chatId)continue;let r=s.homes?.find(i=>e.includes(i));if(!r)continue;let o=s.startedAt.toISOString().slice(11,16);return`${el} Another run of yours is already working on ${r} (started ${o}Z, chat ${s.channel}:${s.chatId??"?"}). Coordinate with it or stop: do not redo or overwrite its work. Keep what is not committed in a branch, not in a shared folder.`}return null}function na(n){let e=rn(n.home),t=Vu(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as tl,writeFileSync as sa,appendFileSync as nl,mkdirSync as sl,existsSync as ra}from"fs";import{resolve as os}from"path";var oa=50,rl="claude-haiku-4-5-20251001",ol=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
66
66
 
67
67
  Extract patterns like:
68
68
  - "When asked about X, the approach that works is Y"
@@ -78,79 +78,68 @@ SKIP:
78
78
  Output a JSON array:
79
79
  [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
80
80
 
81
- If nothing worth extracting, output: []`,on=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=rs(e,".agentx/patterns"),na(this.patternsDir)||nl(this.patternsDir,{recursive:!0})}filePath(e){return rs(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!na(t))return[];try{return el(t,"utf-8").split(`
82
- `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};tl(this.filePath(e),JSON.stringify(s)+`
83
- `)}findRelevant(e,t,s=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(u=>`${u.context} ${u.pattern}`),i=rs(this.patternsDir,`${t}_bm25_cache.json`),a=hr(o,i),c=fr(e,a).slice(0,s).map(u=>r[u.docIndex]).filter(u=>u.confidence>=.3);return c.length>0&&this.recordAccess(t,c.map(u=>u.id)),c}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
84
- `)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(d=>i.includes(d)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&ta(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
81
+ If nothing worth extracting, output: []`,on=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=os(e,".agentx/patterns"),ra(this.patternsDir)||sl(this.patternsDir,{recursive:!0})}filePath(e){return os(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ra(t))return[];try{return tl(t,"utf-8").split(`
82
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};nl(this.filePath(e),JSON.stringify(s)+`
83
+ `)}findRelevant(e,t,s=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(u=>`${u.context} ${u.pattern}`),i=os(this.patternsDir,`${t}_bm25_cache.json`),a=hr(o,i),d=fr(e,a).slice(0,s).map(u=>r[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
84
+ `)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&sa(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
85
85
  `)+`
86
- `)}prune(e){let t=this.getAll(e);t.length<=sa||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,sa),ta(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
86
+ `)}prune(e){let t=this.getAll(e);t.length<=oa||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,oa),sa(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
87
87
  `)+`
88
- `))}};async function ra(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-F5GDJSYD.js"),d=(await o("claude").generate([{role:"system",content:rl},{role:"user",content:`User: ${e.slice(0,500)}
88
+ `))}};async function ia(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-F5GDJSYD.js"),c=(await o("claude").generate([{role:"system",content:ol},{role:"user",content:`User: ${e.slice(0,500)}
89
89
 
90
- Agent: ${t.slice(0,1e3)}`}],{model:sl,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!d)return;let c=JSON.parse(d[0]);if(!(!Array.isArray(c)||c.length===0)){for(let u of c)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as ol}from"events";var il=2e4,is=class{inner=new ol;envelopeListeners=new Set;ring=new co;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let s=this.inner.emit(e,t);try{this.publish(al(e,t))}catch{}return s}publish(e){let t=st(),s=e.id??ao(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Un(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),e.expiresAt&&(r.expiresAt=e.expiresAt),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>il&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Un(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),e.expiresAt&&(s.expiresAt=e.expiresAt),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function al(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"forge:commented":return{...s,kind:"message",ref:t.commentId,summary:`comment ${t.commentId} on ${t.channel} ${t.chatId}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var os;function V(){return os||(os=new is),os}_n();function dl(n){let e=n.replace(/^---[\s\S]*?\n---\n/,""),t=[],s=/^##\s+([^\n]*)\n([\s\S]*?)(?=^##\s|(?![\s\S]))/gm;for(let d=s.exec(e);d;d=s.exec(e))t.push({head:d[1].trim(),text:d[2]});let r=d=>d.replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
91
-
92
- `).trim(),o=t.filter(d=>/^(update|change|amend)/i.test(d.head)),i=t.find(d=>/^rule\b/i.test(d.head)&&!/superseded|earlier rule/i.test(d.head)),a;return o.length?(a=[...o].reverse().map(d=>`${d.head}:
93
- ${r(d.text)}`).join(`
94
-
95
- `),i&&(a+=`
96
-
97
- Older rule (the updates above win where they differ):
98
- ${r(i.text)}`)):a=r(i?i.text:e),a.length>1400?a.slice(0,1400-1)+"\u2026":a}function oa(n,e,t={}){let s=e-(t.days??7)*864e5,r=n.filter(o=>o.meta.type==="decision"&&!o.path.includes("/_versions/")).map(o=>({a:o,at:Date.parse(o.meta.lastUpdated||o.meta.created||"")})).filter(o=>Number.isFinite(o.at)&&o.at>=s).sort((o,i)=>i.at-o.at).slice(0,t.max??6);return r.length===0?"":["[Owner decisions \u2014 the newest recorded rulings, from the wiki]","These outrank the chat history, the continuity memo and your own notes below. Where those say something else (an approval still needed, a step still waiting), they are out of date: follow these.",...r.map(({a:o})=>`
99
- ### ${o.meta.title} (updated ${o.meta.lastUpdated||o.meta.created})
100
- ${dl(o.content)}`),"[End owner decisions]"].join(`
101
- `)}var cl=/\breq-[0-9A-HJKMNP-TV-Z]{26}\b/;var ia="[agentx:same-work",ul=new Set(["app","telegram","whatsapp","voice","slack","discord","email","sms","ntfy","dashboard","web-chat","tui","admin","test-drive","workflow-editor","guest","public-api"]);function ll(n){return!!n&&ul.has(n)}var gl=new Set(["a2a","cron","workflow","reminder","events","business"]);function aa(n){return!!n&&gl.has(n)}function da(n,e){return!n||ll(e)||n.startsWith(ia)?null:cl.exec(n)?.[0]??null}var an=class{constructor(e={}){this.opts=e}holders=new Map;ended=new Map;now(){return this.opts.now?.()??Date.now()}async enter(e,t,s,r){let o=`${e}\0${t}`,i=this.now(),a=this.opts.waitMs??9e5,d=!1;for(;;){let y=this.holders.get(o);if(!y||s&&y.rootId===s)break;if(r?.aborted||this.now()-i>a){this.opts.log?.(`[${e}] ${t}: going ahead beside a run still on it (waited ${Math.round((this.now()-i)/1e3)}s)`);break}d||this.opts.log?.(`[${e}] ${t}: another run of this agent is on it; waiting for it to end`),d=!0,await Promise.race([y.done,(this.opts.sleep??ml)(1e3)])}let c,u=new Promise(y=>{c=y}),l={rootId:s,startedAt:this.now(),done:u};this.holders.get(o)||this.holders.set(o,l);let f=this.ended.get(o);return{note:f&&this.now()-f.at<=27e5?pl(t,f,this.now()):"",waitedMs:this.now()-i,release:({text:y,ok:A,ran:x=!0})=>{this.holders.get(o)===l&&this.holders.delete(o),x&&this.ended.set(o,{at:this.now(),text:y,ok:A}),this.prune(),c()}}}prune(){let e=this.now()-27e5;for(let[t,s]of this.ended)s.at<e&&this.ended.delete(t)}};function pl(n,e,t){let s=Math.max(0,Math.round((t-e.at)/6e4)),r=e.text.length>1500?e.text.slice(0,1500-1)+"\u2026":e.text;return[`${ia} key=${n}]`,`Another run of yours worked on ${n} and ended ${s===0?"just now":`${s} min ago`}${e.ok?"":" (it failed)"}. It answered:`,r||"(no answer)","","Do not do again what it already did. Check the live state, build on it, or say it is already done.","","The new message:",""].join(`
90
+ Agent: ${t.slice(0,1e3)}`}],{model:rl,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as il}from"events";var al=2e4,as=class{inner=new il;envelopeListeners=new Set;ring=new co;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let s=this.inner.emit(e,t);try{this.publish(dl(e,t))}catch{}return s}publish(e){let t=st(),s=e.id??ao(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:Hn(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),e.expiresAt&&(r.expiresAt=e.expiresAt),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>al&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:Hn(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),e.expiresAt&&(s.expiresAt=e.expiresAt),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function dl(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"forge:commented":return{...s,kind:"message",ref:t.commentId,summary:`comment ${t.commentId} on ${t.channel} ${t.chatId}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var is;function V(){return is||(is=new as),is}Pn();var cl=/\breq-[0-9A-HJKMNP-TV-Z]{26}\b/;var aa="[agentx:same-work",ul=new Set(["app","telegram","whatsapp","voice","slack","discord","email","sms","ntfy","dashboard","web-chat","tui","admin","test-drive","workflow-editor","guest","public-api"]);function ll(n){return!!n&&ul.has(n)}var gl=new Set(["a2a","cron","workflow","reminder","events","business"]);function da(n){return!!n&&gl.has(n)}function ca(n,e){return!n||ll(e)||n.startsWith(aa)?null:cl.exec(n)?.[0]??null}var an=class{constructor(e={}){this.opts=e}holders=new Map;ended=new Map;now(){return this.opts.now?.()??Date.now()}async enter(e,t,s,r){let o=`${e}\0${t}`,i=this.now(),a=this.opts.waitMs??9e5,c=!1;for(;;){let y=this.holders.get(o);if(!y||s&&y.rootId===s)break;if(r?.aborted||this.now()-i>a){this.opts.log?.(`[${e}] ${t}: going ahead beside a run still on it (waited ${Math.round((this.now()-i)/1e3)}s)`);break}c||this.opts.log?.(`[${e}] ${t}: another run of this agent is on it; waiting for it to end`),c=!0,await Promise.race([y.done,(this.opts.sleep??ml)(1e3)])}let d,u=new Promise(y=>{d=y}),l={rootId:s,startedAt:this.now(),done:u};this.holders.get(o)||this.holders.set(o,l);let f=this.ended.get(o);return{note:f&&this.now()-f.at<=27e5?pl(t,f,this.now()):"",waitedMs:this.now()-i,release:({text:y,ok:A,ran:x=!0})=>{this.holders.get(o)===l&&this.holders.delete(o),x&&this.ended.set(o,{at:this.now(),text:y,ok:A}),this.prune(),d()}}}prune(){let e=this.now()-27e5;for(let[t,s]of this.ended)s.at<e&&this.ended.delete(t)}};function pl(n,e,t){let s=Math.max(0,Math.round((t-e.at)/6e4)),r=e.text.length>1500?e.text.slice(0,1500-1)+"\u2026":e.text;return[`${aa} key=${n}]`,`Another run of yours worked on ${n} and ended ${s===0?"just now":`${s} min ago`}${e.ok?"":" (it failed)"}. It answered:`,r||"(no answer)","","Do not do again what it already did. Check the live state, build on it, or say it is already done.","","The new message:",""].join(`
102
91
  `)}function ml(n){return new Promise(e=>setTimeout(e,n))}var fl="[agentx:notices",dn=class{constructor(e={}){this.opts=e}byAgent=new Map;now(){return this.opts.now?.()??Date.now()}add(e,t,s){let r=this.byAgent.get(e)??[];for(r.push({from:t,text:s.length>1e3?s.slice(0,1e3-1)+"\u2026":s,at:this.now()});r.length>20;)r.shift();return this.byAgent.set(e,r),r.length}count(e){return this.byAgent.get(e)?.length??0}take(e){let t=this.byAgent.get(e);return t?.length?(this.byAgent.delete(e),hl(t,this.now())):""}overdue(){let e=this.opts.maxHoldMs??36e5,t=[];for(let[s,r]of this.byAgent)r.length&&this.now()-r[0].at>=e&&t.push(s);return t}};function hl(n,e){let t=n.map(s=>{let r=Math.max(0,Math.round((e-s.at)/6e4));return`- ${r===0?"just now":`${r} min ago`}, from ${s.from}: ${s.text.replace(/\s*\n\s*/g," ")}`});return[`${fl} count=${n.length}]`,"For your information; these did not need a run of their own. Act on one only if it changes your work.",...t,"",""].join(`
103
- `)}_n();var ca=["manual","notify","auto"];function yl(n){return typeof n=="string"&&ca.includes(n)}var as={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var wl=7*24*60*6e4,lt=class{constructor(e={},t){this.store=t;this.opts={...as,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-wl;for(let[o,i]of Object.entries(s))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,s){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:Ue(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:bl(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function bl(n,e){return n.length<=e?n:`${n.slice(0,e)}
104
- \u2026[truncated ${n.length-e} chars]`}Pc();import{z as xl}from"zod";var la=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Sl(n){if(n==null)return{ok:!0,subscriptions:la};let e=xl.array($r).min(1).safeParse(n);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var Il=15,Tl=1500,ua=200;function ga(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function kl(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function Wh(n,e,t={}){let s=kl(e,n.cursor),r=s.length?ga(s):n.cursor,o=s.filter(c=>n.subscriptions.some(u=>uo(u,c)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:d}=vl(o,i,t);return{text:a,cursor:r,matched:o.length,shown:d}}function vl(n,e,t={}){let s=Math.max(3,t.maxLines??Il),r=Math.max(200,t.maxChars??Tl),o=n.map(a=>Al(`- ${go(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let d=i-a,u=[d?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];d&&u.push(`+${d} more \u2014 \`agentx events --since ${e}\``);let l=u.join(`
105
- `);if(u.length<=s&&l.length<=r)return{text:l,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Al(n){return n.length<=ua?n:`${n.slice(0,ua-1)}\u2026`}import{existsSync as $l,mkdirSync as Cl,readFileSync as Ml,renameSync as Rl,writeFileSync as _l}from"node:fs";import{homedir as Pl}from"node:os";import{dirname as El,join as Ol}from"node:path";function Dl(n){return{load:()=>$l(n)?JSON.parse(Ml(n,"utf-8")):{},save:e=>{Cl(El(n),{recursive:!0});let t=`${n}.tmp`;_l(t,JSON.stringify(e,null,2),{mode:384}),Rl(t,n)}}}function Ll(){if(!process.env.VITEST)return Dl(process.env.AGENTX_ATTACH_BINDINGS_FILE??Ol(Pl(),".agentx","attach-bindings.json"))}var ds;function pa(){return ds||(ds=new lt({},Ll())),ds}Pn();import{readFileSync as Nl}from"fs";import{homedir as Bl}from"os";import{join as Fl}from"path";var gt=null,Ul=6e4;function Hl(){try{let n=Fl(Bl(),".claude.json"),e=Nl(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function jl(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Wl(n=!1){let e=Date.now();return!n&&gt&&e-gt.checkedAt<Ul||(gt=jl(Hl(),e)),gt}function ma(n){let e=Wl();return e.available||n?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var ha={warnRatio:.8},ze={...ha},ql=5*60*60*1e3,Gl=60*60*1e3,Ee=[];function ya(n){ze={...ha,...n||{}}}function wa(n){let e=n-ql,t=0;for(;t<Ee.length&&Ee[t]<e;)t++;t>0&&Ee.splice(0,t)}function ba(n=Date.now()){wa(n),Ee.push(n)}var Oe=new Map,Kl=15*60*1e3,Jl=24*60*60*1e3,ls=new Map;function cn(n){return n.resetsAt??n.seenAt+Kl}function cs(n,e,t){n.status!=="rejected"||n.usingOverage||ls.set(n.window,{window:n.window,heldSince:n.seenAt,...n.resetsAt&&{resetsAt:n.resetsAt},liftedAt:e,how:t})}function sy(n=Date.now()){let e=new Map(ls);for(let t of Oe.values()){if(t.status!=="rejected"||t.usingOverage)continue;let s=cn(t);s<=n?e.set(t.window,{window:t.window,heldSince:t.seenAt,...t.resetsAt&&{resetsAt:t.resetsAt},liftedAt:s,how:"reset"}):e.delete(t.window)}return[...e.values()].filter(t=>n-t.liftedAt<Jl).sort((t,s)=>s.liftedAt-t.liftedAt)}var us=null;function gs(n,e=Date.now(),t){if(!n||typeof n!="object")return;let s=n;if(s.type!=="system"||s.subtype!=="init")return;let r=o=>typeof o=="string"&&o?o:void 0;us={...t&&{agentId:t},...r(s.apiKeySource)&&{apiKeySource:r(s.apiKeySource)},...r(s.claude_code_version)&&{cliVersion:r(s.claude_code_version)},...r(s.model)&&{model:r(s.model)},seenAt:e}}function ry(){return us?{...us}:null}function xa(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function zl(n){let e=xa(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ql(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=zl(s.resetsAt??s.resets_at),a=xa(s.utilization),d=s.overageStatus??s.overage_status,c=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||d==="allowed"||d==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...c&&{usingOverage:c},seenAt:e}}function Sa(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Ia(n,e){let t=Sa(n);return!t||!e||e.toLowerCase().includes(t)}function ps(n,e=Date.now(),t){let s=Ql(n,e);if(!s)return null;if(s.status!=="rejected"){for(let[r,o]of Oe)if(o.status==="rejected"){if(r===s.window){cn(o)>e&&cs(o,e,"served");continue}(!Sa(r)||t&&Ia(r,t))&&(cn(o)>e&&cs(o,e,"served"),Oe.delete(r))}}else ls.delete(s.window);return Oe.set(s.window,s),s}function Ta(n=Date.now()){return[...Oe.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:cn(e)>n)}function Xl(n=Date.now(),e){return Ta(n).find(t=>Ia(t.window,e))??null}function oy(n=Date.now()){let e=Ta(n);for(let t of e)cs(t,n,"operator"),Oe.delete(t.window);return e}function Yl(){return[...Oe.values()].sort((n,e)=>e.seenAt-n.seenAt)}function fa(n){return typeof n=="number"&&n>0}function ka(n=Date.now()){wa(n);let e=n-Gl,t=0;for(let o=Ee.length-1;o>=0&&Ee[o]>=e;o--)t++;let s=Ee.length,r={lastHour:t,last5h:s,maxPerHour:fa(ze.maxPerHour)?ze.maxPerHour:void 0,maxPer5h:fa(ze.maxPer5h)?ze.maxPer5h:void 0,provider:Yl()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function va(n){return n.replace(/_/g," ")}function Aa(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function $a(n,e=Date.now(),t){let s=ka(e);if(n)return null;let r=Xl(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${va(r.window)} window as rejected. Cold dispatches are held until it resets ${Aa(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.maxPerHour} claude-code runs in the last hour. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPerHour in agentx.json (applies on save).`,usage:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.maxPer5h} claude-code runs in the last 5h. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPer5h in agentx.json (applies on save).`,usage:s}:null}function Ca(n=Date.now()){let e=ka(n),t=e.provider.find(r=>r.status==="allowed_warning");if(t){let r=t.utilization!==void 0?` (${Math.round(t.utilization*100)}% used)`:"";return`claude plan ${va(t.window)} window nearing its limit${r}, resets ${Aa(t.resetsAt,n)}`}let s=ze.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of local cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}import{existsSync as Zl,mkdirSync as Vl,readFileSync as eg,renameSync as tg,writeFileSync as ng}from"fs";import{dirname as sg}from"path";var ms=200,un=class{constructor(e=ms,t,s=()=>{}){this.max=e;this.file=t;this.log=s;t&&this.load(t)}held=new Map;hold(e,t){let s=this.held.get(e)??[];if(s.length>=this.max)return"full";let r=s.some(o=>o.channel===t.channel&&o.chatId===t.chatId);return s.push(t),this.held.set(e,s),this.save(),r?"held":"held-first"}count(e){return this.held.get(e)?.length??0}agents(){return[...this.held.keys()]}take(e,t=()=>!0){let s=this.held.get(e)??[],r=s.filter(t);if(!r.length)return[];let o=s.filter(i=>!r.includes(i));return o.length?this.held.set(e,o):this.held.delete(e),this.save(),r}get size(){let e=0;for(let t of this.held.values())e+=t.length;return e}load(e){if(Zl(e))try{let t=JSON.parse(eg(e,"utf-8"));for(let[s,r]of Object.entries(t??{})){let o=(Array.isArray(r)?r:[]).filter(i=>i&&typeof i.text=="string"&&typeof i.channel=="string"&&typeof i.chatId=="string").slice(0,this.max);o.length&&this.held.set(s,o)}}catch(t){this.log(`[budget] couldn't read held messages from ${e} (${t?.message??t}); starting empty`)}}save(){if(this.file)try{Vl(sg(this.file),{recursive:!0});let e=`${this.file}.tmp`;ng(e,JSON.stringify(Object.fromEntries(this.held))),tg(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var fs=new Map;function Ma(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function Ra(n,e,t,s=Date.now()){let r=fs.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},fs.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function _a(n){let e=fs.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as ug,readFileSync as lg}from"fs";import{resolve as gg}from"path";import{existsSync as rg,readFileSync as og,unlinkSync as ig,writeFileSync as ag}from"fs";import{resolve as Ea}from"path";var Pa="_agentxManaged";function ln(n=process){let e=n.argv[1]?Ea(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function my(n,e){return!e||n.agentx?n:{...n,agentx:e}}function fy(n,e){let t=Ea(n,".mcp.json"),s=rg(t),r=s?cg(t):null,o=r!==null&&r[Pa]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return ig(t),"removed";let a={[Pa]:!0,mcpServers:dg(e)};return ag(t,JSON.stringify(a,null,2)+`
106
- `),s?"updated":"installed"}function dg(n){let e={};for(let[t,s]of Object.entries(n)){let{allowTools:r,readTools:o,...i}=s;if(i.type==="http"){let{headersEnv:a,headers:d,...c}=i,u=Hr(s);e[t]=u?{...c,headers:u}:c}else e[t]=i}return e}function cg(n){try{return JSON.parse(og(n,"utf-8"))}catch{return null}}var pg=["github","a2a","workflow","cron"],mg=["claude-code","codex-cli"],fg={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},hg="AGENTX_MCP_TOOLS",yg=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint","agentx_node"],wg=["agentx_agents","agentx_recent","agentx_wiki_query"];function Da(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function La(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...yg,...n.contextOnDemand?wg:[],...s];return Array.from(new Set(r))}function bg(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[hg]:e.join(",")}}}function Na(n,e,t){if(!mg.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(pg.includes(e)?"lean":"full")}function Ba(n){return{...fg,...n?.lean??{}}}function Fa(n){return n.settingSources.includes("project")}function xg(n,e,t=ln(),s){let r=Ua(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=bg(o.agentx??r.agentx??t,La(e,s)),o}function Ua(n){let e=gg(n,".mcp.json");if(!ug(e))return{};try{let s=JSON.parse(lg(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function Ha(n,e,t=ln(),s){let r=xg(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Da(e,s);return i.length&&o.push("--tools",Wa(i).join(",")),o}function ja(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Oa="ToolSearch";function Wa(n){return n.includes(Oa)?n:[...n,Oa]}function qa(n,e=ln()){let t=Ua(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function Ga(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), stored knowledge (agentx_wiki_query), and this machine, its programs, Claude usage limits and running work (agentx_node: answer from it with its check time, never from memory).`].join(`
107
- `)}function Ka(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=Da(e,t);r.length&&s.push(`tools=${Wa(r).join("+")}`);let o=La(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ae,mkdirSync as Sm,readdirSync as ye,readFileSync as bt,rmSync as Im,writeFileSync as Tm}from"fs";import{resolve as G}from"path";import{randomUUID as km}from"crypto";import{existsSync as Le,mkdirSync as hs,readFileSync as Sg,readdirSync as Ig,renameSync as Tg,unlinkSync as kg,writeFileSync as gn}from"fs";import{resolve as ke,relative as pn}from"path";import{z as Y}from"zod";var De=Y.object({id:Y.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:Y.string().min(1),trigger:Y.string().min(1,"procedures must describe when they apply"),inputs:Y.array(Y.string()).default([]),expected:Y.string().optional(),kpis:Y.array(Y.string()).default([]),owner:Y.string().optional(),tags:Y.array(Y.string()).default([]),status:Y.enum(["draft","active","deprecated"]).default("active"),source:Y.string().optional(),evidence:Y.array(Y.string()).default([]),created:Y.string().optional(),updated:Y.string().optional(),related:Y.array(Y.string()).default([])});function vg(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
92
+ `)}Pn();var ua=["manual","notify","auto"];function yl(n){return typeof n=="string"&&ua.includes(n)}var ds={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var wl=7*24*60*6e4,lt=class{constructor(e={},t){this.store=t;this.opts={...ds,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-wl;for(let[o,i]of Object.entries(s))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,s){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:Ue(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:bl(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function bl(n,e){return n.length<=e?n:`${n.slice(0,e)}
93
+ \u2026[truncated ${n.length-e} chars]`}Ec();import{z as xl}from"zod";var ga=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Sl(n){if(n==null)return{ok:!0,subscriptions:ga};let e=xl.array($r).min(1).safeParse(n);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var Il=15,Tl=1500,la=200;function pa(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function kl(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function jh(n,e,t={}){let s=kl(e,n.cursor),r=s.length?pa(s):n.cursor,o=s.filter(d=>n.subscriptions.some(u=>uo(u,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:c}=vl(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function vl(n,e,t={}){let s=Math.max(3,t.maxLines??Il),r=Math.max(200,t.maxChars??Tl),o=n.map(a=>Al(`- ${go(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let c=i-a,u=[c?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];c&&u.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let l=u.join(`
94
+ `);if(u.length<=s&&l.length<=r)return{text:l,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Al(n){return n.length<=la?n:`${n.slice(0,la-1)}\u2026`}import{existsSync as $l,mkdirSync as Cl,readFileSync as Ml,renameSync as Rl,writeFileSync as _l}from"node:fs";import{homedir as Pl}from"node:os";import{dirname as El,join as Ol}from"node:path";function Dl(n){return{load:()=>$l(n)?JSON.parse(Ml(n,"utf-8")):{},save:e=>{Cl(El(n),{recursive:!0});let t=`${n}.tmp`;_l(t,JSON.stringify(e,null,2),{mode:384}),Rl(t,n)}}}function Ll(){if(!process.env.VITEST)return Dl(process.env.AGENTX_ATTACH_BINDINGS_FILE??Ol(Pl(),".agentx","attach-bindings.json"))}var cs;function ma(){return cs||(cs=new lt({},Ll())),cs}En();import{readFileSync as Nl}from"fs";import{homedir as Bl}from"os";import{join as Fl}from"path";var gt=null,Ul=6e4;function Hl(){try{let n=Fl(Bl(),".claude.json"),e=Nl(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function jl(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Wl(n=!1){let e=Date.now();return!n&&gt&&e-gt.checkedAt<Ul||(gt=jl(Hl(),e)),gt}function fa(n){let e=Wl();return e.available||n?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var ya={warnRatio:.8},ze={...ya},ql=5*60*60*1e3,Gl=60*60*1e3,Ee=[];function wa(n){ze={...ya,...n||{}}}function ba(n){let e=n-ql,t=0;for(;t<Ee.length&&Ee[t]<e;)t++;t>0&&Ee.splice(0,t)}function xa(n=Date.now()){ba(n),Ee.push(n)}var Oe=new Map,Kl=15*60*1e3,Jl=24*60*60*1e3,gs=new Map;function cn(n){return n.resetsAt??n.seenAt+Kl}function us(n,e,t){n.status!=="rejected"||n.usingOverage||gs.set(n.window,{window:n.window,heldSince:n.seenAt,...n.resetsAt&&{resetsAt:n.resetsAt},liftedAt:e,how:t})}function ny(n=Date.now()){let e=new Map(gs);for(let t of Oe.values()){if(t.status!=="rejected"||t.usingOverage)continue;let s=cn(t);s<=n?e.set(t.window,{window:t.window,heldSince:t.seenAt,...t.resetsAt&&{resetsAt:t.resetsAt},liftedAt:s,how:"reset"}):e.delete(t.window)}return[...e.values()].filter(t=>n-t.liftedAt<Jl).sort((t,s)=>s.liftedAt-t.liftedAt)}var ls=null;function ps(n,e=Date.now(),t){if(!n||typeof n!="object")return;let s=n;if(s.type!=="system"||s.subtype!=="init")return;let r=o=>typeof o=="string"&&o?o:void 0;ls={...t&&{agentId:t},...r(s.apiKeySource)&&{apiKeySource:r(s.apiKeySource)},...r(s.claude_code_version)&&{cliVersion:r(s.claude_code_version)},...r(s.model)&&{model:r(s.model)},seenAt:e}}function sy(){return ls?{...ls}:null}function Sa(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function zl(n){let e=Sa(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ql(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=zl(s.resetsAt??s.resets_at),a=Sa(s.utilization),c=s.overageStatus??s.overage_status,d=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||c==="allowed"||c==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...d&&{usingOverage:d},seenAt:e}}function Ia(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Ta(n,e){let t=Ia(n);return!t||!e||e.toLowerCase().includes(t)}function ms(n,e=Date.now(),t){let s=Ql(n,e);if(!s)return null;if(s.status!=="rejected"){for(let[r,o]of Oe)if(o.status==="rejected"){if(r===s.window){cn(o)>e&&us(o,e,"served");continue}(!Ia(r)||t&&Ta(r,t))&&(cn(o)>e&&us(o,e,"served"),Oe.delete(r))}}else gs.delete(s.window);return Oe.set(s.window,s),s}function ka(n=Date.now()){return[...Oe.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:cn(e)>n)}function Xl(n=Date.now(),e){return ka(n).find(t=>Ta(t.window,e))??null}function ry(n=Date.now()){let e=ka(n);for(let t of e)us(t,n,"operator"),Oe.delete(t.window);return e}function Yl(){return[...Oe.values()].sort((n,e)=>e.seenAt-n.seenAt)}function ha(n){return typeof n=="number"&&n>0}function va(n=Date.now()){ba(n);let e=n-Gl,t=0;for(let o=Ee.length-1;o>=0&&Ee[o]>=e;o--)t++;let s=Ee.length,r={lastHour:t,last5h:s,maxPerHour:ha(ze.maxPerHour)?ze.maxPerHour:void 0,maxPer5h:ha(ze.maxPer5h)?ze.maxPer5h:void 0,provider:Yl()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function Aa(n){return n.replace(/_/g," ")}function $a(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function Ca(n,e=Date.now(),t){let s=va(e);if(n)return null;let r=Xl(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Aa(r.window)} window as rejected. Cold dispatches are held until it resets ${$a(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.maxPerHour} claude-code runs in the last hour. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPerHour in agentx.json (applies on save).`,usage:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.maxPer5h} claude-code runs in the last 5h. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPer5h in agentx.json (applies on save).`,usage:s}:null}function Ma(n=Date.now()){let e=va(n),t=e.provider.find(r=>r.status==="allowed_warning");if(t){let r=t.utilization!==void 0?` (${Math.round(t.utilization*100)}% used)`:"";return`claude plan ${Aa(t.window)} window nearing its limit${r}, resets ${$a(t.resetsAt,n)}`}let s=ze.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of local cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}import{existsSync as Zl,mkdirSync as Vl,readFileSync as eg,renameSync as tg,writeFileSync as ng}from"fs";import{dirname as sg}from"path";var fs=200,un=class{constructor(e=fs,t,s=()=>{}){this.max=e;this.file=t;this.log=s;t&&this.load(t)}held=new Map;hold(e,t){let s=this.held.get(e)??[];if(s.length>=this.max)return"full";let r=s.some(o=>o.channel===t.channel&&o.chatId===t.chatId);return s.push(t),this.held.set(e,s),this.save(),r?"held":"held-first"}count(e){return this.held.get(e)?.length??0}agents(){return[...this.held.keys()]}take(e,t=()=>!0){let s=this.held.get(e)??[],r=s.filter(t);if(!r.length)return[];let o=s.filter(i=>!r.includes(i));return o.length?this.held.set(e,o):this.held.delete(e),this.save(),r}get size(){let e=0;for(let t of this.held.values())e+=t.length;return e}load(e){if(Zl(e))try{let t=JSON.parse(eg(e,"utf-8"));for(let[s,r]of Object.entries(t??{})){let o=(Array.isArray(r)?r:[]).filter(i=>i&&typeof i.text=="string"&&typeof i.channel=="string"&&typeof i.chatId=="string").slice(0,this.max);o.length&&this.held.set(s,o)}}catch(t){this.log(`[budget] couldn't read held messages from ${e} (${t?.message??t}); starting empty`)}}save(){if(this.file)try{Vl(sg(this.file),{recursive:!0});let e=`${this.file}.tmp`;ng(e,JSON.stringify(Object.fromEntries(this.held))),tg(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var hs=new Map;function Ra(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function _a(n,e,t,s=Date.now()){let r=hs.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},hs.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function Pa(n){let e=hs.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as ug,readFileSync as lg}from"fs";import{resolve as gg}from"path";import{existsSync as rg,readFileSync as og,unlinkSync as ig,writeFileSync as ag}from"fs";import{resolve as Oa}from"path";var Ea="_agentxManaged";function ln(n=process){let e=n.argv[1]?Oa(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function py(n,e){return!e||n.agentx?n:{...n,agentx:e}}function my(n,e){let t=Oa(n,".mcp.json"),s=rg(t),r=s?cg(t):null,o=r!==null&&r[Ea]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return ig(t),"removed";let a={[Ea]:!0,mcpServers:dg(e)};return ag(t,JSON.stringify(a,null,2)+`
95
+ `),s?"updated":"installed"}function dg(n){let e={};for(let[t,s]of Object.entries(n)){let{allowTools:r,readTools:o,...i}=s;if(i.type==="http"){let{headersEnv:a,headers:c,...d}=i,u=Hr(s);e[t]=u?{...d,headers:u}:d}else e[t]=i}return e}function cg(n){try{return JSON.parse(og(n,"utf-8"))}catch{return null}}var pg=["github","a2a","workflow","cron"],mg=["claude-code","codex-cli"],fg={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},hg="AGENTX_MCP_TOOLS",yg=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint","agentx_node"],wg=["agentx_agents","agentx_recent","agentx_wiki_query"];function La(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function Na(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...yg,...n.contextOnDemand?wg:[],...s];return Array.from(new Set(r))}function bg(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[hg]:e.join(",")}}}function Ba(n,e,t){if(!mg.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(pg.includes(e)?"lean":"full")}function Fa(n){return{...fg,...n?.lean??{}}}function Ua(n){return n.settingSources.includes("project")}function xg(n,e,t=ln(),s){let r=Ha(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=bg(o.agentx??r.agentx??t,Na(e,s)),o}function Ha(n){let e=gg(n,".mcp.json");if(!ug(e))return{};try{let s=JSON.parse(lg(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function ja(n,e,t=ln(),s){let r=xg(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=La(e,s);return i.length&&o.push("--tools",qa(i).join(",")),o}function Wa(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Da="ToolSearch";function qa(n){return n.includes(Da)?n:[...n,Da]}function Ga(n,e=ln()){let t=Ha(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function Ka(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), stored knowledge (agentx_wiki_query), and this machine, its programs, Claude usage limits and running work (agentx_node: answer from it with its check time, never from memory).`].join(`
96
+ `)}function Ja(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=La(e,t);r.length&&s.push(`tools=${qa(r).join("+")}`);let o=Na(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ae,mkdirSync as Sm,readdirSync as ye,readFileSync as bt,rmSync as Im,writeFileSync as Tm}from"fs";import{resolve as G}from"path";import{randomUUID as km}from"crypto";import{existsSync as Le,mkdirSync as ys,readFileSync as Sg,readdirSync as Ig,renameSync as Tg,unlinkSync as kg,writeFileSync as gn}from"fs";import{resolve as ke,relative as pn}from"path";import{z as Y}from"zod";var De=Y.object({id:Y.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:Y.string().min(1),trigger:Y.string().min(1,"procedures must describe when they apply"),inputs:Y.array(Y.string()).default([]),expected:Y.string().optional(),kpis:Y.array(Y.string()).default([]),owner:Y.string().optional(),tags:Y.array(Y.string()).default([]),status:Y.enum(["draft","active","deprecated"]).default("active"),source:Y.string().optional(),evidence:Y.array(Y.string()).default([]),created:Y.string().optional(),updated:Y.string().optional(),related:Y.array(Y.string()).default([])});function vg(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
108
97
  `)){let r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function mn(n){let e=["---"];return e.push(`id: ${n.id}`),e.push(`title: "${n.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${n.trigger.replace(/"/g,'\\"')}"`),n.inputs?.length&&e.push(`inputs: ${JSON.stringify(n.inputs)}`),n.expected&&e.push(`expected: "${n.expected.replace(/"/g,'\\"')}"`),n.kpis?.length&&e.push(`kpis: ${JSON.stringify(n.kpis)}`),n.owner&&e.push(`owner: ${n.owner}`),n.tags?.length&&e.push(`tags: ${JSON.stringify(n.tags)}`),e.push(`status: ${n.status}`),n.source&&e.push(`source: "${n.source.replace(/"/g,'\\"')}"`),n.evidence?.length&&e.push(`evidence: ${JSON.stringify(n.evidence)}`),n.related?.length&&e.push(`related: ${JSON.stringify(n.related)}`),n.created&&e.push(`created: ${n.created}`),n.updated&&e.push(`updated: ${n.updated}`),e.push("---"),e.join(`
109
- `)}var pt=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ke(process.cwd(),".agentx/procedures"),hs(this.baseDir,{recursive:!0})}pathFor(e){return ke(this.baseDir,`${e}.md`)}get draftsDir(){return ke(this.baseDir,"_drafts")}draftPathFor(e){return ke(this.draftsDir,`${e}.md`)}parseFile(e){let t=Sg(e,"utf-8"),{meta:s,body:r}=vg(t),o=De.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:pn(this.baseDir,e)}:null}listDir(e){if(!Le(e))return[];let t=[];for(let s of Ig(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(ke(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return Le(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return Le(t)?this.parseFile(t):null}add(e,t){let s=De.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(Le(r))throw new Error(`Procedure already exists: ${s.id}`);return gn(r,mn(s)+`
98
+ `)}var pt=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??ke(process.cwd(),".agentx/procedures"),ys(this.baseDir,{recursive:!0})}pathFor(e){return ke(this.baseDir,`${e}.md`)}get draftsDir(){return ke(this.baseDir,"_drafts")}draftPathFor(e){return ke(this.draftsDir,`${e}.md`)}parseFile(e){let t=Sg(e,"utf-8"),{meta:s,body:r}=vg(t),o=De.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:pn(this.baseDir,e)}:null}listDir(e){if(!Le(e))return[];let t=[];for(let s of Ig(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(ke(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return Le(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return Le(t)?this.parseFile(t):null}add(e,t){let s=De.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(Le(r))throw new Error(`Procedure already exists: ${s.id}`);return gn(r,mn(s)+`
110
99
 
111
100
  `+t.trim()+`
112
101
  `),{meta:s,body:t.trim(),path:pn(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=De.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return gn(this.pathFor(e),mn(o)+`
113
102
 
114
103
  `+i.trim()+`
115
- `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=De.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(s.id))throw new Error(`Procedure already exists: ${s.id}`);let r=this.draftPathFor(s.id);if(Le(r))throw new Error(`Draft already exists: ${s.id}`);return hs(this.draftsDir,{recursive:!0}),gn(r,mn(s)+`
104
+ `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=De.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(s.id))throw new Error(`Procedure already exists: ${s.id}`);let r=this.draftPathFor(s.id);if(Le(r))throw new Error(`Draft already exists: ${s.id}`);return ys(this.draftsDir,{recursive:!0}),gn(r,mn(s)+`
116
105
 
117
106
  `+t.trim()+`
118
107
  `),{meta:s,body:t.trim(),path:pn(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let s=De.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return gn(this.pathFor(e),mn(s)+`
119
108
 
120
109
  `+t.body+`
121
- `),kg(this.draftPathFor(e)),{meta:s,body:t.body,path:pn(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!Le(t))throw new Error(`Draft not found: ${e}`);let s=ke(this.draftsDir,"_rejected");hs(s,{recursive:!0}),Tg(t,ke(s,`${e}.md`))}isRejected(e){return Le(ke(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Ag,mkdirSync as $g,readFileSync as Cg,writeFileSync as Mg}from"fs";import{dirname as Rg,resolve as _g}from"path";import{z as ie}from"zod";var Pg=ie.object({key:ie.string(),count:ie.number().int().min(0).default(0),firstSeen:ie.string(),lastSeen:ie.string(),taskIds:ie.array(ie.string()).default([]),sampleMessage:ie.string().default(""),status:ie.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:ie.string().optional()}),Eg=ie.object({minedThrough:ie.string().optional(),candidates:ie.array(Pg).default([])});function Ja(n){return _g(n,"_candidates.json")}function Og(n){let e=Ja(n);if(!Ag(e))return{candidates:[]};try{let t=Eg.safeParse(JSON.parse(Cg(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Dg(n,e){let t=Ja(n);$g(Rg(t),{recursive:!0}),Mg(t,JSON.stringify(e,null,2)+`
122
- `)}function Lg(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function Ng(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function Bg(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function ys(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function za(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function ws(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=ys(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let d=[],c=za(o,ys(a.meta.trigger));c>0&&d.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=za(o,ys(u));l>0&&d.push("title/tags");let p=Math.min(1,c*.7+l*.5);p>=r&&i.push({procedure:a,score:p,reasons:d})}return i.sort((a,d)=>d.score-a.score).slice(0,s)}function bs(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
110
+ `),kg(this.draftPathFor(e)),{meta:s,body:t.body,path:pn(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!Le(t))throw new Error(`Draft not found: ${e}`);let s=ke(this.draftsDir,"_rejected");ys(s,{recursive:!0}),Tg(t,ke(s,`${e}.md`))}isRejected(e){return Le(ke(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Ag,mkdirSync as $g,readFileSync as Cg,writeFileSync as Mg}from"fs";import{dirname as Rg,resolve as _g}from"path";import{z as ie}from"zod";var Pg=ie.object({key:ie.string(),count:ie.number().int().min(0).default(0),firstSeen:ie.string(),lastSeen:ie.string(),taskIds:ie.array(ie.string()).default([]),sampleMessage:ie.string().default(""),status:ie.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:ie.string().optional()}),Eg=ie.object({minedThrough:ie.string().optional(),candidates:ie.array(Pg).default([])});function za(n){return _g(n,"_candidates.json")}function Og(n){let e=za(n);if(!Ag(e))return{candidates:[]};try{let t=Eg.safeParse(JSON.parse(Cg(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Dg(n,e){let t=za(n);$g(Rg(t),{recursive:!0}),Mg(t,JSON.stringify(e,null,2)+`
111
+ `)}function Lg(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function Ng(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function Bg(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function ws(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Qa(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function bs(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=ws(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Qa(o,ws(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=Qa(o,ws(u));l>0&&c.push("title/tags");let p=Math.min(1,d*.7+l*.5);p>=r&&i.push({procedure:a,score:p,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,s)}function xs(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
123
112
  `)})].join(`
124
113
 
125
- `)}Dn();Lt();var Ss="turn-progress",Qa={progress:He({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},xs=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function Xa(n){return{agent:n.agent,request:xs(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:xs(e.input,300),...e.result!==void 0?{result:xs(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}Lt();var Ya="turn-handoff",Za="approval-binding",Va={nextStep:He({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},ed={approves:nt("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},Fg=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,td=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,Ug=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Is(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Ug.test(e.split(`
126
- `).slice(-3).join(" ")):!1}var Hg=/^\s*(yes|yep|yeah|ok(ay)?|sure|go( ahead)?|proceed|do it|please do|confirmed?|approved?|go-ahead|let'?s go|oui|نعم)\b/i;function nd(n){return n.trim().length<=160&&Hg.test(n)}function sd(n){return n.trim().length<=160}function rd(n){return{agent:n.agent,channel:n.channel,request:Fg(n.request,1500),agentReplyEnding:td(n.reply,1200)}}function od(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:td(n.previousReply,1200)}}var jg=5*6e4,Wg=3,qg=12,Gg=24*60*6e4,id=new Set(["cron","heartbeat","bench","a2a","business"]),Kg={observe(){},stop(){}};function ad(n){if(Nt(Ss)==="off")return Kg;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let p;for(let[f,h]of o)h>1&&(!p||h>p.times)&&(p={call:f,times:h});return p},u=p=>{if(d)return;d=!0,a=s.length;let f=Xa({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-qg),repeated:c(),trigger:p});Se(Ss,f,Qa,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:p}}).finally(()=>{d=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??jg);return l.unref?.(),{observe(p){let f=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let h of f){if(h?.type!=="tool_use")continue;let y=h.input?JSON.stringify(h.input):"",A={tool:h.name||"tool",input:y};s.push(A),typeof h.id=="string"&&r.set(h.id,A);let x=`${A.tool}(${y})`,E=(o.get(x)??0)+1;o.set(x,E),E>=Wg&&!i.has(x)&&(i.add(x),u("repetition"))}else if(p?.type==="user")for(let h of f){if(h?.type!=="tool_result")continue;let y=r.get(h.tool_use_id);y&&(y.result=Array.isArray(h.content)?h.content.map(A=>typeof A?.text=="string"?A.text:"").join(""):typeof h.content=="string"?h.content:"",h.is_error&&(y.error=!0))}},stop(){clearInterval(l)}}}var Ts=new Map,dd=(n,e,t)=>`${n}\0${e}\0${t}`;function cd(n){if(id.has(n.channel)||!Is(n.reply))return;let e=dd(n.agent,n.channel,n.chatId);Se(Ya,rd(n),Va,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&Ts.set(e,{callId:t.callId,at:Date.now()})})}function ud(n){if(id.has(n.channel))return;let e=dd(n.agent,n.channel,n.chatId),t=Ts.get(e);if(t){Ts.delete(e);let s=Cr().store;if(s&&Date.now()-t.at<Gg)try{s.label(t.callId,"userReply",nd(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!sd(n.message)||!Is(n.previousReply)||Se(Za,od({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),ed,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Cc();Rc();_c();function ld(n){let e=n?.dueAt;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}}function fn(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function Gy(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=fn(n);return!t||fn(e)?e:{...e??{},taskType:t}}Ar();function gd(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(Ne(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(d=>{a(),s(d)},d=>{a(),r(d)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function Ne(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Qe=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function pd(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Qe(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as Jg,spawn as zg}from"child_process";import{existsSync as Qg,mkdirSync as Xg,readFileSync as Yg,renameSync as Zg,statSync as Vg,writeFileSync as ep}from"fs";import{dirname as tp}from"path";var yn={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function np(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function ks(n){try{return!n||!Qg(n)?void 0:Jg("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function mt(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function md(n){let e={...yn,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=mt(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??ks,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let d=np(r(a));if(d&&d.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var sp=24*60*60*1e3,rp=7*sp,hn=class{constructor(e){this.file=e}sessions=[];stamp;fileStamp(){try{let e=Vg(this.file);return`${e.mtimeMs}:${e.size}`}catch{return""}}load(){let e=this.fileStamp();if(e!==this.stamp){this.stamp=e;try{let t=JSON.parse(Yg(this.file,"utf8")),s=Array.isArray(t?.sessions)?t.sessions:[];this.sessions=s.filter(r=>r&&typeof r.repo=="string"&&typeof r.sessionId=="string"&&Number.isFinite(r.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<rp);try{Xg(tp(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;ep(t,JSON.stringify({sessions:this.sessions},null,2)),Zg(t,this.file),this.stamp=this.fileStamp()}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},op=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
127
- `);function ip(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var ap=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function fd(n){return n.replace(ap,"")}function dp(n){let e=fd(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function hd(n){let e=n.spawn??((d,c,u)=>zg(d,c,u)),t=n.python??"python3",s=["-c",op,"claude",...ip(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=d=>{o+=d.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>fd(o).trim().split(`
114
+ `)}Ln();Lt();var Is="turn-progress",Xa={progress:He({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},Ss=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function Ya(n){return{agent:n.agent,request:Ss(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:Ss(e.input,300),...e.result!==void 0?{result:Ss(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}Lt();var Za="turn-handoff",Va="approval-binding",ed={nextStep:He({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},td={approves:nt("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},Fg=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,nd=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,Ug=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Ts(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Ug.test(e.split(`
115
+ `).slice(-3).join(" ")):!1}var Hg=/^\s*(yes|yep|yeah|ok(ay)?|sure|go( ahead)?|proceed|do it|please do|confirmed?|approved?|go-ahead|let'?s go|oui|نعم)\b/i;function sd(n){return n.trim().length<=160&&Hg.test(n)}function rd(n){return n.trim().length<=160}function od(n){return{agent:n.agent,channel:n.channel,request:Fg(n.request,1500),agentReplyEnding:nd(n.reply,1200)}}function id(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:nd(n.previousReply,1200)}}var jg=5*6e4,Wg=3,qg=12,Gg=24*60*6e4,ad=new Set(["cron","heartbeat","bench","a2a","business"]),Kg={observe(){},stop(){}};function dd(n){if(Nt(Is)==="off")return Kg;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let p;for(let[f,h]of o)h>1&&(!p||h>p.times)&&(p={call:f,times:h});return p},u=p=>{if(c)return;c=!0,a=s.length;let f=Ya({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-qg),repeated:d(),trigger:p});Se(Is,f,Xa,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:p}}).finally(()=>{c=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??jg);return l.unref?.(),{observe(p){let f=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let h of f){if(h?.type!=="tool_use")continue;let y=h.input?JSON.stringify(h.input):"",A={tool:h.name||"tool",input:y};s.push(A),typeof h.id=="string"&&r.set(h.id,A);let x=`${A.tool}(${y})`,E=(o.get(x)??0)+1;o.set(x,E),E>=Wg&&!i.has(x)&&(i.add(x),u("repetition"))}else if(p?.type==="user")for(let h of f){if(h?.type!=="tool_result")continue;let y=r.get(h.tool_use_id);y&&(y.result=Array.isArray(h.content)?h.content.map(A=>typeof A?.text=="string"?A.text:"").join(""):typeof h.content=="string"?h.content:"",h.is_error&&(y.error=!0))}},stop(){clearInterval(l)}}}var ks=new Map,cd=(n,e,t)=>`${n}\0${e}\0${t}`;function ud(n){if(ad.has(n.channel)||!Ts(n.reply))return;let e=cd(n.agent,n.channel,n.chatId);Se(Za,od(n),ed,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&ks.set(e,{callId:t.callId,at:Date.now()})})}function ld(n){if(ad.has(n.channel))return;let e=cd(n.agent,n.channel,n.chatId),t=ks.get(e);if(t){ks.delete(e);let s=Cr().store;if(s&&Date.now()-t.at<Gg)try{s.label(t.callId,"userReply",sd(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!rd(n.message)||!Ts(n.previousReply)||Se(Va,id({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),td,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Mc();_c();Pc();function gd(n){let e=n?.dueAt;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}}function fn(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function qy(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=fn(n);return!t||fn(e)?e:{...e??{},taskType:t}}Ar();function pd(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(Ne(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(c=>{a(),s(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function Ne(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Qe=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function md(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Qe(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as Jg,spawn as zg}from"child_process";import{existsSync as Qg,mkdirSync as Xg,readFileSync as Yg,renameSync as Zg,statSync as Vg,writeFileSync as ep}from"fs";import{dirname as tp}from"path";var yn={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function np(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function vs(n){try{return!n||!Qg(n)?void 0:Jg("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function mt(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function fd(n){let e={...yn,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=mt(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??vs,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let c=np(r(a));if(c&&c.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var sp=24*60*60*1e3,rp=7*sp,hn=class{constructor(e){this.file=e}sessions=[];stamp;fileStamp(){try{let e=Vg(this.file);return`${e.mtimeMs}:${e.size}`}catch{return""}}load(){let e=this.fileStamp();if(e!==this.stamp){this.stamp=e;try{let t=JSON.parse(Yg(this.file,"utf8")),s=Array.isArray(t?.sessions)?t.sessions:[];this.sessions=s.filter(r=>r&&typeof r.repo=="string"&&typeof r.sessionId=="string"&&Number.isFinite(r.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<rp);try{Xg(tp(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;ep(t,JSON.stringify({sessions:this.sessions},null,2)),Zg(t,this.file),this.stamp=this.fileStamp()}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},op=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
116
+ `);function ip(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var ap=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function hd(n){return n.replace(ap,"")}function dp(n){let e=hd(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function yd(n){let e=n.spawn??((c,d,u)=>zg(c,d,u)),t=n.python??"python3",s=["-c",op,"claude",...ip(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=c=>{o+=c.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>hd(o).trim().split(`
128
117
  `).slice(-5).join(`
129
- `).slice(-600);return new Promise(d=>{let c=!1,u=h=>{c||(c=!0,d(h))},l;try{l=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(h){u({ok:!1,reason:`could not start ${t}: ${h?.message||h}`,output:o});return}let p=h=>{try{l.pid&&process.kill(-l.pid,h)}catch{try{l.kill(h)}catch{}}},f=setTimeout(()=>{p("SIGTERM"),setTimeout(()=>p("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);f.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",h=>{clearTimeout(f);let y=h?.code==="ENOENT";u({ok:!1,reason:y?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${h?.message||h}`,output:o})}),l.on("close",h=>{if(clearTimeout(f),c)return;let y=dp(o);if(n.sessionId){if(h===0){u({ok:!0,sessionId:n.sessionId,url:y.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(y.sessionId&&y.url){u({ok:!0,sessionId:y.sessionId,url:y.url,output:o});return}if(h!==0){u({ok:!1,reason:`claude --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var cp=1e5;function up(n,e){let s=`
118
+ `).slice(-600);return new Promise(c=>{let d=!1,u=h=>{d||(d=!0,c(h))},l;try{l=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(h){u({ok:!1,reason:`could not start ${t}: ${h?.message||h}`,output:o});return}let p=h=>{try{l.pid&&process.kill(-l.pid,h)}catch{try{l.kill(h)}catch{}}},f=setTimeout(()=>{p("SIGTERM"),setTimeout(()=>p("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);f.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",h=>{clearTimeout(f);let y=h?.code==="ENOENT";u({ok:!1,reason:y?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${h?.message||h}`,output:o})}),l.on("close",h=>{if(clearTimeout(f),d)return;let y=dp(o);if(n.sessionId){if(h===0){u({ok:!0,sessionId:n.sessionId,url:y.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(y.sessionId&&y.url){u({ok:!0,sessionId:y.sessionId,url:y.url,output:o});return}if(h!==0){u({ok:!1,reason:`claude --cloud exited with code ${h??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var cp=1e5;function up(n,e){let s=`
130
119
 
131
120
  ---
132
121
  This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.number} in ${e.repo}. Work in this repository and open or update a pull request that references #${e.number}.`,r=cp-s.length;return`${n.length>r?`${n.slice(0,r)}
133
122
  [message cut at ${r} characters]`:n}${s}`}function lp(n,e,t){return[`Started a Claude cloud session for this ${e==="pull"?"pull request":"issue"}. The result arrives as a pull request.`,`Session: \`${n.sessionId}\``,n.url,`Comments here are forwarded to that session for the next ${t} hours.`].join(`
134
- `)}function gp(n){return/\bsession\b[^\n]{0,40}\b(?:not found|does not exist|doesn't exist|no longer exists)|no such session|not_found_error|\b404\b/i.test(n)}function pp(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function yd(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:pp(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):gp(a.reason)?(n.store.close(i.repo,i.number),n.log(`[${n.agentId}] cloud session ${i.sessionId} for ${i.repo}#${i.number} is gone, closed it, running locally: ${a.reason}`),n.trace({action:"fallback",status:"error",summary:`session ${i.sessionId} is gone, closed it: ${a.reason}`}),null):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=up(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:lp(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as yp}from"child_process";import{existsSync as wp,mkdirSync as bp,mkdtempSync as xp,readFileSync as kd,renameSync as Sp,rmSync as Ip,writeFileSync as Tp}from"fs";import{homedir as kp,tmpdir as vp}from"os";import{dirname as Ap,join as As,resolve as $s,sep as Sd}from"path";var mp=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function fp(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
123
+ `)}function gp(n){return/\bsession\b[^\n]{0,40}\b(?:not found|does not exist|doesn't exist|no longer exists)|no such session|not_found_error|\b404\b/i.test(n)}function pp(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function wd(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:pp(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):gp(a.reason)?(n.store.close(i.repo,i.number),n.log(`[${n.agentId}] cloud session ${i.sessionId} for ${i.repo}#${i.number} is gone, closed it, running locally: ${a.reason}`),n.trace({action:"fallback",status:"error",summary:`session ${i.sessionId} is gone, closed it: ${a.reason}`}),null):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=up(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:lp(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as yp}from"child_process";import{existsSync as wp,mkdirSync as bp,mkdtempSync as xp,readFileSync as vd,renameSync as Sp,rmSync as Ip,writeFileSync as Tp}from"fs";import{homedir as kp,tmpdir as vp}from"os";import{dirname as Ap,join as $s,resolve as Cs,sep as Id}from"path";var mp=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function fp(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
135
124
  `).filter(e=>!/^[ \t]*>/.test(e)).join(`
136
- `)}function wd(n,e){return ft(n)?n:`${n}
125
+ `)}function bd(n,e){return ft(n)?n:`${n}
137
126
 
138
- <!-- agentx:${e} -->`}function ft(n){if(!n)return null;let e=fp(n).match(mp);return e?e[1]:null}var bd="unknown";function Zy(n,e){let t=ft(n);return t&&(!e||t===e)?t:null}function Vy(n){return`> \u{1F916} **${n}** (via AgentX)
127
+ <!-- agentx:${e} -->`}function ft(n){if(!n)return null;let e=fp(n).match(mp);return e?e[1]:null}var xd="unknown";function Yy(n,e){let t=ft(n);return t&&(!e||t===e)?t:null}function Zy(n){return`> \u{1F916} **${n}** (via AgentX)
139
128
 
140
- `}function xd(n,e){if(!e||!n)return null;let t=ft(n);return t&&t!==bd?t:null}function ew(n,e){return e&&ft(n)===bd}function tw(n,e,t){let s=xd(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function nw(n,e,t){let s=xd(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function sw(n,e){return e||!n?n:hp(n)}function rw(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function hp(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return ft(n)?n.replace(/</g,"&lt;"):n}var vd={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Ad(n){return`spec-tests/issue-${n}`}function $d(n){return`test: spec tests for #${n}`}function $p(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var Cp=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Mp(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${Cp(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function Rp(n){let e=n.split(/\r?\n/),t=r=>r.match(/^\s*[-*]\s+\[[ xX]\]\s+(.+?)\s*$/)?.[1],s=e.findIndex(r=>/^\s*#{1,6}\s*acceptance criteria\b/i.test(r));if(s>=0){let r=[];for(let o of e.slice(s+1)){if(/^\s*#{1,6}\s/.test(o))break;let i=t(o);i&&r.push(i)}if(r.length)return r}return e.map(t).filter(r=>!!r)}function _p(n){let e=new Set;for(let t of n.matchAll(/`([^`\n]{2,160})`/g)){let s=t[1].trim();/\s/.test(s)&&!/^[\w.$]+\s*[(<]/.test(s)||/[A-Za-z_]/.test(s)&&e.add(s)}return[...e]}function Pp(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:Rp(e),interfaces:_p(`${n.title}
141
- ${e}`)}}var vs=2e4;function Ep(n){let e=n.body.length>vs?`${n.body.slice(0,vs)}
142
- [issue cut at ${vs} characters]`:n.body,t=n.acceptanceCriteria.length?n.acceptanceCriteria.map((r,o)=>`${o+1}. ${r}`).join(`
129
+ `}function Sd(n,e){if(!e||!n)return null;let t=ft(n);return t&&t!==xd?t:null}function Vy(n,e){return e&&ft(n)===xd}function ew(n,e,t){let s=Sd(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function tw(n,e,t){let s=Sd(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function nw(n,e){return e||!n?n:hp(n)}function sw(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function hp(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return ft(n)?n.replace(/</g,"&lt;"):n}var Ad={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function $d(n){return`spec-tests/issue-${n}`}function Cd(n){return`test: spec tests for #${n}`}function $p(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var Cp=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Mp(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${Cp(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function Rp(n){let e=n.split(/\r?\n/),t=r=>r.match(/^\s*[-*]\s+\[[ xX]\]\s+(.+?)\s*$/)?.[1],s=e.findIndex(r=>/^\s*#{1,6}\s*acceptance criteria\b/i.test(r));if(s>=0){let r=[];for(let o of e.slice(s+1)){if(/^\s*#{1,6}\s/.test(o))break;let i=t(o);i&&r.push(i)}if(r.length)return r}return e.map(t).filter(r=>!!r)}function _p(n){let e=new Set;for(let t of n.matchAll(/`([^`\n]{2,160})`/g)){let s=t[1].trim();/\s/.test(s)&&!/^[\w.$]+\s*[(<]/.test(s)||/[A-Za-z_]/.test(s)&&e.add(s)}return[...e]}function Pp(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:Rp(e),interfaces:_p(`${n.title}
130
+ ${e}`)}}var As=2e4;function Ep(n){let e=n.body.length>As?`${n.body.slice(0,As)}
131
+ [issue cut at ${As} characters]`:n.body,t=n.acceptanceCriteria.length?n.acceptanceCriteria.map((r,o)=>`${o+1}. ${r}`).join(`
143
132
  `):"(the issue has no checklist; take the requirements from its text)",s=n.interfaces.length?n.interfaces.map(r=>`- \`${r}\``).join(`
144
133
  `):"(none named)";return[`You are the spec-test agent for issue #${n.number} in ${n.repo}.`,"Another agent is writing the code for this issue at the same time. You do not see its code, and you must not guess at it. Write tests from the issue alone.","","## Your job","- Write one test file for this issue, following the repository's existing test conventions (framework, folder, naming). Read the existing tests and the public interfaces the issue names to get imports and signatures right.","- One test or more per acceptance criterion. Name each test after the criterion it checks, so a failure points at the criterion.","- Test behaviour through public interfaces. The code under test may not exist yet: that is expected, the tests may fail now.","- Only create or edit test files. Do not change any other file. Do not commit: the daemon commits your file.","- When a criterion cannot be tested from the issue text alone, write no test for it and say so in your final reply.","- End with a short reply: the file you wrote and one line per criterion (tested, or why not).","",`## Issue #${n.number}: ${n.title}`,e,"","## Acceptance criteria",t,"","## Interfaces the issue names",s].join(`
145
- `)}function Cd(n,e){let t=Ad(n);return["","## Spec tests (#992)",`A separate test agent ("${e}") is writing tests for this issue from the issue text only, without seeing your code. It pushes them as one commit, "${$d(n)}", to the branch \`${t}\`.`,"- Do not write those tests yourself. Do not edit or delete them, except as described below.",`- Before you open the pull request, and again before you finish, run \`git fetch origin ${t}\`. When the branch exists, merge it into your branch with \`git merge --no-ff origin/${t}\` (a merge, not a cherry-pick, squash or rebase, so the commit keeps its author), then run its tests.`,'- When a spec test fails, decide which it is. A code defect: fix the code. A test that misreads the acceptance criteria: change that test in a separate commit whose message starts with "test: spec misread" and quotes the criterion it misreads. Never skip or disable a spec test.','- In the pull request description, add a "Spec tests" section that lists each failure on the first run and your call (code defect or test misread), and ends with this line, filled in:'," <!-- agentx:spec-tests written=W failed-first-run=F code-defects=D test-misreads=M -->","- If the branch has not appeared by the time you finish, say so in that section."].join(`
146
- `)}var Op=90*24*60*60*1e3,wn=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(kd(this.file,"utf8")),t=Array.isArray(e?.runs)?e.runs:[];this.runs=t.filter(s=>s&&typeof s.repo=="string"&&Number.isInteger(s.number)&&Number.isFinite(s.startedAt))}catch{this.runs=[]}}}save(){let e=Date.now();this.runs=this.runs.filter(t=>e-t.startedAt<Op);try{bp(Ap(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Tp(t,JSON.stringify({runs:this.runs},null,2)),Sp(t,this.file)}catch{}}get(e,t){this.load();let s=e.toLowerCase();return this.runs.find(r=>r.repo.toLowerCase()===s&&r.number===t)}record(e){this.load(),this.runs=this.runs.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.runs.push(e),this.save()}all(){return this.load(),[...this.runs]}},Dp=10*6e4;function Cs(n,e,t=Date.now()){if(n){if(n.status!=="running")return`spec tests already ran for this issue (${n.status})`;if(!(t-n.startedAt>e.maxMinutes*6e4+Dp))return"spec tests are already running for this issue"}}function Md(n){let{settings:e,issue:t}=n;if(!e.enabled)return{run:!1,reason:"spec tests are off"};if(!t)return{run:!1,reason:"the issue text could not be read"};if(!Mp(`${t.title}
147
- ${t.body}`,e.paths))return{run:!1,reason:`issue names none of the pilot paths (${e.paths.join(", ")||"none set"})`};if(e.agent.trim().toLowerCase()===n.codeAgent.trim().toLowerCase())return{run:!1,reason:`the test agent "${e.agent}" is the coding agent; set quality.specTests.agent to another name`};let s=Cs(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:Pp(t)}}function Lp(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function Np(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function Bp(n){let e=n.split("\0").filter(Boolean),t=[];for(let s=0;s<e.length;s++){let r=e[s],o=r.slice(0,2);t.push({status:o,path:r.slice(3)}),(o.startsWith("R")||o.startsWith("C"))&&s++}return t}function Fp(n){let e=[],t=[];for(let s of n)s.status==="??"&&Lp(s.path)?e.push(s.path):t.push(s.status==="??"?`${s.path} (new, not a test file)`:`${s.path} (${s.status.trim()||"changed"}, existing file)`);return{keep:e,discard:t}}var Up=[["private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/],["GitHub token",/\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})/],["GitLab token",/\bglpat-[A-Za-z0-9_-]{20,}/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}/],["API key (sk-)",/\bsk-(?!ant-)(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/],["Stripe key",/\b[sr]k_live_[A-Za-z0-9]{20,}/],["DigitalOcean token",/\bdo[pro]_v1_[a-f0-9]{64}\b/],["Hugging Face token",/\bhf_[A-Za-z0-9]{30,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["JSON Web Token",/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/],["AWS access key",/\b(AKIA|ASIA)[0-9A-Z]{16}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{35}\b/],["Slack token",/\bxox[abposr]-[A-Za-z0-9-]{10,}/],["Telegram bot token",/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/],["password in a URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s@/]{8,}@/i]];function Hp(n){return Up.filter(([,e])=>e.test(n)).map(([e])=>e)}var jp=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],Wp=n=>`/${$s(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function qp(n,e){let t=$s(n),s=a=>t===a||t.startsWith(a.endsWith(Sd)?a:a+Sd),r=kp(),o=[...e,r,...jp.map(a=>As(r,a)),"/proc"].map(a=>$s(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let d=`/${Wp(a)}/**`;i.push(`Read(${d})`,`Edit(${d})`)}return i}async function Rd(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Ad(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},d,c=(l,p,f=12e4)=>s("git",l,{cwd:p,timeoutMs:f});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let p=r(),f={...a,...l,finishedAt:p,minutes:Math.round((p-o)/6e4*10)/10};n.store.record(f);let h=f.costUsd===void 0?"cost not reported":`$${f.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${f.status} in ${f.minutes} min, ${h}${f.note?` \u2014 ${f.note}`:""}`),f.status!=="pushed"&&f.note)try{await n.noteOnIssue(wd(`Spec tests for #${t.number} (${e.agent}): ${f.note}`,e.agent))}catch(y){n.log(`[spec-tests] ${t.repo}#${t.number}: could not leave the note on the issue: ${y?.message||y}`)}return f};try{let l=await c(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let p=await c(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),f=p.code===0&&p.stdout.trim()?p.stdout.trim():"origin/main";d=(n.makeTempDir??(()=>xp(As(vp(),`agentx-spec-${t.number}-`))))();let h=await c(["worktree","add","--detach",d,f],n.checkout);if(h.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${f}: ${h.stderr.trim().slice(0,300)}`});let y=await n.runAgent({prompt:Ep(t),dir:d,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:qp(d,n.protectedPaths??[n.checkout,process.cwd()])});if(y.budgetStopped)return await u({status:"budget-stopped",costUsd:y.costUsd,note:`stopped at the budget of $${e.maxCostPerIssue.toFixed(2)} (quality.specTests.maxCostPerIssue). No tests were pushed; review the issue's acceptance criteria by hand.`});if(y.timedOut)return await u({status:"timed-out",costUsd:y.costUsd,note:`stopped after ${e.maxMinutes} minutes (quality.specTests.maxMinutes). No tests were pushed.`});if(!y.ok)return await u({status:"failed",costUsd:y.costUsd,note:`the test agent failed: ${(y.error||"no reason given").slice(0,300)}`});let A=await c(["status","--porcelain","-z","--untracked-files=all"],d);if(A.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not list the files the test agent wrote: ${A.stderr.trim().slice(0,300)}`});let{keep:x,discard:E}=Fp(Bp(A.stdout));if(E.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${E.join(", ")}`),!x.length)return await u({status:"no-tests",costUsd:y.costUsd,note:`the test agent wrote no new test file${E.length?` (its other changes were discarded: ${E.join(", ")})`:""}.`});let H=0,b=[];for(let $ of x){let v=kd(As(d,$),"utf8");H+=Np(v);for(let S of Hp(v))b.push(`${S} in ${$}`)}if(b.length)return await u({status:"blocked",costUsd:y.costUsd,testFiles:x,note:`a written file looks like it holds a secret (${b.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let _=$p(e.agent),R=["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`],M=await c(["add","--",...x],d);if(M.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not stage the tests: ${M.stderr.trim().slice(0,300)}`});let L=`Written by ${e.agent} from the text of #${t.number} and its acceptance criteria only, without the implementation (#992).`,N=await c([...R,"commit","--no-verify","-m",$d(t.number),"-m",L],d);if(N.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,note:`could not commit the tests: ${N.stderr.trim().slice(0,300)}`});let j=(await c(["rev-parse","HEAD"],d)).stdout.trim(),q=await c(["push","origin",`HEAD:refs/heads/${i}`],d);if(q.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,commit:j,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let J=await u({status:"pushed",costUsd:y.costUsd,branch:i,commit:j,testFiles:x,testsWritten:H});if(n.tellAuthor)try{await n.tellAuthor(`The spec tests for #${t.number} are on \`${i}\` (${x.join(", ")}). Merge them with \`git fetch origin ${i} && git merge --no-ff origin/${i}\`, run them, and record the outcome in the pull request's "Spec tests" section as described in your task.`)}catch($){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${$?.message||$}`)}return J}catch(l){return await u({status:"failed",note:`unexpected error: ${(l?.message||String(l)).slice(0,300)}`})}finally{if(d){try{await c(["worktree","remove","--force",d],n.checkout)}catch{}try{wp(d)&&Ip(d,{recursive:!0,force:!0})}catch{}}}}var Gp=5e3,ht=new Set,Id=!1;function Kp(){for(let n of ht)try{process.kill(-n,"SIGKILL")}catch{}ht.clear()}function _d(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,d=[],c=(f,h)=>{if(!a){a=!0;for(let y of d)clearTimeout(y);s({code:f,stdout:r,stderr:h??o,timedOut:i})}},u;try{u=yp(n,e,{cwd:t.cwd,env:t.env,detached:t.killGroup,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(f){c(-1,f?.message||String(f));return}t.killGroup&&u.pid&&(ht.add(u.pid),Id||(Id=!0,process.once("exit",Kp)));let l=t.killGraceMs??Gp,p=f=>{if(t.killGroup&&u.pid)try{process.kill(-u.pid,f);return}catch{}u.kill(f)};t.timeoutMs&&d.push(setTimeout(()=>{i=!0,p("SIGTERM"),d.push(setTimeout(()=>{p("SIGKILL"),d.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),c(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",f=>{r+=f}),u.stderr?.on("data",f=>{o+=f}),u.stdin?.on("error",()=>{}),u.on("error",f=>{u.pid&&ht.delete(u.pid),c(-1,f.message)}),u.on("exit",()=>{if(t.killGroup&&u.pid){ht.delete(u.pid);try{process.kill(-u.pid,"SIGKILL")}catch{}}}),u.on("close",f=>c(f??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var Xe=async(n,e,t)=>{let s=await _d(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},Jp="Read,Glob,Grep,Write,Edit";function zp(n){return["-p","-","--output-format","json","--tools",Jp,"--permission-mode","acceptEdits","--max-budget-usd",String(n.maxBudgetUsd),...n.model?["--model",n.model]:[],"--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",JSON.stringify({disableAllHooks:!0,permissions:{deny:n.deny??[]}}),"--no-session-persistence"]}function Td(n,e){let t;try{t=JSON.parse(n)}catch{t=void 0}let s=typeof t?.total_cost_usd=="number"&&Number.isFinite(t.total_cost_usd)?t.total_cost_usd:void 0;return t?.subtype==="error_max_budget_usd"?{ok:!1,budgetStopped:!0,costUsd:s}:t?t.is_error||typeof t.subtype=="string"&&t.subtype!=="success"?{ok:!1,costUsd:s,error:String(t.result??t.subtype).slice(0,300)}:{ok:!0,costUsd:s,reply:String(t.result??"")}:{ok:!1,error:`claude exited ${e??"unknown"} with no result`}}var Pd=async n=>{let e=await _d("claude",zp(n),{cwd:n.dir,env:Pr(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:Td(e.stdout,e.code).costUsd};let t=Td(e.stdout,e.code);return!t.ok&&!t.budgetStopped&&e.stderr&&(!t.error||!e.stdout)&&(t.error=e.stderr.trim().slice(0,300)),t};async function Ed(n,e,t,s){let r=await n("gh",["issue","view",String(t),"--repo",e,"--json","title,body"],{cwd:s,timeoutMs:2e4});if(r.code===0)try{let o=JSON.parse(r.stdout);return typeof o?.title!="string"?void 0:{repo:e,number:t,title:o.title,body:typeof o.body=="string"?o.body:""}}catch{return}}async function Od(n,e,t,s,r){let o=await n("gh",["issue","comment",String(t),"--repo",e,"--body",r],{cwd:s,timeoutMs:2e4});if(o.code!==0)throw new Error(o.stderr.trim().slice(0,300)||`gh exited ${o.code}`)}import{existsSync as Rs,mkdirSync as Qp,readdirSync as Xp,statSync as Yp,utimesSync as Zp}from"fs";import{basename as Vp,dirname as em,join as yt,resolve as Ms}from"path";var Ld={enabled:!1,maxAgeDays:14};function Nd(n,e){if(!e)return null;if(n==="github"){let t=mt(e);return t&&t.kind==="issue"?{source:"github",repo:t.repo,id:String(t.number)}:null}if(n==="gitlab"){let t=e.match(/^(.+):issue:(\d+)$/);return t?{source:"gitlab",repo:t[1],id:t[2]}:null}if(n==="linear"||n==="jira"){let t=e.match(/^(?:linear|jira):([A-Za-z][A-Za-z0-9_]*-\d+)$/);return t?{source:n,id:t[1].toUpperCase()}:null}return null}function tm(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function nm(n){let e=(n||"").trim();return e?(e.match(/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?[^/]+\/(.+?)(?:\.git)?\/?$/i)??e.match(/^(?:[^@/\s]+@)?[^/:\s]+:(?!\/)(.+?)(?:\.git)?\/?$/))?.[1]:void 0}function Bd(n,e,t=ks){let s=[...new Set(e.filter(Boolean))];for(let o of s){let i=t(o);if(i){if(!n.repo)return{dir:o};if(nm(i)?.toLowerCase()===n.repo.toLowerCase())return{dir:o}}}let r=s.join(", ")||"nothing";return{reason:n.repo?`no checkout of ${n.repo} (looked in ${r})`:`no git checkout (looked in ${r})`}}function Fd(n,e){return e.root?Ms(e.root):yt(em(Ms(n)),".agentx-worktrees",Vp(Ms(n)))}var _s=n=>n.trim().slice(0,300);async function Ud(n,e,t,s){let r=(p,f)=>s.exec("git",p,{cwd:f,timeoutMs:12e4}),o=tm(n),i=Fd(e,t),a=yt(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(Rs(yt(a,".git"))){let p=await r(["rev-parse","--abbrev-ref","HEAD"],a);return p.code===0&&p.stdout.trim()===o?(Dd(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${p.code===0?` (it is on ${p.stdout.trim()})`:""}; remove it or check out ${o} there`}}let d=await r(["fetch","origin"],e);d.code!==0&&s.log?.(`[worktrees] fetch in ${e} failed, using what is there: ${_s(d.stderr)}`),await r(["worktree","prune"],e);let c=await r(["rev-parse","--verify","--quiet",`refs/heads/${o}`],e),u;if(c.code===0)u=["worktree","add",a,o];else{let p=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),f=`origin/${o}`;if(p.code!==0){let h=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);f=h.code===0&&h.stdout.trim()?h.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,f]}Qp(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${_s(l.stderr)}`}:(Dd(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function Dd(n,e){let t=new Date((e??Date.now)());try{Zp(n,t,t)}catch{}}async function Hd(n,e,t){let s=Fd(n,e);if(!Rs(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of Xp(s)){let a=yt(s,i);if(a===t.keep||!Rs(yt(a,".git")))continue;let d;try{d=Yp(a).mtimeMs}catch{continue}if(r-d<e.maxAgeDays*864e5)continue;let c=await t.exec("git",["status","--porcelain"],{cwd:a,timeoutMs:6e4});if(c.code!==0||c.stdout.trim()){t.log?.(`[worktrees] kept ${a}: ${c.code!==0?"git status failed":"it has uncommitted changes"}`);continue}let u=await t.exec("git",["worktree","remove",a],{cwd:n,timeoutMs:6e4});u.code===0?o.push(a):t.log?.(`[worktrees] could not remove ${a}: ${_s(u.stderr)}`)}return o}function jd(n){return[`You are working in a git worktree of your own for this issue: ${n.dir}, on the branch \`${n.branch}\`.`,`Make your changes there, commit them on \`${n.branch}\`, push that branch, and open the pull request (or merge request) from it.`,`Do not switch branches and do not edit ${n.checkout}: other tasks use it.`].join(" ")}var sm=["owner","critical","normal","background"],Gd={enabled:!0,mode:"enforce",tiers:["claude-code","codex-cli","opencode"],maxSessions:0,ownerExtraSessions:1,delegationHeadroom:2,minAvailableMemoryMB:512,minAvailableMemoryPercent:10,maxSwapUsedMB:0,minDiskFreeMB:2048,maxLoadPerCpu:2,minStartGapSeconds:10,boot:{windowSeconds:300,startsPerInterval:2,intervalSeconds:30},allowOneWhenIdle:!0,maxWaitMinutes:60,sampleSeconds:5,classes:{},closeIdle:{enabled:!0,maxPerRound:3,minQuietSeconds:60,settleSeconds:30},priority:{ownerChannels:["voice","app"],ownerPeople:[],criticalAgents:[],backgroundChannels:["cron","heartbeat","routine"]}},Kd=n=>(n||"").toLowerCase().split("@")[0];function rm(n,e){if(n.priority)return n.priority;let t=Kd(n.channel);return n.owner||e.priority.ownerChannels.includes(t)||n.person&&e.priority.ownerPeople.includes(n.person)?"owner":e.priority.criticalAgents.includes(n.agentId)?"critical":e.priority.backgroundChannels.includes(t)?"background":"normal"}function om(n,e){if(n.class)return n.class;let t=Kd(n.channel);for(let[s,r]of Object.entries(e.classes))if(r.agents?.includes(n.agentId)||r.channels?.includes(t))return s;return null}function Wd(n,e){return n.maxSessions>0?n.maxSessions:Math.max(2,Math.round((e-2048)/1024))}function Jd(n,e){let t=e.swapGrows?e.memTotalMB*3/4:e.swapTotalMB/2;return{minAvailableMemoryMB:Math.max(n.minAvailableMemoryMB,Math.round(e.memTotalMB*n.minAvailableMemoryPercent/100)),maxSwapUsedMB:n.maxSwapUsedMB>0?n.maxSwapUsedMB:Math.round(t),minDiskFreeMB:n.minDiskFreeMB,maxLoad1:n.maxLoadPerCpu>0?Math.round(n.maxLoadPerCpu*e.cpuCount*100)/100:0}}function qd(n,e){let t=Jd(e,n),s=[];return n.memAvailableMB<t.minAvailableMemoryMB&&s.push(`memory: ${n.memAvailableMB} MB available, needs ${t.minAvailableMemoryMB} MB`),n.swapTotalMB>0&&n.swapUsedMB>t.maxSwapUsedMB&&s.push(`swap: ${n.swapUsedMB} MB used, limit ${t.maxSwapUsedMB} MB`),t.minDiskFreeMB>0&&n.diskFreeMB!==null&&n.diskFreeMB<t.minDiskFreeMB&&s.push(`disk: ${n.diskFreeMB} MB free, needs ${t.minDiskFreeMB} MB`),t.maxLoad1>0&&n.load1>t.maxLoad1&&s.push(`load: ${n.load1}, limit ${t.maxLoad1}`),s}var bn=class{constructor(e,t,s=()=>{},r=Date.now,o=()=>[]){this.settings=e;this.sampler=t;this.log=s;this.now=r;this.closeIdle=o;this.bootAt=r()}waiting=[];running=new Map;starts=[];seq=0;pumping=!1;again=!1;timer=null;closedAt=null;lastReasons=[];lastCloseRoundAt=null;saidNothingToClose=!1;bootAt;get closed(){return this.closedAt!==null}admit(e){let t=this.settings(),r={id:`adm-${++this.seq}`,agentId:e.agentId,channel:e.channel||"api",chatId:e.chatId,priority:rm(e,t),cls:om(e,t),label:(e.label||"").replace(/\s+/g," ").slice(0,80)};return this.closed?e.keepOnClose?new Promise(()=>{}):Promise.resolve({ok:!1,reason:"closed",waitedMs:0,blockedBy:[]}):e.signal?.aborted?Promise.resolve({ok:!1,reason:"caller-gone",waitedMs:0,blockedBy:[]}):t.enabled?new Promise(o=>{let i={...r,seq:this.seq,delegated:!!e.delegated,enqueuedAt:this.now(),nodeHeldSince:null,blockedBy:[],req:e,resolve:o};e.signal&&(i.onAbort=()=>{this.waiting.includes(i)&&(this.log(`[admission] ${i.agentId} left the queue (caller gone) after ${Math.round((this.now()-i.enqueuedAt)/1e3)}s`),this.refuse(i,"caller-gone"))},e.signal.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i),this.pump()}):(e.onStart?.(),Promise.resolve({ok:!0,ticket:this.start(r,0)}))}close(){this.closedAt=this.now(),this.timer&&clearTimeout(this.timer),this.timer=null;let e=0,t=0;for(let s of[...this.waiting])s.req.keepOnClose?(this.drop(s),e++):(this.refuse(s,"closed"),t++);return{kept:e,refused:t}}get waitingCount(){return this.waiting.length}drop(e){let t=this.waiting.indexOf(e);t!==-1&&this.waiting.splice(t,1),e.req.signal&&e.onAbort&&e.req.signal.removeEventListener("abort",e.onAbort)}refuse(e,t){this.drop(e),e.resolve({ok:!1,reason:t,waitedMs:this.now()-e.enqueuedAt,blockedBy:e.blockedBy})}start(e,t){let s=this.now();this.running.set(e.id,{...e,startedAt:s,waitedMs:t}),this.starts.push(s);let r=!1;return{id:e.id,release:()=>{r||(r=!0,this.running.delete(e.id),this.waiting.length&&this.pump())}}}ordered(){let e=t=>sm.indexOf(t);return[...this.waiting].sort((t,s)=>e(t.priority)-e(s.priority)||t.enqueuedAt-s.enqueuedAt||t.seq-s.seq)}paceWait(e,t,s){if(e==="owner")return 0;let r=this.starts[this.starts.length-1],o=r!==void 0?Math.max(0,r+t.minStartGapSeconds*1e3-s):0;if(s-this.bootAt<t.boot.windowSeconds*1e3&&t.boot.startsPerInterval>0){let i=t.boot.intervalSeconds*1e3,a=this.starts.filter(d=>d>s-i);a.length>=t.boot.startsPerInterval&&(o=Math.max(o,a[0]+i-s))}return o}classCount(e){let t=0;for(let s of this.running.values())s.cls===e&&t++;return t}async pump(){if(this.pumping){this.again=!0;return}this.pumping=!0;try{do{if(this.again=!1,!this.waiting.length||this.closed)break;let s;try{s=await this.sampler.read(this.now())}catch{break}if(this.closed)break;this.pass(this.settings(),s)}while(this.again);let e=Math.max(6e4,this.settings().boot.intervalSeconds*1e3),t=this.now()-e;for(;this.starts.length>1&&this.starts[0]<t;)this.starts.shift()}finally{this.pumping=!1}this.arm()}pass(e,t){let s=this.now(),r=Wd(e,t.memTotalMB),o=qd(t,e);o.join()!==this.lastReasons.join()&&(this.log(o.length?`[admission] gate closed: ${o.join("; ")}`:"[admission] gate open"),this.lastReasons=o);let i=!1,a=!1;for(let d of this.ordered()){let c=s-d.enqueuedAt;if(e.maxWaitMinutes>0&&d.nodeHeldSince!==null&&s-d.nodeHeldSince>=e.maxWaitMinutes*6e4){this.log(`[admission] ${d.agentId} refused after ${Math.round((s-d.nodeHeldSince)/6e4)}m held by the node \u2014 ${d.blockedBy.join("; ")||"no room"}`),this.refuse(d,"timeout");continue}let u=[],l=d.cls?e.classes[d.cls]?.max:void 0;l!==void 0&&this.classCount(d.cls)>=l&&u.push(`class ${d.cls}: ${this.classCount(d.cls)}/${l} running`),d.req.canStart&&!d.req.canStart()&&u.push("agent busy");let p=[];i&&p.push("behind earlier work");let f=d.priority==="owner"?e.ownerExtraSessions:0,h=r+Math.max(f,d.delegated?e.delegationHeadroom:0);this.running.size>=h&&p.push(`session cap: ${this.running.size}/${h} running`);let y=[];o.length&&!(e.allowOneWhenIdle&&this.running.size===0)&&(y.push(...o),u.length||(a=!0));let A=this.paceWait(d.priority,e,s);if(A>0&&y.push(`start pace: next start in ${Math.ceil(A/1e3)}s`),p.push(...y),!e.enabled||e.mode==="observe"){if(e.enabled&&p.some(x=>x!=="behind earlier work")&&this.log(`[admission] observe: would hold ${d.agentId} (${d.priority}) \u2014 ${p.join("; ")}`),u.includes("agent busy")){d.blockedBy=u;continue}this.admitEntry(d,c);continue}if(u.length||p.length){d.blockedBy=[...p,...u],p.length?d.nodeHeldSince??=s:d.nodeHeldSince=null,y.length&&(i=!0);continue}this.admitEntry(d,c)}this.closeIdleRound(e,a?o:[],s)}closeIdleRound(e,t,s){let r=t.filter(c=>c.startsWith("memory:")||c.startsWith("swap:"));if(!r.length){this.saidNothingToClose=!1;return}let o=e.closeIdle;if(!e.enabled||!o.enabled||this.lastCloseRoundAt!==null&&s-this.lastCloseRoundAt<o.settleSeconds*1e3)return;let i=new Set([...this.waiting,...this.running.values()].map(c=>fe({agentId:c.agentId,channel:c.channel,chatId:c.chatId??""}))),a=e.mode==="observe",d=this.closeIdle({max:o.maxPerRound,minQuietMs:o.minQuietSeconds*1e3,reason:`gate shut (${r.join("; ")})`,skip:c=>i.has(fe(c)),dryRun:a});if(!d.length){this.saidNothingToClose||this.log(`[admission] gate shut (${r.join("; ")}): no idle session to close`),this.saidNothingToClose=!0;return}this.saidNothingToClose=!1,this.lastCloseRoundAt=s,a?this.log(`[admission] observe: would close ${d.length} idle session(s) \u2014 ${d.map(fe).join(", ")}`):this.log(`[admission] gate shut (${r.join("; ")}): closed ${d.length} idle session(s), ${this.waiting.length} waiting`)}admitEntry(e,t){this.drop(e);try{e.req.onStart?.()}catch{}let s=this.start(e,t);t>=1e3&&this.log(`[admission] started ${e.agentId} (${e.priority}) after ${Math.round(t/1e3)}s in the queue`),e.resolve({ok:!0,ticket:s})}arm(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),!this.waiting.length||this.closed)return;let e=this.settings(),t=this.now(),s=Math.max(1,e.sampleSeconds)*1e3;for(let r of this.waiting){let o=this.paceWait(r.priority,e,t);o>0&&(s=Math.min(s,o+50))}this.timer=setTimeout(()=>{this.timer=null,this.pump()},s),this.timer.unref?.()}snapshot(){let e=this.settings(),t=this.now(),s=this.sampler.latest(),r=s?Wd(e,s.memTotalMB):e.maxSessions||null,o=this.ordered().map((c,u)=>({position:u+1,id:c.id,agentId:c.agentId,channel:c.channel,chatId:c.chatId??null,priority:c.priority,class:c.cls,label:c.label,waitingSeconds:Math.round((t-c.enqueuedAt)/1e3),blockedBy:c.blockedBy})),i={};for(let[c,u]of Object.entries(e.classes))i[c]={max:u.max,running:this.classCount(c)};let a=this.bootAt+e.boot.windowSeconds*1e3,d=s?qd(s,e):[];return{enabled:e.enabled,mode:e.mode,checkedAt:s?new Date(s.at).toISOString():null,resources:s,limits:s?Jd(e,s):null,gate:{open:d.length===0,reasons:d},caps:{maxSessions:r,ownerExtraSessions:e.ownerExtraSessions,delegationHeadroom:e.delegationHeadroom,classes:i},warmUp:{active:t<a,until:new Date(a).toISOString(),startsPerInterval:e.boot.startsPerInterval,intervalSeconds:e.boot.intervalSeconds},running:[...this.running.values()].map(c=>({id:c.id,agentId:c.agentId,channel:c.channel,chatId:c.chatId??null,priority:c.priority,class:c.cls,label:c.label,startedAt:new Date(c.startedAt).toISOString(),waitedSeconds:Math.round(c.waitedMs/1e3)})),waiting:o,next:o[0]??null}}async refresh(){await this.sampler.read(this.now())}};import{execFile as im}from"child_process";import{readFile as am,statfs as dm}from"fs/promises";import{cpus as cm,freemem as um,loadavg as lm,platform as gm,totalmem as pm}from"os";var wt=1024*1024;function mm(n){let e=Number(n.match(/page size of (\d+) bytes/)?.[1]);if(!e)return null;let t=r=>{let o=n.match(new RegExp(`^${r}:\\s+(\\d+)`,"m"));return o?Number(o[1]):0},s=t("Pages free")+t("Pages inactive")+t("Pages speculative")+t("Pages purgeable");return Math.round(s*e/wt)}function fm(n){let e=r=>{let o=n.match(new RegExp(`${r}\\s*=\\s*([\\d.]+)([KMGT]?)`));if(!o)return null;let i={"":1/wt,K:1/1024,M:1,G:1024,T:1024*1024};return Number(o[1])*(i[o[2]]??1)},t=e("total"),s=e("used");return t===null||s===null?null:{totalMB:Math.round(t),usedMB:Math.round(s)}}function hm(n){let e=o=>{let i=n.match(new RegExp(`^${o}:\\s+(\\d+)`,"m"));return i?Number(i[1]):null},t=e("MemAvailable");if(t===null)return null;let s=e("SwapTotal")??0,r=e("SwapFree")??s;return{availableMB:Math.round(t/1024),swapTotalMB:Math.round(s/1024),swapUsedMB:Math.round(Math.max(0,s-r)/1024)}}function zd(n,e){return new Promise(t=>{im(n,e,{timeout:3e3},(s,r)=>t(s?"":String(r)))})}async function ym(n){let e=Math.round(pm()/wt),t=Math.round(um()/wt),s=0,r=0,o=gm(),i=o==="darwin";if(o==="darwin"){let[d,c]=await Promise.all([zd("vm_stat",[]),zd("sysctl",["-n","vm.swapusage"])]);t=mm(d)??t;let u=fm(c);u&&(s=u.totalMB,r=u.usedMB)}else if(o==="linux"){let d=hm(await am("/proc/meminfo","utf-8").catch(()=>""));d&&(t=d.availableMB,s=d.swapTotalMB,r=d.swapUsedMB)}let a=null;try{let d=await dm(n);a=Math.round(Number(d.bavail)*Number(d.bsize)/wt)}catch{}return{at:Date.now(),memTotalMB:e,memAvailableMB:t,swapTotalMB:s,swapUsedMB:r,swapGrows:i,diskFreeMB:a,load1:Math.round(lm()[0]*100)/100,cpuCount:Math.max(1,cm().length)}}var xn=class{constructor(e,t=3e3,s=ym){this.diskPath=e;this.ttlMs=t;this.sample=s}last=null;pending=null;latest(){return this.last}async read(e=Date.now()){return this.last&&e-this.last.at<this.ttlMs?this.last:(this.pending||(this.pending=this.sample(this.diskPath).then(t=>(this.last=t,t)).finally(()=>{this.pending=null})),this.pending)}};var bm=250,xm=5e3,vm={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},Am=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),Qd=`[Operating principle]
148
- Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`,$m="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function Cm(n){return n==="claude-code"?`${Qd}
149
- ${$m}`:n==="codex-cli"?Qd:""}function Xd(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var nc;function Kb(n){nc=n}function Jb(){return nc}function Mm(n){let e=n.split(`
150
- `);for(let t=e.length-1;t>=0;t--){let s=Gr(e[t].trim());if(s)return s.length>160?s.slice(0,159)+"\u2026":s}}var Yd=64*1024,Rm=5*60*1e3,_m=3e4,Pm=300,Em=25*6e4,Ye=".agentx/task-history",Om=30;function xt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function Dm(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Lm(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=lo(n,e,V().recent());return po(t,s)}function Nm(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function Bm(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let l=u.meta.type||"untyped",p=r.get(l)||[];p.push(u.meta.title),r.set(l,p)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
151
- `),d=process.argv[1]||"dist/cli.js",c=n.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${s.length} article${s.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
152
- node ${d} wiki query "the question" --dir ${c} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${d} wiki facts list --dir ${c}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,...t.notesInbox&&t.notesInbox.inbox!==e?["",`When you learn something the wiki should know (a change, a correction, a fact that went stale), leave a short note for the wiki run: \`node ${d} wiki notes add --from ${e} --change "what changed" --source "where you saw it" --date YYYY-MM-DD --daemon ${t.notesInbox.daemonUrl}\`. The run checks it before it changes anything. Notes stay inside the fleet; never put secrets in one.`]:[],"[End Institutional Wiki]"].join(`
153
- `)}var Ps=8*1024;function Fm(n,e){if(n)try{Oo(n)}catch{}return e}function Zd(n){if(n.length<=Ps)return n;let e=n.length-Ps;return n.slice(0,Ps)+`\u2026[+${e}]`}function Vd(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function Um(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function ec(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=V();if(s==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Zd(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Zd(a):null,at:r})}return}}function Hm(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
134
+ `)}function Md(n,e){let t=$d(n);return["","## Spec tests (#992)",`A separate test agent ("${e}") is writing tests for this issue from the issue text only, without seeing your code. It pushes them as one commit, "${Cd(n)}", to the branch \`${t}\`.`,"- Do not write those tests yourself. Do not edit or delete them, except as described below.",`- Before you open the pull request, and again before you finish, run \`git fetch origin ${t}\`. When the branch exists, merge it into your branch with \`git merge --no-ff origin/${t}\` (a merge, not a cherry-pick, squash or rebase, so the commit keeps its author), then run its tests.`,'- When a spec test fails, decide which it is. A code defect: fix the code. A test that misreads the acceptance criteria: change that test in a separate commit whose message starts with "test: spec misread" and quotes the criterion it misreads. Never skip or disable a spec test.','- In the pull request description, add a "Spec tests" section that lists each failure on the first run and your call (code defect or test misread), and ends with this line, filled in:'," <!-- agentx:spec-tests written=W failed-first-run=F code-defects=D test-misreads=M -->","- If the branch has not appeared by the time you finish, say so in that section."].join(`
135
+ `)}var Op=90*24*60*60*1e3,wn=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(vd(this.file,"utf8")),t=Array.isArray(e?.runs)?e.runs:[];this.runs=t.filter(s=>s&&typeof s.repo=="string"&&Number.isInteger(s.number)&&Number.isFinite(s.startedAt))}catch{this.runs=[]}}}save(){let e=Date.now();this.runs=this.runs.filter(t=>e-t.startedAt<Op);try{bp(Ap(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Tp(t,JSON.stringify({runs:this.runs},null,2)),Sp(t,this.file)}catch{}}get(e,t){this.load();let s=e.toLowerCase();return this.runs.find(r=>r.repo.toLowerCase()===s&&r.number===t)}record(e){this.load(),this.runs=this.runs.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.runs.push(e),this.save()}all(){return this.load(),[...this.runs]}},Dp=10*6e4;function Ms(n,e,t=Date.now()){if(n){if(n.status!=="running")return`spec tests already ran for this issue (${n.status})`;if(!(t-n.startedAt>e.maxMinutes*6e4+Dp))return"spec tests are already running for this issue"}}function Rd(n){let{settings:e,issue:t}=n;if(!e.enabled)return{run:!1,reason:"spec tests are off"};if(!t)return{run:!1,reason:"the issue text could not be read"};if(!Mp(`${t.title}
136
+ ${t.body}`,e.paths))return{run:!1,reason:`issue names none of the pilot paths (${e.paths.join(", ")||"none set"})`};if(e.agent.trim().toLowerCase()===n.codeAgent.trim().toLowerCase())return{run:!1,reason:`the test agent "${e.agent}" is the coding agent; set quality.specTests.agent to another name`};let s=Ms(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:Pp(t)}}function Lp(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function Np(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function Bp(n){let e=n.split("\0").filter(Boolean),t=[];for(let s=0;s<e.length;s++){let r=e[s],o=r.slice(0,2);t.push({status:o,path:r.slice(3)}),(o.startsWith("R")||o.startsWith("C"))&&s++}return t}function Fp(n){let e=[],t=[];for(let s of n)s.status==="??"&&Lp(s.path)?e.push(s.path):t.push(s.status==="??"?`${s.path} (new, not a test file)`:`${s.path} (${s.status.trim()||"changed"}, existing file)`);return{keep:e,discard:t}}var Up=[["private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/],["GitHub token",/\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})/],["GitLab token",/\bglpat-[A-Za-z0-9_-]{20,}/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}/],["API key (sk-)",/\bsk-(?!ant-)(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/],["Stripe key",/\b[sr]k_live_[A-Za-z0-9]{20,}/],["DigitalOcean token",/\bdo[pro]_v1_[a-f0-9]{64}\b/],["Hugging Face token",/\bhf_[A-Za-z0-9]{30,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["JSON Web Token",/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/],["AWS access key",/\b(AKIA|ASIA)[0-9A-Z]{16}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{35}\b/],["Slack token",/\bxox[abposr]-[A-Za-z0-9-]{10,}/],["Telegram bot token",/\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/],["password in a URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s@/]{8,}@/i]];function Hp(n){return Up.filter(([,e])=>e.test(n)).map(([e])=>e)}var jp=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],Wp=n=>`/${Cs(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function qp(n,e){let t=Cs(n),s=a=>t===a||t.startsWith(a.endsWith(Id)?a:a+Id),r=kp(),o=[...e,r,...jp.map(a=>$s(r,a)),"/proc"].map(a=>Cs(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let c=`/${Wp(a)}/**`;i.push(`Read(${c})`,`Edit(${c})`)}return i}async function _d(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=$d(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},c,d=(l,p,f=12e4)=>s("git",l,{cwd:p,timeoutMs:f});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let p=r(),f={...a,...l,finishedAt:p,minutes:Math.round((p-o)/6e4*10)/10};n.store.record(f);let h=f.costUsd===void 0?"cost not reported":`$${f.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${f.status} in ${f.minutes} min, ${h}${f.note?` \u2014 ${f.note}`:""}`),f.status!=="pushed"&&f.note)try{await n.noteOnIssue(bd(`Spec tests for #${t.number} (${e.agent}): ${f.note}`,e.agent))}catch(y){n.log(`[spec-tests] ${t.repo}#${t.number}: could not leave the note on the issue: ${y?.message||y}`)}return f};try{let l=await d(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let p=await d(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),f=p.code===0&&p.stdout.trim()?p.stdout.trim():"origin/main";c=(n.makeTempDir??(()=>xp($s(vp(),`agentx-spec-${t.number}-`))))();let h=await d(["worktree","add","--detach",c,f],n.checkout);if(h.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${f}: ${h.stderr.trim().slice(0,300)}`});let y=await n.runAgent({prompt:Ep(t),dir:c,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:qp(c,n.protectedPaths??[n.checkout,process.cwd()])});if(y.budgetStopped)return await u({status:"budget-stopped",costUsd:y.costUsd,note:`stopped at the budget of $${e.maxCostPerIssue.toFixed(2)} (quality.specTests.maxCostPerIssue). No tests were pushed; review the issue's acceptance criteria by hand.`});if(y.timedOut)return await u({status:"timed-out",costUsd:y.costUsd,note:`stopped after ${e.maxMinutes} minutes (quality.specTests.maxMinutes). No tests were pushed.`});if(!y.ok)return await u({status:"failed",costUsd:y.costUsd,note:`the test agent failed: ${(y.error||"no reason given").slice(0,300)}`});let A=await d(["status","--porcelain","-z","--untracked-files=all"],c);if(A.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not list the files the test agent wrote: ${A.stderr.trim().slice(0,300)}`});let{keep:x,discard:E}=Fp(Bp(A.stdout));if(E.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${E.join(", ")}`),!x.length)return await u({status:"no-tests",costUsd:y.costUsd,note:`the test agent wrote no new test file${E.length?` (its other changes were discarded: ${E.join(", ")})`:""}.`});let H=0,b=[];for(let $ of x){let v=vd($s(c,$),"utf8");H+=Np(v);for(let S of Hp(v))b.push(`${S} in ${$}`)}if(b.length)return await u({status:"blocked",costUsd:y.costUsd,testFiles:x,note:`a written file looks like it holds a secret (${b.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let _=$p(e.agent),R=["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`],M=await d(["add","--",...x],c);if(M.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not stage the tests: ${M.stderr.trim().slice(0,300)}`});let L=`Written by ${e.agent} from the text of #${t.number} and its acceptance criteria only, without the implementation (#992).`,N=await d([...R,"commit","--no-verify","-m",Cd(t.number),"-m",L],c);if(N.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,note:`could not commit the tests: ${N.stderr.trim().slice(0,300)}`});let j=(await d(["rev-parse","HEAD"],c)).stdout.trim(),q=await d(["push","origin",`HEAD:refs/heads/${i}`],c);if(q.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,commit:j,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let J=await u({status:"pushed",costUsd:y.costUsd,branch:i,commit:j,testFiles:x,testsWritten:H});if(n.tellAuthor)try{await n.tellAuthor(`The spec tests for #${t.number} are on \`${i}\` (${x.join(", ")}). Merge them with \`git fetch origin ${i} && git merge --no-ff origin/${i}\`, run them, and record the outcome in the pull request's "Spec tests" section as described in your task.`)}catch($){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${$?.message||$}`)}return J}catch(l){return await u({status:"failed",note:`unexpected error: ${(l?.message||String(l)).slice(0,300)}`})}finally{if(c){try{await d(["worktree","remove","--force",c],n.checkout)}catch{}try{wp(c)&&Ip(c,{recursive:!0,force:!0})}catch{}}}}var Gp=5e3,ht=new Set,Td=!1;function Kp(){for(let n of ht)try{process.kill(-n,"SIGKILL")}catch{}ht.clear()}function Pd(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,c=[],d=(f,h)=>{if(!a){a=!0;for(let y of c)clearTimeout(y);s({code:f,stdout:r,stderr:h??o,timedOut:i})}},u;try{u=yp(n,e,{cwd:t.cwd,env:t.env,detached:t.killGroup,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(f){d(-1,f?.message||String(f));return}t.killGroup&&u.pid&&(ht.add(u.pid),Td||(Td=!0,process.once("exit",Kp)));let l=t.killGraceMs??Gp,p=f=>{if(t.killGroup&&u.pid)try{process.kill(-u.pid,f);return}catch{}u.kill(f)};t.timeoutMs&&c.push(setTimeout(()=>{i=!0,p("SIGTERM"),c.push(setTimeout(()=>{p("SIGKILL"),c.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),d(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",f=>{r+=f}),u.stderr?.on("data",f=>{o+=f}),u.stdin?.on("error",()=>{}),u.on("error",f=>{u.pid&&ht.delete(u.pid),d(-1,f.message)}),u.on("exit",()=>{if(t.killGroup&&u.pid){ht.delete(u.pid);try{process.kill(-u.pid,"SIGKILL")}catch{}}}),u.on("close",f=>d(f??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var Xe=async(n,e,t)=>{let s=await Pd(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},Jp="Read,Glob,Grep,Write,Edit";function zp(n){return["-p","-","--output-format","json","--tools",Jp,"--permission-mode","acceptEdits","--max-budget-usd",String(n.maxBudgetUsd),...n.model?["--model",n.model]:[],"--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",JSON.stringify({disableAllHooks:!0,permissions:{deny:n.deny??[]}}),"--no-session-persistence"]}function kd(n,e){let t;try{t=JSON.parse(n)}catch{t=void 0}let s=typeof t?.total_cost_usd=="number"&&Number.isFinite(t.total_cost_usd)?t.total_cost_usd:void 0;return t?.subtype==="error_max_budget_usd"?{ok:!1,budgetStopped:!0,costUsd:s}:t?t.is_error||typeof t.subtype=="string"&&t.subtype!=="success"?{ok:!1,costUsd:s,error:String(t.result??t.subtype).slice(0,300)}:{ok:!0,costUsd:s,reply:String(t.result??"")}:{ok:!1,error:`claude exited ${e??"unknown"} with no result`}}var Ed=async n=>{let e=await Pd("claude",zp(n),{cwd:n.dir,env:Pr(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:kd(e.stdout,e.code).costUsd};let t=kd(e.stdout,e.code);return!t.ok&&!t.budgetStopped&&e.stderr&&(!t.error||!e.stdout)&&(t.error=e.stderr.trim().slice(0,300)),t};async function Od(n,e,t,s){let r=await n("gh",["issue","view",String(t),"--repo",e,"--json","title,body"],{cwd:s,timeoutMs:2e4});if(r.code===0)try{let o=JSON.parse(r.stdout);return typeof o?.title!="string"?void 0:{repo:e,number:t,title:o.title,body:typeof o.body=="string"?o.body:""}}catch{return}}async function Dd(n,e,t,s,r){let o=await n("gh",["issue","comment",String(t),"--repo",e,"--body",r],{cwd:s,timeoutMs:2e4});if(o.code!==0)throw new Error(o.stderr.trim().slice(0,300)||`gh exited ${o.code}`)}import{existsSync as _s,mkdirSync as Qp,readdirSync as Xp,statSync as Yp,utimesSync as Zp}from"fs";import{basename as Vp,dirname as em,join as yt,resolve as Rs}from"path";var Nd={enabled:!1,maxAgeDays:14};function Bd(n,e){if(!e)return null;if(n==="github"){let t=mt(e);return t&&t.kind==="issue"?{source:"github",repo:t.repo,id:String(t.number)}:null}if(n==="gitlab"){let t=e.match(/^(.+):issue:(\d+)$/);return t?{source:"gitlab",repo:t[1],id:t[2]}:null}if(n==="linear"||n==="jira"){let t=e.match(/^(?:linear|jira):([A-Za-z][A-Za-z0-9_]*-\d+)$/);return t?{source:n,id:t[1].toUpperCase()}:null}return null}function tm(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function nm(n){let e=(n||"").trim();return e?(e.match(/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?[^/]+\/(.+?)(?:\.git)?\/?$/i)??e.match(/^(?:[^@/\s]+@)?[^/:\s]+:(?!\/)(.+?)(?:\.git)?\/?$/))?.[1]:void 0}function Fd(n,e,t=vs){let s=[...new Set(e.filter(Boolean))];for(let o of s){let i=t(o);if(i){if(!n.repo)return{dir:o};if(nm(i)?.toLowerCase()===n.repo.toLowerCase())return{dir:o}}}let r=s.join(", ")||"nothing";return{reason:n.repo?`no checkout of ${n.repo} (looked in ${r})`:`no git checkout (looked in ${r})`}}function Ud(n,e){return e.root?Rs(e.root):yt(em(Rs(n)),".agentx-worktrees",Vp(Rs(n)))}var Ps=n=>n.trim().slice(0,300);async function Hd(n,e,t,s){let r=(p,f)=>s.exec("git",p,{cwd:f,timeoutMs:12e4}),o=tm(n),i=Ud(e,t),a=yt(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(_s(yt(a,".git"))){let p=await r(["rev-parse","--abbrev-ref","HEAD"],a);return p.code===0&&p.stdout.trim()===o?(Ld(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${p.code===0?` (it is on ${p.stdout.trim()})`:""}; remove it or check out ${o} there`}}let c=await r(["fetch","origin"],e);c.code!==0&&s.log?.(`[worktrees] fetch in ${e} failed, using what is there: ${Ps(c.stderr)}`),await r(["worktree","prune"],e);let d=await r(["rev-parse","--verify","--quiet",`refs/heads/${o}`],e),u;if(d.code===0)u=["worktree","add",a,o];else{let p=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),f=`origin/${o}`;if(p.code!==0){let h=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);f=h.code===0&&h.stdout.trim()?h.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,f]}Qp(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${Ps(l.stderr)}`}:(Ld(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function Ld(n,e){let t=new Date((e??Date.now)());try{Zp(n,t,t)}catch{}}async function jd(n,e,t){let s=Ud(n,e);if(!_s(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of Xp(s)){let a=yt(s,i);if(a===t.keep||!_s(yt(a,".git")))continue;let c;try{c=Yp(a).mtimeMs}catch{continue}if(r-c<e.maxAgeDays*864e5)continue;let d=await t.exec("git",["status","--porcelain"],{cwd:a,timeoutMs:6e4});if(d.code!==0||d.stdout.trim()){t.log?.(`[worktrees] kept ${a}: ${d.code!==0?"git status failed":"it has uncommitted changes"}`);continue}let u=await t.exec("git",["worktree","remove",a],{cwd:n,timeoutMs:6e4});u.code===0?o.push(a):t.log?.(`[worktrees] could not remove ${a}: ${Ps(u.stderr)}`)}return o}function Wd(n){return[`You are working in a git worktree of your own for this issue: ${n.dir}, on the branch \`${n.branch}\`.`,`Make your changes there, commit them on \`${n.branch}\`, push that branch, and open the pull request (or merge request) from it.`,`Do not switch branches and do not edit ${n.checkout}: other tasks use it.`].join(" ")}var sm=["owner","critical","normal","background"],Kd={enabled:!0,mode:"enforce",tiers:["claude-code","codex-cli","opencode"],maxSessions:0,ownerExtraSessions:1,delegationHeadroom:2,minAvailableMemoryMB:512,minAvailableMemoryPercent:10,maxSwapUsedMB:0,minDiskFreeMB:2048,maxLoadPerCpu:2,minStartGapSeconds:10,boot:{windowSeconds:300,startsPerInterval:2,intervalSeconds:30},allowOneWhenIdle:!0,maxWaitMinutes:60,sampleSeconds:5,classes:{},closeIdle:{enabled:!0,maxPerRound:3,minQuietSeconds:60,settleSeconds:30},priority:{ownerChannels:["voice","app"],ownerPeople:[],criticalAgents:[],backgroundChannels:["cron","heartbeat","routine"]}},Jd=n=>(n||"").toLowerCase().split("@")[0];function rm(n,e){if(n.priority)return n.priority;let t=Jd(n.channel);return n.owner||e.priority.ownerChannels.includes(t)||n.person&&e.priority.ownerPeople.includes(n.person)?"owner":e.priority.criticalAgents.includes(n.agentId)?"critical":e.priority.backgroundChannels.includes(t)?"background":"normal"}function om(n,e){if(n.class)return n.class;let t=Jd(n.channel);for(let[s,r]of Object.entries(e.classes))if(r.agents?.includes(n.agentId)||r.channels?.includes(t))return s;return null}function qd(n,e){return n.maxSessions>0?n.maxSessions:Math.max(2,Math.round((e-2048)/1024))}function zd(n,e){let t=e.swapGrows?e.memTotalMB*3/4:e.swapTotalMB/2;return{minAvailableMemoryMB:Math.max(n.minAvailableMemoryMB,Math.round(e.memTotalMB*n.minAvailableMemoryPercent/100)),maxSwapUsedMB:n.maxSwapUsedMB>0?n.maxSwapUsedMB:Math.round(t),minDiskFreeMB:n.minDiskFreeMB,maxLoad1:n.maxLoadPerCpu>0?Math.round(n.maxLoadPerCpu*e.cpuCount*100)/100:0}}function Gd(n,e){let t=zd(e,n),s=[];return n.memAvailableMB<t.minAvailableMemoryMB&&s.push(`memory: ${n.memAvailableMB} MB available, needs ${t.minAvailableMemoryMB} MB`),n.swapTotalMB>0&&n.swapUsedMB>t.maxSwapUsedMB&&s.push(`swap: ${n.swapUsedMB} MB used, limit ${t.maxSwapUsedMB} MB`),t.minDiskFreeMB>0&&n.diskFreeMB!==null&&n.diskFreeMB<t.minDiskFreeMB&&s.push(`disk: ${n.diskFreeMB} MB free, needs ${t.minDiskFreeMB} MB`),t.maxLoad1>0&&n.load1>t.maxLoad1&&s.push(`load: ${n.load1}, limit ${t.maxLoad1}`),s}var bn=class{constructor(e,t,s=()=>{},r=Date.now,o=()=>[]){this.settings=e;this.sampler=t;this.log=s;this.now=r;this.closeIdle=o;this.bootAt=r()}waiting=[];running=new Map;starts=[];seq=0;pumping=!1;again=!1;timer=null;closedAt=null;lastReasons=[];lastCloseRoundAt=null;saidNothingToClose=!1;bootAt;get closed(){return this.closedAt!==null}admit(e){let t=this.settings(),r={id:`adm-${++this.seq}`,agentId:e.agentId,channel:e.channel||"api",chatId:e.chatId,priority:rm(e,t),cls:om(e,t),label:(e.label||"").replace(/\s+/g," ").slice(0,80)};return this.closed?e.keepOnClose?new Promise(()=>{}):Promise.resolve({ok:!1,reason:"closed",waitedMs:0,blockedBy:[]}):e.signal?.aborted?Promise.resolve({ok:!1,reason:"caller-gone",waitedMs:0,blockedBy:[]}):t.enabled?new Promise(o=>{let i={...r,seq:this.seq,delegated:!!e.delegated,enqueuedAt:this.now(),nodeHeldSince:null,blockedBy:[],req:e,resolve:o};e.signal&&(i.onAbort=()=>{this.waiting.includes(i)&&(this.log(`[admission] ${i.agentId} left the queue (caller gone) after ${Math.round((this.now()-i.enqueuedAt)/1e3)}s`),this.refuse(i,"caller-gone"))},e.signal.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i),this.pump()}):(e.onStart?.(),Promise.resolve({ok:!0,ticket:this.start(r,0)}))}close(){this.closedAt=this.now(),this.timer&&clearTimeout(this.timer),this.timer=null;let e=0,t=0;for(let s of[...this.waiting])s.req.keepOnClose?(this.drop(s),e++):(this.refuse(s,"closed"),t++);return{kept:e,refused:t}}get waitingCount(){return this.waiting.length}drop(e){let t=this.waiting.indexOf(e);t!==-1&&this.waiting.splice(t,1),e.req.signal&&e.onAbort&&e.req.signal.removeEventListener("abort",e.onAbort)}refuse(e,t){this.drop(e),e.resolve({ok:!1,reason:t,waitedMs:this.now()-e.enqueuedAt,blockedBy:e.blockedBy})}start(e,t){let s=this.now();this.running.set(e.id,{...e,startedAt:s,waitedMs:t}),this.starts.push(s);let r=!1;return{id:e.id,release:()=>{r||(r=!0,this.running.delete(e.id),this.waiting.length&&this.pump())}}}ordered(){let e=t=>sm.indexOf(t);return[...this.waiting].sort((t,s)=>e(t.priority)-e(s.priority)||t.enqueuedAt-s.enqueuedAt||t.seq-s.seq)}paceWait(e,t,s){if(e==="owner")return 0;let r=this.starts[this.starts.length-1],o=r!==void 0?Math.max(0,r+t.minStartGapSeconds*1e3-s):0;if(s-this.bootAt<t.boot.windowSeconds*1e3&&t.boot.startsPerInterval>0){let i=t.boot.intervalSeconds*1e3,a=this.starts.filter(c=>c>s-i);a.length>=t.boot.startsPerInterval&&(o=Math.max(o,a[0]+i-s))}return o}classCount(e){let t=0;for(let s of this.running.values())s.cls===e&&t++;return t}async pump(){if(this.pumping){this.again=!0;return}this.pumping=!0;try{do{if(this.again=!1,!this.waiting.length||this.closed)break;let s;try{s=await this.sampler.read(this.now())}catch{break}if(this.closed)break;this.pass(this.settings(),s)}while(this.again);let e=Math.max(6e4,this.settings().boot.intervalSeconds*1e3),t=this.now()-e;for(;this.starts.length>1&&this.starts[0]<t;)this.starts.shift()}finally{this.pumping=!1}this.arm()}pass(e,t){let s=this.now(),r=qd(e,t.memTotalMB),o=Gd(t,e);o.join()!==this.lastReasons.join()&&(this.log(o.length?`[admission] gate closed: ${o.join("; ")}`:"[admission] gate open"),this.lastReasons=o);let i=!1,a=!1;for(let c of this.ordered()){let d=s-c.enqueuedAt;if(e.maxWaitMinutes>0&&c.nodeHeldSince!==null&&s-c.nodeHeldSince>=e.maxWaitMinutes*6e4){this.log(`[admission] ${c.agentId} refused after ${Math.round((s-c.nodeHeldSince)/6e4)}m held by the node \u2014 ${c.blockedBy.join("; ")||"no room"}`),this.refuse(c,"timeout");continue}let u=[],l=c.cls?e.classes[c.cls]?.max:void 0;l!==void 0&&this.classCount(c.cls)>=l&&u.push(`class ${c.cls}: ${this.classCount(c.cls)}/${l} running`),c.req.canStart&&!c.req.canStart()&&u.push("agent busy");let p=[];i&&p.push("behind earlier work");let f=c.priority==="owner"?e.ownerExtraSessions:0,h=r+Math.max(f,c.delegated?e.delegationHeadroom:0);this.running.size>=h&&p.push(`session cap: ${this.running.size}/${h} running`);let y=[];o.length&&!(e.allowOneWhenIdle&&this.running.size===0)&&(y.push(...o),u.length||(a=!0));let A=this.paceWait(c.priority,e,s);if(A>0&&y.push(`start pace: next start in ${Math.ceil(A/1e3)}s`),p.push(...y),!e.enabled||e.mode==="observe"){if(e.enabled&&p.some(x=>x!=="behind earlier work")&&this.log(`[admission] observe: would hold ${c.agentId} (${c.priority}) \u2014 ${p.join("; ")}`),u.includes("agent busy")){c.blockedBy=u;continue}this.admitEntry(c,d);continue}if(u.length||p.length){c.blockedBy=[...p,...u],p.length?c.nodeHeldSince??=s:c.nodeHeldSince=null,y.length&&(i=!0);continue}this.admitEntry(c,d)}this.closeIdleRound(e,a?o:[],s)}closeIdleRound(e,t,s){let r=t.filter(d=>d.startsWith("memory:")||d.startsWith("swap:"));if(!r.length){this.saidNothingToClose=!1;return}let o=e.closeIdle;if(!e.enabled||!o.enabled||this.lastCloseRoundAt!==null&&s-this.lastCloseRoundAt<o.settleSeconds*1e3)return;let i=new Set([...this.waiting,...this.running.values()].map(d=>fe({agentId:d.agentId,channel:d.channel,chatId:d.chatId??""}))),a=e.mode==="observe",c=this.closeIdle({max:o.maxPerRound,minQuietMs:o.minQuietSeconds*1e3,reason:`gate shut (${r.join("; ")})`,skip:d=>i.has(fe(d)),dryRun:a});if(!c.length){this.saidNothingToClose||this.log(`[admission] gate shut (${r.join("; ")}): no idle session to close`),this.saidNothingToClose=!0;return}this.saidNothingToClose=!1,this.lastCloseRoundAt=s,a?this.log(`[admission] observe: would close ${c.length} idle session(s) \u2014 ${c.map(fe).join(", ")}`):this.log(`[admission] gate shut (${r.join("; ")}): closed ${c.length} idle session(s), ${this.waiting.length} waiting`)}admitEntry(e,t){this.drop(e);try{e.req.onStart?.()}catch{}let s=this.start(e,t);t>=1e3&&this.log(`[admission] started ${e.agentId} (${e.priority}) after ${Math.round(t/1e3)}s in the queue`),e.resolve({ok:!0,ticket:s})}arm(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),!this.waiting.length||this.closed)return;let e=this.settings(),t=this.now(),s=Math.max(1,e.sampleSeconds)*1e3;for(let r of this.waiting){let o=this.paceWait(r.priority,e,t);o>0&&(s=Math.min(s,o+50))}this.timer=setTimeout(()=>{this.timer=null,this.pump()},s),this.timer.unref?.()}snapshot(){let e=this.settings(),t=this.now(),s=this.sampler.latest(),r=s?qd(e,s.memTotalMB):e.maxSessions||null,o=this.ordered().map((d,u)=>({position:u+1,id:d.id,agentId:d.agentId,channel:d.channel,chatId:d.chatId??null,priority:d.priority,class:d.cls,label:d.label,waitingSeconds:Math.round((t-d.enqueuedAt)/1e3),blockedBy:d.blockedBy})),i={};for(let[d,u]of Object.entries(e.classes))i[d]={max:u.max,running:this.classCount(d)};let a=this.bootAt+e.boot.windowSeconds*1e3,c=s?Gd(s,e):[];return{enabled:e.enabled,mode:e.mode,checkedAt:s?new Date(s.at).toISOString():null,resources:s,limits:s?zd(e,s):null,gate:{open:c.length===0,reasons:c},caps:{maxSessions:r,ownerExtraSessions:e.ownerExtraSessions,delegationHeadroom:e.delegationHeadroom,classes:i},warmUp:{active:t<a,until:new Date(a).toISOString(),startsPerInterval:e.boot.startsPerInterval,intervalSeconds:e.boot.intervalSeconds},running:[...this.running.values()].map(d=>({id:d.id,agentId:d.agentId,channel:d.channel,chatId:d.chatId??null,priority:d.priority,class:d.cls,label:d.label,startedAt:new Date(d.startedAt).toISOString(),waitedSeconds:Math.round(d.waitedMs/1e3)})),waiting:o,next:o[0]??null}}async refresh(){await this.sampler.read(this.now())}};import{execFile as im}from"child_process";import{readFile as am,statfs as dm}from"fs/promises";import{cpus as cm,freemem as um,loadavg as lm,platform as gm,totalmem as pm}from"os";var wt=1024*1024;function mm(n){let e=Number(n.match(/page size of (\d+) bytes/)?.[1]);if(!e)return null;let t=r=>{let o=n.match(new RegExp(`^${r}:\\s+(\\d+)`,"m"));return o?Number(o[1]):0},s=t("Pages free")+t("Pages inactive")+t("Pages speculative")+t("Pages purgeable");return Math.round(s*e/wt)}function fm(n){let e=r=>{let o=n.match(new RegExp(`${r}\\s*=\\s*([\\d.]+)([KMGT]?)`));if(!o)return null;let i={"":1/wt,K:1/1024,M:1,G:1024,T:1024*1024};return Number(o[1])*(i[o[2]]??1)},t=e("total"),s=e("used");return t===null||s===null?null:{totalMB:Math.round(t),usedMB:Math.round(s)}}function hm(n){let e=o=>{let i=n.match(new RegExp(`^${o}:\\s+(\\d+)`,"m"));return i?Number(i[1]):null},t=e("MemAvailable");if(t===null)return null;let s=e("SwapTotal")??0,r=e("SwapFree")??s;return{availableMB:Math.round(t/1024),swapTotalMB:Math.round(s/1024),swapUsedMB:Math.round(Math.max(0,s-r)/1024)}}function Qd(n,e){return new Promise(t=>{im(n,e,{timeout:3e3},(s,r)=>t(s?"":String(r)))})}async function ym(n){let e=Math.round(pm()/wt),t=Math.round(um()/wt),s=0,r=0,o=gm(),i=o==="darwin";if(o==="darwin"){let[c,d]=await Promise.all([Qd("vm_stat",[]),Qd("sysctl",["-n","vm.swapusage"])]);t=mm(c)??t;let u=fm(d);u&&(s=u.totalMB,r=u.usedMB)}else if(o==="linux"){let c=hm(await am("/proc/meminfo","utf-8").catch(()=>""));c&&(t=c.availableMB,s=c.swapTotalMB,r=c.swapUsedMB)}let a=null;try{let c=await dm(n);a=Math.round(Number(c.bavail)*Number(c.bsize)/wt)}catch{}return{at:Date.now(),memTotalMB:e,memAvailableMB:t,swapTotalMB:s,swapUsedMB:r,swapGrows:i,diskFreeMB:a,load1:Math.round(lm()[0]*100)/100,cpuCount:Math.max(1,cm().length)}}var xn=class{constructor(e,t=3e3,s=ym){this.diskPath=e;this.ttlMs=t;this.sample=s}last=null;pending=null;latest(){return this.last}async read(e=Date.now()){return this.last&&e-this.last.at<this.ttlMs?this.last:(this.pending||(this.pending=this.sample(this.diskPath).then(t=>(this.last=t,t)).finally(()=>{this.pending=null})),this.pending)}};var bm=250,xm=5e3,vm={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},Am=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),Xd=`[Operating principle]
137
+ Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`,$m="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function Cm(n){return n==="claude-code"?`${Xd}
138
+ ${$m}`:n==="codex-cli"?Xd:""}function Yd(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var sc;function Kb(n){sc=n}function Jb(){return sc}function Mm(n){let e=n.split(`
139
+ `);for(let t=e.length-1;t>=0;t--){let s=Gr(e[t].trim());if(s)return s.length>160?s.slice(0,159)+"\u2026":s}}var Zd=64*1024,Rm=5*60*1e3,_m=3e4,Pm=300,Em=25*6e4,Ye=".agentx/task-history",Om=30;function xt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function Dm(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Lm(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=lo(n,e,V().recent());return po(t,s)}function Nm(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function Bm(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let l=u.meta.type||"untyped",p=r.get(l)||[];p.push(u.meta.title),r.set(l,p)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
140
+ `),c=process.argv[1]||"dist/cli.js",d=n.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${s.length} article${s.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
141
+ node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${c} wiki facts list --dir ${d}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,...t.notesInbox&&t.notesInbox.inbox!==e?["",`When you learn something the wiki should know (a change, a correction, a fact that went stale), leave a short note for the wiki run: \`node ${c} wiki notes add --from ${e} --change "what changed" --source "where you saw it" --date YYYY-MM-DD --daemon ${t.notesInbox.daemonUrl}\`. The run checks it before it changes anything. Notes stay inside the fleet; never put secrets in one.`]:[],"[End Institutional Wiki]"].join(`
142
+ `)}var Es=8*1024;function Fm(n,e){if(n)try{Lo(n)}catch{}return e}function Vd(n){if(n.length<=Es)return n;let e=n.length-Es;return n.slice(0,Es)+`\u2026[+${e}]`}function ec(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function Um(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function tc(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=V();if(s==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Vd(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Vd(a):null,at:r})}return}}function Hm(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
154
143
  `;if(s==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
155
144
  `;if(s==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
156
145
  `;if(s==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
@@ -160,7 +149,7 @@ ${$m}`:n==="codex-cli"?Qd:""}function Xd(n,e){return e!=="claude-code"&&e!=="cod
160
149
  `}if(s==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
161
150
  `;if(s==="turn.started")return`. codex turn started
162
151
  `;if(s==="turn.completed"){let r=t.usage||{},o=r.input_tokens??r.inputTokens,i=r.output_tokens??r.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
163
- `}if(s==="item.started"||s==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let d=r.text,c=d.startsWith(e)?d.slice(e.length):d;return e=d.startsWith(e)?d:e+d,c}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(s==="item.started")return`
152
+ `}if(s==="item.started"||s==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let c=r.text,d=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,d}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(s==="item.started")return`
164
153
  > codex ${o}${i?` ${i}`:""}
165
154
  `;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${xt(String(a),800)}`:""}
166
155
  `}if(s==="error"||s==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${xt(String(r),800)}
@@ -169,34 +158,34 @@ ${$m}`:n==="codex-cli"?Qd:""}function Xd(n,e){return e!=="claude-code"&&e!=="cod
169
158
  \u{1F4AD} ${xt(o.thinking,600)}
170
159
  `;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?xt(JSON.stringify(o.input),400):"";r+=`
171
160
  \u2192 ${i}(${a})
172
- `}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(d=>typeof d?.text=="string"?d.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${xt(i,800)}
161
+ `}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${xt(i,800)}
173
162
  `}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
174
- `:""}}var tc=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new so;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;admission;admissionTickets=new WeakMap;voiceClaims=new Set;workLanes=new an({log:e=>this.log(e)});notices=new dn;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new to;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;specTests;worktreesPending=new Map;worktreesPrunedAt=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new tn(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new Yr(void 0,void 0,"graph"),this.memoryStore=new no,this.patternStore=new on,this.rateLimiter=new nn,this.tokenTracker=new Vr,this.messageQueue=new sn,this.admission=new bn(()=>this.admissionSettings(),new xn(ae(G(process.cwd(),".agentx"))?G(process.cwd(),".agentx"):process.cwd()),s=>this.log(s),Date.now,s=>rt()?.closeIdle(s)??[]),ya({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),mo(ho(e)),fo(bo(e)),this.budgetHolds=new un(ms,G(process.cwd(),".agentx/budget-holds.json"),s=>this.log(s)),this.budgetHolds.size&&(this.log(`[budget] ${this.budgetHolds.size} held message(s) kept from before the restart`),this.armBudgetRelease()),e.graph?.enabled){this.graphStore=new Qr({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Xr({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setRunNote(e){this.runNote=e}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}admissionSettings(){let e=this.config.admission??Gd;return process.env.AGENTX_ADMISSION==="off"?{...e,enabled:!1}:e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=kr(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Po(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let d of a.def.mentions){if(t.atMentionsOnly&&!d.startsWith("@"))continue;let c=d.toLowerCase();s.includes(c)&&c.length>o&&(r=i,o=c.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,d=[];try{let p=this.sessions.getSession(e.agentId,s,r);i=Di(p.messages,e.message??""),d=Li(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let c={message:e.message??"",previousMessage:i,recentRequests:d,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await Se(Jo,Qo(c),zo,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!Xo(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),V().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-26CFE4JN.js"),d=await a(t,s);if(!d.memo){this.log(`[${e}] rotation memo skipped (${i}, ${d.reason}, ${d.durationMs}ms)`);return}let{storeRotationMemo:c}=await import("./rotation-memo-store-DO3W5LXB.js"),u=c(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:d.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${d.durationMs}ms, ${d.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
175
- `)[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 hn(G(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...yn,...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=mt(t.context?.chatId),a=this.cloudSessionStore();return md({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={...yn,...e.cloudSessions??{}},i=Date.now(),a=_e(ct(je(e.workspace),t),e.billing),d=l=>hd({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),c=await this.planSpecTests(t.agentId,s),u=await yd({route:s,agentId:t.agentId,message:c?`${t.message}
176
- ${Cd(c.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d,log:l=>this.log(l),trace:l=>{try{V().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(c&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!Cs(this.specTestStore().get(c.repo,c.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,c,s.cwd,p=>d({cwd:s.cwd,prompt:p,sessionId:l}).then(f=>{if(!f.ok)throw new Error(f.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}async inTaskWorktree(e,t){let s={...Ld,...e.worktrees??{}};if(!s.enabled)return{def:e,task:t};let r=Nd(t.context?.channel,t.context?.chatId);if(!r)return{def:e,task:t};let o=`${r.repo?`${r.repo}#`:""}${r.id}`,i=Bd(r,[t.context?.runbookPath,e.workspace].filter(p=>!!p));if("reason"in i)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${i.reason}`),{def:e,task:t};let a=`${t.agentId}:${i.dir}:${o}`,d=this.worktreesPending.get(a);d||(d=Ud(r,i.dir,s,{exec:Xe,log:p=>this.log(p)}),this.worktreesPending.set(a,d),d.finally(()=>this.worktreesPending.delete(a)).catch(()=>{}));let c;try{c=await d}catch(p){c={error:p?.message||String(p)}}if("error"in c)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${c.error}`),{def:e,task:t};this.log(`[worktrees] ${t.agentId} ${o}: ${c.reused?"reusing":"created"} ${c.dir} on ${c.branch}`);let u=this.worktreesPrunedAt.get(i.dir)??0;Date.now()-u>36e5&&(this.worktreesPrunedAt.set(i.dir,Date.now()),Hd(i.dir,s,{exec:Xe,log:p=>this.log(p),keep:c.dir}).then(p=>{p.length&&this.log(`[worktrees] removed ${p.length} unused worktree(s): ${p.join(", ")}`)}).catch(p=>this.log(`[worktrees] prune failed: ${p?.message||p}`)));let l=jd(c);return{fresh:!c.reused,def:{...e,persistentProcess:!1},task:{...t,cwd:c.dir,systemPromptAppend:t.systemPromptAppend?`${t.systemPromptAppend}
177
-
178
- ${l}`:l}}}specTestSettings(){return{...vd,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new wn(G(process.cwd(),".agentx/spec-tests.json"))),this.specTests}async planSpecTests(e,t){let s=this.specTestSettings();if(!s.enabled||t.route!=="cloud"||t.kind!=="issue")return null;let r=await Ed(Xe,t.repo,t.number,t.cwd),o=Md({settings:s,issue:r,codeAgent:e,previous:this.specTestStore().get(t.repo,t.number)});return o.run?o.input:(this.log(`[spec-tests] ${t.repo}#${t.number}: not running: ${o.reason}`),null)}async startSpecTests(e,t,s,r){try{await Rd({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:Xe,runAgent:Pd,store:this.specTestStore(),noteOnIssue:o=>Od(Xe,t.repo,t.number,s,o),tellAuthor:r,log:o=>this.log(o)})}catch(o){this.log(`[spec-tests] ${t.repo}#${t.number}: ${o?.message||o}`)}}async waitForChat(e,t,s,r){let o=Date.now(),i=25*6e4,a=`${e}\0${s}`;for(;this.messageQueue.isBusy(e,t,s)||this.voiceClaims.has(a);){if(r?.callerSignal?.aborted)return this.callerGone(r,"chat wait");if(Date.now()-o>i)return{content:"",error:`Agent "${e}" busy \u2014 ${t} wait timed out after ${Math.round(i/6e4)}m`};await new Promise(d=>setTimeout(d,500))}return this.voiceClaims.add(a),a}callerGone(e,t){let s=Ne(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=e.context?.channel,i=da(e.message,o);if(aa(o)&&!e.preSpawnRetry&&!e.timeLimitContinuation){let c=this.notices.take(e.agentId);c&&(e={...e,message:c+e.message})}if(!i)return this.runWithRecovery(e,t,s,r);let a=await this.workLanes.enter(e.agentId,i,st()?.rootId,e.callerSignal),d={content:"",error:"run did not end"};try{let c=a.note?{...e,message:a.note+e.message}:e;return d=await this.runWithRecovery(c,t,s,r),d}finally{let c=!!d.error&&We(d.error);a.release({text:d.error?d.error:d.content??"",ok:!d.error,ran:!c})}}async runWithRecovery(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(l){i={content:"",error:l?.message??String(l)}}this.admissionTickets.get(e)?.release();let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let d=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;d&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:d,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&!d&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.runWithRecovery({...e,preSpawnRetry:1,runningTaskId:void 0},t,s,r);if(c){let l=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${l}"). Please send it again.`,errorKind:"interrupted"}}let u=Ki({error:i.error,errorKind:i.errorKind,viaMesh:i.viaMesh,channel:e.context?.channel,chatId:e.context?.chatId,workflowRunId:e.workflowRunId,continuation:e.timeLimitContinuation??0,timeoutMinutes:e.timeoutMinutes,elapsedMs:Date.now()-(e.timeLimitStartedAt??o),callerGone:e.callerSignal?.aborted??!1,settings:this.config.resume?.timeLimit??ss});if(u.action==="continue"){let l=this.config.resume?.timeLimit??ss,p=e.taskId,f=[];try{f=p&&this.traceToolCalls?this.traceToolCalls(p):[]}catch{}let h=zi(u.minutes,f,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${p??"-"}: stopped at its ${u.minutes}m time limit; continuing (${u.continuation}/${l.maxContinuations})`);let y=e.timeLimitRequest??e.message;return this.runWithRecovery({...e,message:`${h}
179
- ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:p??e.resumedFrom,runningTaskId:void 0,freshSession:!1},t,s,r)}if(u.action==="report"&&(this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${e.taskId??"-"}: stopped at its ${u.minutes}m time limit; not continued \u2014 ${u.reason}`),i={...i,error:Ji(i.error,u.reason)}),e.intentRef)try{let l=i.error?We(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";oo().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:l,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(l){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${l?.message??l}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};e.isolated&&(e.autonomy="report");let i=me(e.autonomy),a=vr(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:pa().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(T=>T.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}=Vt(e.context),p,f=u==="app"&&e.context?.via==="voice",h=wo(yo(),e.agentId);if(h)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:h,errorKind:"agent_held"};if(!i){let g=e.context?.channel,m=e.context?.chatId,T=Ft(e.agentId,void 0,Bt(e.agentId,m));if(T&&g&&m&&Hn()?.getChannel(g)){let k=this.budgetHolds.hold(e.agentId,{text:e.message,channel:g,chatId:String(m),context:e.context,heldAt:e.queuedAt??Date.now()});if(k!=="full"){this.armBudgetRelease();let U=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${U} waiting) chat=${g}:${m}`),k==="held"?{content:"",error:Nn("budget",U)}:{content:"",error:`${T.message} This message is kept and runs when the agent resumes.`,errorKind:"budget_cap"}}this.log(`[${e.agentId}] over budget \u2014 hold is full, message refused`)}}if(u==="app"){let g=await this.waitForChat(e.agentId,u,l,e);if(typeof g!="string")return g;p=g}let y=()=>{p&&this.voiceClaims.delete(p)};if(c.activeTasks>=c.def.maxConcurrent)if(u==="api"||u==="app"&&!f||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i){let g=Date.now(),m=e.slotWaitMs??Em,T=500,k=m<6e4?`${Math.max(1,Math.ceil(m/1e3))}s`:`${Math.round(m/6e4)}m`;for(c.activeTasks>=c.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${k}) behind=${c.runningTasks.map(U=>U.id).join(",")||"-"} chat=${u}:${l}`);c.activeTasks>=c.def.maxConcurrent;){if(e.callerSignal?.aborted)return y(),this.callerGone(e,"slot wait");if(Date.now()-g>m)return y(),this.log(`[${e.agentId}] slot wait timed out after ${k} chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${k}`,errorKind:"agent_busy"};await new Promise(U=>setTimeout(U,T))}Date.now()-g>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-g)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"||f){if(!p){let g=await this.waitForChat(e.agentId,u,l);if(typeof g!="string")return g;p=g}}else{let g=c.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 T=this.messageQueue.pendingCount(e.agentId,u,l);return V().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:On(e.context),humanRoot:et(e.context),person:Dt(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: ${T}) behind=${c.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Nn(m,T)}}}let A=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(!A.ok)return y(),this.log(`[${e.agentId}] ${A.reason}`),{content:"",error:A.reason};if(e.callerSignal?.aborted)return y(),this.callerGone(e,"rate-limit wait");if(this.admissionSettings().tiers.includes(c.def.tier)){let g=Dt(this.config.people,e.context),m=u==="voice"?`${e.agentId}\0${l}`:null,T=await this.admission.admit({agentId:e.agentId,channel:u,chatId:l,person:g?.id??null,owner:g?.role==="owner",delegated:xr(e.context)&&!e.context?.delegation,keepOnClose:e.origin?.kind==="router",canStart:()=>c.activeTasks<c.def.maxConcurrent&&!(m&&m!==p&&(this.voiceClaims.has(m)||this.messageQueue.isBusy(e.agentId,u,l))),onStart:()=>{c.activeTasks++,m&&!p&&(p=m,this.voiceClaims.add(m))},signal:e.callerSignal});if(y(),!T.ok){if(T.reason==="caller-gone")return this.callerGone(e,"node queue");if(T.reason==="closed")return{content:"",error:`Agent "${e.agentId}" not started: the daemon is restarting`,errorKind:"interrupted"};let k=Math.round(T.waitedMs/6e4);return{content:"",error:`This machine had no room to start agent "${e.agentId}" for ${k} min (${T.blockedBy.join("; ")||"busy"}). Please send it again later.`}}this.admissionTickets.set(e,T.ticket)}else y(),c.activeTasks++;if(e.queuedAt!==void 0){let g=Xi(e.queuedAt);g&&(e.message=`${g}
180
- ${e.message}`),e.queuedAt=void 0}let E=ea({message:e.message,home:e.context?.home}),H=Vi(c.runningTasks,E,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});H&&(this.log(`[${e.agentId}] ${H.slice(0,160)}`),e.message=`${H}
181
- ${e.message}`),c.totalTasks++,c.lastActive=new Date;let b={...E.length?{homes:E}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};c.runningTasks.push(b),e.runningTaskId=b.id;let _=Dt(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(b.id,e.context??{}),e.onStart)try{e.onStart(b.id)}catch{}let R=new AbortController;this.taskAborts.set(b.id,{agentId:e.agentId,channel:b.channel,chatId:typeof b.chatId=="string"?b.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:st()?.rootId,workflowRunId:e.workflowRunId??(typeof b.chatId=="string"&&b.chatId.startsWith("workflow:")&&b.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(b.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>Yd&&(M.buffer=M.buffer.slice(M.buffer.length-Yd));for(let m of M.subscribers)try{m(g)}catch{}}},N=Ue();e.taskId=N,b.traceId=N;let j=this.taskAborts.get(b.id);j&&(j.traceId=N);let q=new Map,J=(g,m,T)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:T,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},$=0,v=!1,S=()=>{v||(v=!0,$&&J("first-event",$,"ok"))},B;if(t){let g=Hm();B=m=>{S();let T=g(m);if(T&&L(T),ec(N,e.agentId,m),Vd(q,m),ps(m,void 0,e.model||c.def.model),gs(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(S(),ec(N,e.agentId,g),Vd(q,g),ps(g,void 0,e.model||c.def.model),gs(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,P=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;P?.unref?.();let Q=(c.def.preSpawnTimeoutSec??Pm)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${b.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Ne(R.signal).message;/^timed out/.test(g)&&(te=b.step??"start"),this.log(`[${e.agentId}] task ${b.id} aborted in step "${b.step??"start"}" \u2014 ${g} ${D()}`)},{once:!0});let ne=g=>{b.step=g,this.log(`[${e.agentId}] step ${g} ${D()}`)},le=(g,m,T=0)=>{if(R.signal.aborted)return Promise.reject(Ne(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),$=Date.now());let k=Date.now(),U=pd(m(),vm[g]??0,g);return gd(U,R.signal,T).then(K=>(J(g,k,"ok"),K),K=>{throw J(g,k,"error"),K instanceof Qe&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},St=async(g,m,T,k=0)=>{try{return await le(g,m,k)}catch(U){if(U instanceof Qe)return T();throw U}},Es=!1,Sn=!1,Os=g=>{if(!(!Es||Sn)){Sn=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-b.startedAt.getTime(),error:g?.error||(R.signal.aborted?Ne(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(b.id)?!0:void 0,stopped:!this.interruptedRuns.has(b.id)&&(this.stoppedRuns.has(b.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Ds=!1,Ls=g=>{if(Ds)return;Ds=!0,Os(g),this.runReleases.delete(b.id),P&&clearTimeout(P),oe(),c.activeTasks--,this.admissionTickets.get(e)?.release();let m=c.runningTasks.findIndex(k=>k.id===b.id);m!==-1&&c.runningTasks.splice(m,1),this.runningContexts.delete(b.id),this.taskAborts.delete(b.id);let T=this.runEndWaiters.get(b.id);this.runEndWaiters.delete(b.id);for(let k of T??[])try{k()}catch{}M.done=!0,M.endedAt=new Date;for(let k of M.subscribers)try{k(`
163
+ `:""}}var nc=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new so;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;admission;admissionTickets=new WeakMap;voiceClaims=new Set;workLanes=new an({log:e=>this.log(e)});notices=new dn;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new to;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;specTests;worktreesPending=new Map;worktreesPrunedAt=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new tn(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new Yr(void 0,void 0,"graph"),this.memoryStore=new no,this.patternStore=new on,this.rateLimiter=new nn,this.tokenTracker=new Vr,this.messageQueue=new sn,this.admission=new bn(()=>this.admissionSettings(),new xn(ae(G(process.cwd(),".agentx"))?G(process.cwd(),".agentx"):process.cwd()),s=>this.log(s),Date.now,s=>rt()?.closeIdle(s)??[]),wa({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),ho(wo(e)),yo(So(e)),this.budgetHolds=new un(fs,G(process.cwd(),".agentx/budget-holds.json"),s=>this.log(s)),this.budgetHolds.size&&(this.log(`[budget] ${this.budgetHolds.size} held message(s) kept from before the restart`),this.armBudgetRelease()),e.graph?.enabled){this.graphStore=new Qr({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Xr({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setRunNote(e){this.runNote=e}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}admissionSettings(){let e=this.config.admission??Kd;return process.env.AGENTX_ADMISSION==="off"?{...e,enabled:!1}:e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=kr(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Oo(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,s,r);i=Ni(p.messages,e.message??""),c=Bi(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await Se(Qo,Yo(d),Xo,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!Zo(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),V().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-26CFE4JN.js"),c=await a(t,s);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-DO3W5LXB.js"),u=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
164
+ `)[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 hn(G(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...yn,...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=mt(t.context?.chatId),a=this.cloudSessionStore();return fd({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={...yn,...e.cloudSessions??{}},i=Date.now(),a=_e(ct(je(e.workspace),t),e.billing),c=l=>yd({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),d=await this.planSpecTests(t.agentId,s),u=await wd({route:s,agentId:t.agentId,message:d?`${t.message}
165
+ ${Md(d.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:c,log:l=>this.log(l),trace:l=>{try{V().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:l.action,status:l.status,outputSummary:l.status==="ok"?l.summary:void 0,error:l.status==="error"?l.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});if(!u)return null;if(d&&s.route==="cloud"&&!u.error&&!u.cloudSession.followUp&&!Ms(this.specTestStore().get(d.repo,d.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,d,s.cwd,p=>c({cwd:s.cwd,prompt:p,sessionId:l}).then(f=>{if(!f.ok)throw new Error(f.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}async inTaskWorktree(e,t){let s={...Nd,...e.worktrees??{}};if(!s.enabled)return{def:e,task:t};let r=Bd(t.context?.channel,t.context?.chatId);if(!r)return{def:e,task:t};let o=`${r.repo?`${r.repo}#`:""}${r.id}`,i=Fd(r,[t.context?.runbookPath,e.workspace].filter(p=>!!p));if("reason"in i)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${i.reason}`),{def:e,task:t};let a=`${t.agentId}:${i.dir}:${o}`,c=this.worktreesPending.get(a);c||(c=Hd(r,i.dir,s,{exec:Xe,log:p=>this.log(p)}),this.worktreesPending.set(a,c),c.finally(()=>this.worktreesPending.delete(a)).catch(()=>{}));let d;try{d=await c}catch(p){d={error:p?.message||String(p)}}if("error"in d)return this.log(`[worktrees] ${t.agentId} ${o}: running in the workspace: ${d.error}`),{def:e,task:t};this.log(`[worktrees] ${t.agentId} ${o}: ${d.reused?"reusing":"created"} ${d.dir} on ${d.branch}`);let u=this.worktreesPrunedAt.get(i.dir)??0;Date.now()-u>36e5&&(this.worktreesPrunedAt.set(i.dir,Date.now()),jd(i.dir,s,{exec:Xe,log:p=>this.log(p),keep:d.dir}).then(p=>{p.length&&this.log(`[worktrees] removed ${p.length} unused worktree(s): ${p.join(", ")}`)}).catch(p=>this.log(`[worktrees] prune failed: ${p?.message||p}`)));let l=Wd(d);return{fresh:!d.reused,def:{...e,persistentProcess:!1},task:{...t,cwd:d.dir,systemPromptAppend:t.systemPromptAppend?`${t.systemPromptAppend}
166
+
167
+ ${l}`:l}}}specTestSettings(){return{...Ad,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new wn(G(process.cwd(),".agentx/spec-tests.json"))),this.specTests}async planSpecTests(e,t){let s=this.specTestSettings();if(!s.enabled||t.route!=="cloud"||t.kind!=="issue")return null;let r=await Od(Xe,t.repo,t.number,t.cwd),o=Rd({settings:s,issue:r,codeAgent:e,previous:this.specTestStore().get(t.repo,t.number)});return o.run?o.input:(this.log(`[spec-tests] ${t.repo}#${t.number}: not running: ${o.reason}`),null)}async startSpecTests(e,t,s,r){try{await _d({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:Xe,runAgent:Ed,store:this.specTestStore(),noteOnIssue:o=>Dd(Xe,t.repo,t.number,s,o),tellAuthor:r,log:o=>this.log(o)})}catch(o){this.log(`[spec-tests] ${t.repo}#${t.number}: ${o?.message||o}`)}}async waitForChat(e,t,s,r){let o=Date.now(),i=25*6e4,a=`${e}\0${s}`;for(;this.messageQueue.isBusy(e,t,s)||this.voiceClaims.has(a);){if(r?.callerSignal?.aborted)return this.callerGone(r,"chat wait");if(Date.now()-o>i)return{content:"",error:`Agent "${e}" busy \u2014 ${t} wait timed out after ${Math.round(i/6e4)}m`};await new Promise(c=>setTimeout(c,500))}return this.voiceClaims.add(a),a}callerGone(e,t){let s=Ne(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=e.context?.channel,i=ca(e.message,o);if(da(o)&&!e.preSpawnRetry&&!e.timeLimitContinuation){let d=this.notices.take(e.agentId);d&&(e={...e,message:d+e.message})}if(!i)return this.runWithRecovery(e,t,s,r);let a=await this.workLanes.enter(e.agentId,i,st()?.rootId,e.callerSignal),c={content:"",error:"run did not end"};try{let d=a.note?{...e,message:a.note+e.message}:e;return c=await this.runWithRecovery(d,t,s,r),c}finally{let d=!!c.error&&We(c.error);a.release({text:c.error?c.error:c.content??"",ok:!c.error,ran:!d})}}async runWithRecovery(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(l){i={content:"",error:l?.message??String(l)}}this.admissionTickets.get(e)?.release();let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.runWithRecovery({...e,preSpawnRetry:1,runningTaskId:void 0},t,s,r);if(d){let l=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${l}"). Please send it again.`,errorKind:"interrupted"}}let u=zi({error:i.error,errorKind:i.errorKind,viaMesh:i.viaMesh,channel:e.context?.channel,chatId:e.context?.chatId,workflowRunId:e.workflowRunId,continuation:e.timeLimitContinuation??0,timeoutMinutes:e.timeoutMinutes,elapsedMs:Date.now()-(e.timeLimitStartedAt??o),callerGone:e.callerSignal?.aborted??!1,settings:this.config.resume?.timeLimit??rs});if(u.action==="continue"){let l=this.config.resume?.timeLimit??rs,p=e.taskId,f=[];try{f=p&&this.traceToolCalls?this.traceToolCalls(p):[]}catch{}let h=Xi(u.minutes,f,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${p??"-"}: stopped at its ${u.minutes}m time limit; continuing (${u.continuation}/${l.maxContinuations})`);let y=e.timeLimitRequest??e.message;return this.runWithRecovery({...e,message:`${h}
168
+ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:p??e.resumedFrom,runningTaskId:void 0,freshSession:!1},t,s,r)}if(u.action==="report"&&(this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${e.taskId??"-"}: stopped at its ${u.minutes}m time limit; not continued \u2014 ${u.reason}`),i={...i,error:Qi(i.error,u.reason)}),e.intentRef)try{let l=i.error?We(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";oo().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:l,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(l){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${l?.message??l}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};e.isolated&&(e.autonomy="report");let i=me(e.autonomy),a=vr(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:ma().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(T=>T.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}=Vt(e.context),p,f=u==="app"&&e.context?.via==="voice",h=xo(bo(),e.agentId);if(h)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:h,errorKind:"agent_held"};if(!i){let g=e.context?.channel,m=e.context?.chatId,T=Ft(e.agentId,void 0,Bt(e.agentId,m));if(T&&g&&m&&jn()?.getChannel(g)){let k=this.budgetHolds.hold(e.agentId,{text:e.message,channel:g,chatId:String(m),context:e.context,heldAt:e.queuedAt??Date.now()});if(k!=="full"){this.armBudgetRelease();let U=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${U} waiting) chat=${g}:${m}`),k==="held"?{content:"",error:Bn("budget",U)}:{content:"",error:`${T.message} This message is kept and runs when the agent resumes.`,errorKind:"budget_cap"}}this.log(`[${e.agentId}] over budget \u2014 hold is full, message refused`)}}if(u==="app"){let g=await this.waitForChat(e.agentId,u,l,e);if(typeof g!="string")return g;p=g}let y=()=>{p&&this.voiceClaims.delete(p)};if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"&&!f||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i){let g=Date.now(),m=e.slotWaitMs??Em,T=500,k=m<6e4?`${Math.max(1,Math.ceil(m/1e3))}s`:`${Math.round(m/6e4)}m`;for(d.activeTasks>=d.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${k}) behind=${d.runningTasks.map(U=>U.id).join(",")||"-"} chat=${u}:${l}`);d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return y(),this.callerGone(e,"slot wait");if(Date.now()-g>m)return y(),this.log(`[${e.agentId}] slot wait timed out after ${k} chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${k}`,errorKind:"agent_busy"};await new Promise(U=>setTimeout(U,T))}Date.now()-g>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-g)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"||f){if(!p){let g=await this.waitForChat(e.agentId,u,l);if(typeof g!="string")return g;p=g}}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 T=this.messageQueue.pendingCount(e.agentId,u,l);return V().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Dn(e.context),humanRoot:et(e.context),person:Dt(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: ${T}) behind=${d.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Bn(m,T)}}}let A=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(!A.ok)return y(),this.log(`[${e.agentId}] ${A.reason}`),{content:"",error:A.reason};if(e.callerSignal?.aborted)return y(),this.callerGone(e,"rate-limit wait");if(this.admissionSettings().tiers.includes(d.def.tier)){let g=Dt(this.config.people,e.context),m=u==="voice"?`${e.agentId}\0${l}`:null,T=await this.admission.admit({agentId:e.agentId,channel:u,chatId:l,person:g?.id??null,owner:g?.role==="owner",delegated:xr(e.context)&&!e.context?.delegation,keepOnClose:e.origin?.kind==="router",canStart:()=>d.activeTasks<d.def.maxConcurrent&&!(m&&m!==p&&(this.voiceClaims.has(m)||this.messageQueue.isBusy(e.agentId,u,l))),onStart:()=>{d.activeTasks++,m&&!p&&(p=m,this.voiceClaims.add(m))},signal:e.callerSignal});if(y(),!T.ok){if(T.reason==="caller-gone")return this.callerGone(e,"node queue");if(T.reason==="closed")return{content:"",error:`Agent "${e.agentId}" not started: the daemon is restarting`,errorKind:"interrupted"};let k=Math.round(T.waitedMs/6e4);return{content:"",error:`This machine had no room to start agent "${e.agentId}" for ${k} min (${T.blockedBy.join("; ")||"busy"}). Please send it again later.`}}this.admissionTickets.set(e,T.ticket)}else y(),d.activeTasks++;if(e.queuedAt!==void 0){let g=Zi(e.queuedAt);g&&(e.message=`${g}
169
+ ${e.message}`),e.queuedAt=void 0}let E=na({message:e.message,home:e.context?.home}),H=ta(d.runningTasks,E,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});H&&(this.log(`[${e.agentId}] ${H.slice(0,160)}`),e.message=`${H}
170
+ ${e.message}`),d.totalTasks++,d.lastActive=new Date;let b={...E.length?{homes:E}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(b),e.runningTaskId=b.id;let _=Dt(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(b.id,e.context??{}),e.onStart)try{e.onStart(b.id)}catch{}let R=new AbortController;this.taskAborts.set(b.id,{agentId:e.agentId,channel:b.channel,chatId:typeof b.chatId=="string"?b.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:st()?.rootId,workflowRunId:e.workflowRunId??(typeof b.chatId=="string"&&b.chatId.startsWith("workflow:")&&b.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(b.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>Zd&&(M.buffer=M.buffer.slice(M.buffer.length-Zd));for(let m of M.subscribers)try{m(g)}catch{}}},N=Ue();e.taskId=N,b.traceId=N;let j=this.taskAborts.get(b.id);j&&(j.traceId=N);let q=new Map,J=(g,m,T)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:T,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},$=0,v=!1,S=()=>{v||(v=!0,$&&J("first-event",$,"ok"))},B;if(t){let g=Hm();B=m=>{S();let T=g(m);if(T&&L(T),tc(N,e.agentId,m),ec(q,m),ms(m,void 0,e.model||d.def.model),ps(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(S(),tc(N,e.agentId,g),ec(q,g),ms(g,void 0,e.model||d.def.model),ps(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,P=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;P?.unref?.();let Q=(d.def.preSpawnTimeoutSec??Pm)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${b.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Ne(R.signal).message;/^timed out/.test(g)&&(te=b.step??"start"),this.log(`[${e.agentId}] task ${b.id} aborted in step "${b.step??"start"}" \u2014 ${g} ${D()}`)},{once:!0});let ne=g=>{b.step=g,this.log(`[${e.agentId}] step ${g} ${D()}`)},le=(g,m,T=0)=>{if(R.signal.aborted)return Promise.reject(Ne(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),$=Date.now());let k=Date.now(),U=md(m(),vm[g]??0,g);return pd(U,R.signal,T).then(K=>(J(g,k,"ok"),K),K=>{throw J(g,k,"error"),K instanceof Qe&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},St=async(g,m,T,k=0)=>{try{return await le(g,m,k)}catch(U){if(U instanceof Qe)return T();throw U}},Os=!1,Sn=!1,Ds=g=>{if(!(!Os||Sn)){Sn=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-b.startedAt.getTime(),error:g?.error||(R.signal.aborted?Ne(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(b.id)?!0:void 0,stopped:!this.interruptedRuns.has(b.id)&&(this.stoppedRuns.has(b.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Ls=!1,Ns=g=>{if(Ls)return;Ls=!0,Ds(g),this.runReleases.delete(b.id),P&&clearTimeout(P),oe(),d.activeTasks--,this.admissionTickets.get(e)?.release();let m=d.runningTasks.findIndex(k=>k.id===b.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(b.id),this.taskAborts.delete(b.id);let T=this.runEndWaiters.get(b.id);this.runEndWaiters.delete(b.id);for(let k of T??[])try{k()}catch{}M.done=!0,M.endedAt=new Date;for(let k of M.subscribers)try{k(`
182
171
  [task finished]
183
- `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),Rm).unref?.();try{let k=M.endedAt,U={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(U);let K=(U.responseText||U.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:U.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let U=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,at:new Date().toISOString()});for(let X of k){let Ce=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Ce,queuedAt:X.queuedAt??X.timestamp}).then(be=>(We(be.error)||K(),this.postQueuedResponseToChannel(e.agentId,Ce,be)),be=>{throw K(),be}).catch(be=>{this.log(`[${e.agentId}] queued message failed: ${be.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Ls),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:sc,selectRequestContext:rc}=await import("./request-planner-63YQLEPP.js"),Ns=St("request-gate",()=>sc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),In=!1;Ns.then(()=>{In=!0},()=>{In=!0});let I=l,Tn=e.context?.sender||"User",de=c.def.tier==="codex-cli",Ze=Na(this.config.session,w,c.def.tier),It=Ba(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let Tt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await St("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let oc=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ud({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:oc,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,Tn,e.message);let Bs=Date.now(),Fs={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Bs).toISOString(),taskId:N,resumeOrigin:Gi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:On(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Sr(e.context),operator:Ir(e.context),dueAt:ld(e.context),taskType:fn(e.context)};V().emit("task:started",Fs),Es=!0;let ee,kn,Us=this.classifier;if(Us&&w!=="a2a"&&!de){ne("classify");let g=Date.now();kn=Us.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let Hs=async g=>{if(!kn)return;let m;await Promise.race([kn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await Hs(bm);let ve=this.config.workflows?.matching,we,js,Ws=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Ws?.enabled&&(Ws.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ve?.suggestThreshold??.65)&&(js=So(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ve?.enabled&&!i)try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ve.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ve.mode} reasons=${m.reasons.join(",")||"n/a"}`),ve.mode==="auto"&&m.confidence>=ve.autoRunThreshold&&(this.workflowAutoRunner?we={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 Ae=Io(this.config.workflows,e.agentId)&&To(e)?this.workflowRuns:void 0;if(Ae&&!we&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ve?.autoRunThreshold??.85;m&&m.confidence>=T&&(we={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ae?km():void 0,ic=ce?ko(ce):void 0,qs=this.wikiHub.getAgentWiki(e.agentId),Gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Ks=this.memoryStore.buildContext(Gs),Js=this.memoryStore.contextFacts(Gs),ac=this.patternStore.findRelevant(e.message,e.agentId,5),dc=this.patternStore.buildContext(ac),zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(c.def.workspace)),k=e.personLimits?.skills??[],U=k.length?T.filter(K=>!k.some(X=>tt(X,K.frontmatter.name))):T;zs=m(U,e.message)}catch{}let F=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,w,I,Tt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,F,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,F,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,F,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=Ko({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:Tt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${Wn(m)}`),this.captureRotationMemoAsync(e.agentId,c.def,F,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${Wn(m)}`)}}if(F&&c.def.tier==="claude-code"){let g=F;await St("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let cc=process.env.AGENTX_CONTEXT_SURGERY==="1",uc=de?{maxMessages:8,maxChars:2400}:cc&&Xd(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,lc=!F&&!de?Bm(qs,e.agentId,{notesInbox:Nm(this.config)}):void 0,Qs;if(!F&&!de)try{Qs=oa(qs.listArticles(e.agentId),Date.now())||void 0}catch{}let kt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,w,I,uc):void 0,gc=F?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Xs,Ys=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new pt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=ws(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Xs=bs(m),Ys=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Re&&Re.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],U=kt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${kt.length}c/${kt.split(`
184
- `).length}L`,K=`[${e.agentId}] ${w}:${I} ${U} | session.messages=${m.length}`+(m.length>0?` first=${T.timestamp.slice(11,19)}(${T.role}:${(T.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Re.cat("context",K)}catch(g){Re.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Zs;if(c.def.contextReferences&&!F)try{let g=c.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,U]=await le("references",()=>Promise.all([Bn(c.def.workspace),Fn(c.def.workspace)]));if(k.byId.size===0&&U.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Bn(process.cwd()),Fn(process.cwd())]));m={refs:K,recipes:X}}else m={refs:k,recipes:U};this.referencesCache.set(g,m)}let T=io({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);T.cards.length>0&&(Zs=ro(T.cards,500*4)),T.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${T.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Vs=ge||Ve?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),er,vt=ge?null:Oi(e.message);if(vt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:vt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${vt.lookbackDays}d on this chat (cue-triggered)]`],T=[...g.turns].sort((k,U)=>k.ts.localeCompare(U.ts));for(let k of T){let U=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${U} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),er=m.join(`
185
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${vt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let pc=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",tr,nr,sr=!1;In||ne("request-gate");let $e=await Ns;if($e.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),pc==="planner"&&!ge&&!$e.active&&!Ve&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(sr=!0,tr=m.sessionHistory,Ks=m.memoryContext,Js=m.memoryFacts,Vs=m.crossChatContext,nr=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)`)}sr&&F&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),F=void 0)}let vn=`${e.agentId}:${w}:${I}`,At=Br(e.message);At&&(At==="default"?(this.activeSouls.delete(vn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(vn,At),this.log(`[${e.agentId}] Soul switched to: ${At}`)));let mc=this.activeSouls.get(vn),fc=Lr(c.def.workspace,mc),hc=Nr(fc),yc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),wc=Cm(c.def.tier),bc=jm(c.def.richMessages,e.context?.via==="voice"?"voice":w),xc=c.def.tier==="claude-code"&&(ge||Ze!=="lean"||Fa(It)),rr="";if(c.def.workspace&&!xc){let g=G(c.def.workspace,"CLAUDE.md");if(ae(g))try{let m=bt(g,"utf-8");rr=`[Project CLAUDE.md]
172
+ `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),Rm).unref?.();try{let k=M.endedAt,U={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(U);let K=(U.responseText||U.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:U.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let U=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,at:new Date().toISOString()});for(let X of k){let Ce=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Ce,queuedAt:X.queuedAt??X.timestamp}).then(be=>(We(be.error)||K(),this.postQueuedResponseToChannel(e.agentId,Ce,be)),be=>{throw K(),be}).catch(be=>{this.log(`[${e.agentId}] queued message failed: ${be.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Ns),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:rc,selectRequestContext:oc}=await import("./request-planner-4GT4JGV2.js"),Bs=St("request-gate",()=>rc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),In=!1;Bs.then(()=>{In=!0},()=>{In=!0});let I=l,Tn=e.context?.sender||"User",de=d.def.tier==="codex-cli",Ze=Ba(this.config.session,w,d.def.tier),It=Fa(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let Tt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await St("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let ic=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ld({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:ic,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,Tn,e.message);let Fs=Date.now(),Us={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Fs).toISOString(),taskId:N,resumeOrigin:Ji(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Dn(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Sr(e.context),operator:Ir(e.context),dueAt:gd(e.context),taskType:fn(e.context)};V().emit("task:started",Us),Os=!0;let ee,kn,Hs=this.classifier;if(Hs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();kn=Hs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let js=async g=>{if(!kn)return;let m;await Promise.race([kn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await js(bm);let ve=this.config.workflows?.matching,we,Ws,qs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&qs?.enabled&&(qs.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ve?.suggestThreshold??.65)&&(Ws=To(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ve?.enabled&&!i)try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ve.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ve.mode} reasons=${m.reasons.join(",")||"n/a"}`),ve.mode==="auto"&&m.confidence>=ve.autoRunThreshold&&(this.workflowAutoRunner?we={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 Ae=ko(this.config.workflows,e.agentId)&&vo(e)?this.workflowRuns:void 0;if(Ae&&!we&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ve?.autoRunThreshold??.85;m&&m.confidence>=T&&(we={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ae?km():void 0,ac=ce?Ao(ce):void 0,vn=this.wikiHub.getAgentWiki(e.agentId),Gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Ks=this.memoryStore.buildContext(Gs),Js=this.memoryStore.contextFacts(Gs),dc=this.patternStore.findRelevant(e.message,e.agentId,5),cc=this.patternStore.buildContext(dc),zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],U=k.length?T.filter(K=>!k.some(X=>tt(X,K.frontmatter.name))):T;zs=m(U,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,w,I,Tt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=zo({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:Tt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${qn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${qn(m)}`)}}if(F&&d.def.tier==="claude-code"){let g=F;await St("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let uc=process.env.AGENTX_CONTEXT_SURGERY==="1",lc=de?{maxMessages:8,maxChars:2400}:uc&&Yd(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,gc=!F&&!de?Bm(vn,e.agentId,{notesInbox:Nm(this.config)}):void 0,Qs;if(!F&&!de)try{let g=this.config.wiki?.decisionApprovals?.required===!0,m=fo(vn.listArticles(e.agentId),vn.baseDir,g);Qs=mo(m,Date.now())||void 0}catch{}let kt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,w,I,lc):void 0,pc=F?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Xs,Ys=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new pt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=bs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Xs=xs(m),Ys=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Re&&Re.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],U=kt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${kt.length}c/${kt.split(`
173
+ `).length}L`,K=`[${e.agentId}] ${w}:${I} ${U} | session.messages=${m.length}`+(m.length>0?` first=${T.timestamp.slice(11,19)}(${T.role}:${(T.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Re.cat("context",K)}catch(g){Re.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Zs;if(d.def.contextReferences&&!F)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,U]=await le("references",()=>Promise.all([Fn(d.def.workspace),Un(d.def.workspace)]));if(k.byId.size===0&&U.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Fn(process.cwd()),Un(process.cwd())]));m={refs:K,recipes:X}}else m={refs:k,recipes:U};this.referencesCache.set(g,m)}let T=io({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);T.cards.length>0&&(Zs=ro(T.cards,500*4)),T.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${T.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Vs=ge||Ve?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),er,vt=ge?null:Li(e.message);if(vt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:vt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${vt.lookbackDays}d on this chat (cue-triggered)]`],T=[...g.turns].sort((k,U)=>k.ts.localeCompare(U.ts));for(let k of T){let U=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${U} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),er=m.join(`
174
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${vt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let mc=de?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",tr,nr,sr=!1;In||ne("request-gate");let $e=await Bs;if($e.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),mc==="planner"&&!ge&&!$e.active&&!Ve&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(sr=!0,tr=m.sessionHistory,Ks=m.memoryContext,Js=m.memoryFacts,Vs=m.crossChatContext,nr=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)`)}sr&&F&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),F=void 0)}let An=`${e.agentId}:${w}:${I}`,At=Br(e.message);At&&(At==="default"?(this.activeSouls.delete(An),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(An,At),this.log(`[${e.agentId}] Soul switched to: ${At}`)));let fc=this.activeSouls.get(An),hc=Lr(d.def.workspace,fc),yc=Nr(hc),wc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),bc=Cm(d.def.tier),xc=jm(d.def.richMessages,e.context?.via==="voice"?"voice":w),Sc=d.def.tier==="claude-code"&&(ge||Ze!=="lean"||Ua(It)),rr="";if(d.def.workspace&&!Sc){let g=G(d.def.workspace,"CLAUDE.md");if(ae(g))try{let m=bt(g,"utf-8");rr=`[Project CLAUDE.md]
186
175
  ${m.length>4e3?m.slice(0,4e3)+`
187
176
 
188
- [CLAUDE.md truncated to 4KB]`:m}`}catch{}}let $t=e.context?.runbookPath,An=[];if($t&&ae($t)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],m=0,T=4e3,k=16e3;for(let U of g){if(m>=k)break;let K=G($t,U);if(ae(K))try{let X=bt(K,"utf-8"),Ce=X.length>T?X.slice(0,T)+`
177
+ [CLAUDE.md truncated to 4KB]`:m}`}catch{}}let $t=e.context?.runbookPath,$n=[];if($t&&ae($t)){let g=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],m=0,T=4e3,k=16e3;for(let U of g){if(m>=k)break;let K=G($t,U);if(ae(K))try{let X=bt(K,"utf-8"),Ce=X.length>T?X.slice(0,T)+`
189
178
 
190
- [${U} truncated to ${T} bytes]`:X;An.push(`[Project Runbook \u2014 ${U} from ${$t}]
191
- ${Ce}`),m+=Ce.length}catch{}}}let Sc=An.length>0?An.join(`
179
+ [${U} truncated to ${T} bytes]`:X;$n.push(`[Project Runbook \u2014 ${U} from ${$t}]
180
+ ${Ce}`),m+=Ce.length}catch{}}}let Ic=$n.length>0?$n.join(`
192
181
 
193
- `):"",$n=[c.def.systemPrompt||"",wc,bc,rr,Sc,hc||"",yc||""].filter(g=>g.trim().length>0).join(`
182
+ `):"",Cn=[d.def.systemPrompt||"",bc,xc,rr,Ic,yc||"",wc||""].filter(g=>g.trim().length>0).join(`
194
183
 
195
- `)||void 0,Ct={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:Tn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ve||Xd(w,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:de?void 0:dc||void 0,procedureContext:[Xs,js].filter(Boolean).join(`
184
+ `)||void 0,Ct={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:Tn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ve||Yd(w,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:de?void 0:cc||void 0,procedureContext:[Xs,Ws].filter(Boolean).join(`
196
185
 
197
- `)||void 0,workflowRunContext:ic,references:Zs,skillInjection:zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:tr??kt,memoryContext:Ks||void 0,crossChatContext:Vs||void 0,longMemoryRecall:er||void 0,contextOnDemand:Ve&&!F?Ga(w,I):void 0,wikiContext:lc,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Fs)}catch{return}})(),rotationMemo:gc,ownerDecisions:Qs,eventDigest:F?void 0:Lm(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Eo(w,!F,c.def.richMessages);return g?Fm(c.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(Ct,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Mt=e.model?void 0:_r({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?Tt:null});Mt?.downgraded&&this.log(`[${e.agentId}] ${Mt.reason}`);let or=Rr(c.def.tier,this.config.decisions.routing),ir=Mt?.downgraded?Promise.resolve(Mt.model):!e.model&&or&&(!$e.active||$e.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-MLJJ3R3V.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!F,sessionIdleMs:F?Tt:null,cheapModel:or}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ar=!1;ir.then(()=>{ar=!0});let Rt=$e.active&&$e.preprocess?await St("select-context",()=>rc(Ct),()=>({input:Ct,excluded:[]})):{input:Ct,excluded:[]};Rt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Rt.excluded.join(", ")}`);let _t=qi(Rt.input,de?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Ic=eo(_t,{memory:Js,procedures:Ys,wikiContext:Rt.input.wikiContext}),Cn=(_t?.length??0)+($n?.length??0)+(e.message?.length??0),Pt={history:_t?.length??0,sysPrompt:$n?.length??0,message:e.message?.length??0},dr=Ma(e.agentId,w,I);Ra(dr,Cn,Pt);let cr=_a(dr);cr&&this.log(`[${e.agentId}] ${cr}`),Cn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${Cn} bytes (history=${Pt.history}, sysPrompt=${Pt.sysPrompt}, message=${Pt.message})`),ar||ne("route-model");let ur=await ir,lr=c.def.tier!=="claude-code"?void 0:ge?ja():Ze==="lean"?Ha(c.def.workspace,It,void 0,w):qa(c.def.workspace);Ze==="lean"&&!ge&&!F&&this.log(`[${e.agentId}] session profile for ${w}: ${Ka(Ze,It,w)}`);let gr=c.def.tier==="claude-code"&&!F?qo({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,Tc={...e,systemPromptAppend:$n,...lr?{claudeArgs:lr}:{},...ur?{model:ur}:{}},se,pr=ad({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:c.def.maxExecutionMinutes??20}),kc=B,mr=!1,Mn=!0;B=g=>{if(pr.observe(g),ce&&Mn)for(let m of Ao(g))vo(m.name,m.input)||(Mn=!1);kc?.(g)};try{let g=this.workflowAutoRunner;if(we&&g){let O=we;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${we.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:we.workflowId,workflowRunId:z.runId,workflowMatchConfidence:we.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ae)try{let O=Co(Ae,e.resumedFrom);$o(Ae,{runId:ce,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),mr=!0,b.workflow={runId:ce,workflowId:xo}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${O?.message||O}`)}let m=()=>{if(c.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=c.def.persistentProcess?rt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!F||z,Fe=[ma(pe),$a(pe,void 0,e.model||c.def.model)].find(Me=>Me&&Me.abort);if(Fe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Fe.reason}`);let Me={content:"",error:Fe.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Fe.message}`;for(let $c of M.subscribers)try{$c(M.buffer)}catch{}}return Me}ba();let ue=Ca();return ue&&this.log(`[${e.agentId}] ${ue}`),null},T=Ft(e.agentId,void 0,Bt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return c.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(c.def,e);if(k.route==="local"){let O=m();if(O)return c.errors++,se=O,O}let U=c.def.tier==="claude-code",K=U?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,Ce=U?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},be=()=>{X&&(L(`
198
- `),X=!1)},vc=U?K:K?(O,z)=>{be(),K(O,z)}:void 0,C=await le("agent",async()=>{if(k.route!=="local"){let z=await this.runCloudSession(c.def,e,k,N);if(z)return z;let pe=m();if(pe)return pe}let O=await this.inTaskWorktree(c.def,Tc);return _i(O.def,O.task,this.providers,vc,_t,O.fresh?void 0:F,B,R.signal,Ce)},_m);if(!C.error){let O=Um(c.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([pe,Be])=>`${pe}=${Be}`).join(", ")||"none";C.error=`tool_required_not_called: ${O} (invoked: ${z})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}gr&&Go(gr,{toolUses:q,eventsSeen:v,error:C.error,agentId:e.agentId},O=>this.log(O));let Et=this.interruptedRuns.get(b.id);Et&&(C.content="",C.error=Et,C.errorKind="interrupted");let Rn=Et?void 0:this.stoppedRuns.get(b.id);Rn&&(C.content="",C.error=Rn,C.errorKind="stopped"),se=C;let xe=C.usage?Zr(C.usage):void 0,Ac=C.billedModel||e.model||c.def.model||void 0,Ot=C.costUsd??(C.usage?this.tokenTracker.runCost(C.usage,Ac,c.def.tier):void 0);if(Sn=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-Bs,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Et?!0:void 0,stopped:Rn?!0:void 0,inputTokens:xe?.inputTokens,outputTokens:xe?.outputTokens,cacheReadTokens:xe?.cacheReadTokens,cacheCreateTokens:xe?.cacheCreateTokens,tier2InputTokens:xe?.tier2InputTokens,tier2OutputTokens:xe?.tier2OutputTokens,tier2CacheReadTokens:xe?.tier2CacheReadTokens,tier2CacheCreateTokens:xe?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:$e.arm,numTurns:C.numTurns,costUsd:Ot!==void 0&&Number.isFinite(Ot)&&Ot>0?Ot:void 0,injectedContext:Ic,finalResponse:C.content||void 0,billedModel:C.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let O=C.error?`[error] ${C.error}`:C.content;M.buffer=O;for(let z of M.subscribers)try{z(O)}catch{}}if(C.error)c.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,C.content),cd({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:C.content,taskId:N}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,C.usage,C.contextTokens),C.usage){let ue=C.contextTokens,Me=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(ue??Me)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}let O=qr({channel:w,content:`User: ${e.message}`,responseLength:C.content.length}),z=G(this.wikiHub.getBaseDir(),Ni);O.capture||Bi(z,e.agentId,O,ue=>this.log(ue)),O.capture&&(await Hs(xm),Fi(z,e.agentId,()=>{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
186
+ `)||void 0,workflowRunContext:ac,references:Zs,skillInjection:zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:tr??kt,memoryContext:Ks||void 0,crossChatContext:Vs||void 0,longMemoryRecall:er||void 0,contextOnDemand:Ve&&!F?Ka(w,I):void 0,wikiContext:gc,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Us)}catch{return}})(),rotationMemo:pc,ownerDecisions:Qs,eventDigest:F?void 0:Lm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Do(w,!F,d.def.richMessages);return g?Fm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(Ct,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Mt=e.model?void 0:_r({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?Tt:null});Mt?.downgraded&&this.log(`[${e.agentId}] ${Mt.reason}`);let or=Rr(d.def.tier,this.config.decisions.routing),ir=Mt?.downgraded?Promise.resolve(Mt.model):!e.model&&or&&(!$e.active||$e.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-73DPZ65Q.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!F,sessionIdleMs:F?Tt:null,cheapModel:or}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ar=!1;ir.then(()=>{ar=!0});let Rt=$e.active&&$e.preprocess?await St("select-context",()=>oc(Ct),()=>({input:Ct,excluded:[]})):{input:Ct,excluded:[]};Rt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Rt.excluded.join(", ")}`);let _t=Ki(Rt.input,de?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Tc=eo(_t,{memory:Js,procedures:Ys,wikiContext:Rt.input.wikiContext}),Mn=(_t?.length??0)+(Cn?.length??0)+(e.message?.length??0),Pt={history:_t?.length??0,sysPrompt:Cn?.length??0,message:e.message?.length??0},dr=Ra(e.agentId,w,I);_a(dr,Mn,Pt);let cr=Pa(dr);cr&&this.log(`[${e.agentId}] ${cr}`),Mn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${Mn} bytes (history=${Pt.history}, sysPrompt=${Pt.sysPrompt}, message=${Pt.message})`),ar||ne("route-model");let ur=await ir,lr=d.def.tier!=="claude-code"?void 0:ge?Wa():Ze==="lean"?ja(d.def.workspace,It,void 0,w):Ga(d.def.workspace);Ze==="lean"&&!ge&&!F&&this.log(`[${e.agentId}] session profile for ${w}: ${Ja(Ze,It,w)}`);let gr=d.def.tier==="claude-code"&&!F?Ko({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,kc={...e,systemPromptAppend:Cn,...lr?{claudeArgs:lr}:{},...ur?{model:ur}:{}},se,pr=dd({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),vc=B,mr=!1,Rn=!0;B=g=>{if(pr.observe(g),ce&&Rn)for(let m of Co(g))$o(m.name,m.input)||(Rn=!1);vc?.(g)};try{let g=this.workflowAutoRunner;if(we&&g){let O=we;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${we.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:we.workflowId,workflowRunId:z.runId,workflowMatchConfidence:we.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ae)try{let O=Ro(Ae,e.resumedFrom);Mo(Ae,{runId:ce,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),mr=!0,b.workflow={runId:ce,workflowId:Io}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=d.def.persistentProcess?rt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!F||z,Fe=[fa(pe),Ca(pe,void 0,e.model||d.def.model)].find(Me=>Me&&Me.abort);if(Fe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Fe.reason}`);let Me={content:"",error:Fe.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Fe.message}`;for(let Cc of M.subscribers)try{Cc(M.buffer)}catch{}}return Me}xa();let ue=Ma();return ue&&this.log(`[${e.agentId}] ${ue}`),null},T=Ft(e.agentId,void 0,Bt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return d.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(d.def,e);if(k.route==="local"){let O=m();if(O)return d.errors++,se=O,O}let U=d.def.tier==="claude-code",K=U?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,Ce=U?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},be=()=>{X&&(L(`
187
+ `),X=!1)},Ac=U?K:K?(O,z)=>{be(),K(O,z)}:void 0,C=await le("agent",async()=>{if(k.route!=="local"){let z=await this.runCloudSession(d.def,e,k,N);if(z)return z;let pe=m();if(pe)return pe}let O=await this.inTaskWorktree(d.def,kc);return Ei(O.def,O.task,this.providers,Ac,_t,O.fresh?void 0:F,B,R.signal,Ce)},_m);if(!C.error){let O=Um(d.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([pe,Be])=>`${pe}=${Be}`).join(", ")||"none";C.error=`tool_required_not_called: ${O} (invoked: ${z})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}gr&&Jo(gr,{toolUses:q,eventsSeen:v,error:C.error,agentId:e.agentId},O=>this.log(O));let Et=this.interruptedRuns.get(b.id);Et&&(C.content="",C.error=Et,C.errorKind="interrupted");let _n=Et?void 0:this.stoppedRuns.get(b.id);_n&&(C.content="",C.error=_n,C.errorKind="stopped"),se=C;let xe=C.usage?Zr(C.usage):void 0,$c=C.billedModel||e.model||d.def.model||void 0,Ot=C.costUsd??(C.usage?this.tokenTracker.runCost(C.usage,$c,d.def.tier):void 0);if(Sn=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-Fs,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Et?!0:void 0,stopped:_n?!0:void 0,inputTokens:xe?.inputTokens,outputTokens:xe?.outputTokens,cacheReadTokens:xe?.cacheReadTokens,cacheCreateTokens:xe?.cacheCreateTokens,tier2InputTokens:xe?.tier2InputTokens,tier2OutputTokens:xe?.tier2OutputTokens,tier2CacheReadTokens:xe?.tier2CacheReadTokens,tier2CacheCreateTokens:xe?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:$e.arm,numTurns:C.numTurns,costUsd:Ot!==void 0&&Number.isFinite(Ot)&&Ot>0?Ot:void 0,injectedContext:Tc,finalResponse:C.content||void 0,billedModel:C.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let O=C.error?`[error] ${C.error}`:C.content;M.buffer=O;for(let z of M.subscribers)try{z(O)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,C.content),ud({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:C.content,taskId:N}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,C.usage,C.contextTokens),C.usage){let ue=C.contextTokens,Me=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(ue??Me)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}let O=qr({channel:w,content:`User: ${e.message}`,responseLength:C.content.length}),z=G(this.wikiHub.getBaseDir(),Fi);O.capture||Ui(z,e.agentId,O,ue=>this.log(ue)),O.capture&&(await js(xm),Hi(z,e.agentId,()=>{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
199
188
 
200
- Agent: ${C.content}`,meta:Dm(ee,e.context)})},ue=>this.log(ue)),Jr(e.agentId,e.message,C.content,{channel:w,chatId:I,sender:Tn},this.memoryStore).catch(()=>{}),ra(e.agentId,e.message,C.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||c.def.model,Be=e.context?.channel,Fe=Be&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Be}:${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,pe,Be,Fe),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${D()}`)}return C}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=qt(g.message);return se={content:"",error:Gt(m),errorKind:m.kind},se}finally{if(pr.stop(),mr&&ce&&Ae)try{let g=se?.usage,m=Mo(Ae,ce,{error:se?se.error||void 0:R.signal.aborted?Ne(R.signal).message:"run ended before completion",canceled:Ro(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Mn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Os(se),Ls(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?Mm(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:_o(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||Sm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Tm(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=G(process.cwd(),Ye,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=G(a,l);if(ae(p))try{for(let f of ye(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),x=t-1-A;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of ye(e)){let r=G(e,s),o;try{o=ye(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ye(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(bt(G(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Om){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ye(t)){let i=G(t,o),a;try{a=ye(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{Im(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=ye(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=G(s,i),d;try{d=ye(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(bt(G(a,c),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(bt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Bt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Hn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){Am.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=Vt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,d]of this.taskAborts)d.agentId!==e||d.channel!==t||d.chatId!==s||o!==void 0&&d.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let f=this.messageQueue.pendingCount(i,a,d);V().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Tr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function jm(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(`
201
- `)}export{Yo as a,Zm as b,Vm as c,ef as d,Vo as e,uf as f,ti as g,Gc as h,ni as i,Jt as j,vf as k,Mf as l,Rf as m,Df as n,Vt as o,pu as p,Ci as q,wu as r,bu as s,xu as t,_i as u,tn as v,Ni as w,ph as x,nn as y,qu as z,wh as A,bh as B,Sh as C,rn as D,kh as E,is as F,V as G,ca as H,yl as I,Sl as J,ga as K,Wh as L,pa as M,ya as N,sy as O,ry as P,Ta as Q,oy as R,ka as S,ln as T,my as U,fy as V,pt as W,Og as X,Dg as Y,Lg as Z,Ng as _,Bg as $,ws as aa,fn as ba,Gy as ca,yn as da,hn as ea,wd as fa,ft as ga,bd as ha,Zy as ia,Vy as ja,ew as ka,tw as la,nw as ma,sw as na,rw as oa,hp as pa,_d as qa,Xe as ra,$m as sa,Cm as ta,Kb as ua,Jb as va,Mm as wa,Em as xa,Dm as ya,Lm as za,Bm as Aa,Ps as Ba,Zd as Ca,Vd as Da,Um as Ea,ec as Fa,tc as Ga,jm as Ha};
202
- //# sourceMappingURL=chunk-LCVBPN2T.js.map
189
+ Agent: ${C.content}`,meta:Dm(ee,e.context)})},ue=>this.log(ue)),Jr(e.agentId,e.message,C.content,{channel:w,chatId:I,sender:Tn},this.memoryStore).catch(()=>{}),ia(e.agentId,e.message,C.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Be=e.context?.channel,Fe=Be&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Be}:${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,pe,Be,Fe),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${D()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=qt(g.message);return se={content:"",error:Gt(m),errorKind:m.kind},se}finally{if(pr.stop(),mr&&ce&&Ae)try{let g=se?.usage,m=_o(Ae,ce,{error:se?se.error||void 0:R.signal.aborted?Ne(R.signal).message:"run ended before completion",canceled:Po(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Rn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Ds(se),Ns(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?Mm(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Eo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||Sm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Tm(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=G(process.cwd(),Ye,this.safe(e));if(!ae(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 p=G(a,l);if(ae(p))try{for(let f of ye(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),x=t-1-A;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of ye(e)){let r=G(e,s),o;try{o=ye(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=ye(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(bt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Om){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ye(t)){let i=G(t,o),a;try{a=ye(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Im(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=ye(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=G(s,i),c;try{c=ye(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(bt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(bt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Bt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=jn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){Am.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Vt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}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 p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Tr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}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=p=>{u||(u=!0,d(p))};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:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function jm(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(`
190
+ `)}export{Vo as a,Zm as b,Vm as c,ef as d,ti as e,uf as f,si as g,Kc as h,ri as i,Jt as j,vf as k,Mf as l,Rf as m,Df as n,Vt as o,mu as p,Ri as q,bu as r,xu as s,Su as t,Ei as u,tn as v,Fi as w,ph as x,nn as y,Gu as z,wh as A,bh as B,Sh as C,rn as D,kh as E,as as F,V as G,ua as H,yl as I,Sl as J,pa as K,jh as L,ma as M,wa as N,ny as O,sy as P,ka as Q,ry as R,va as S,ln as T,py as U,my as V,pt as W,Og as X,Dg as Y,Lg as Z,Ng as _,Bg as $,bs as aa,fn as ba,qy as ca,yn as da,hn as ea,bd as fa,ft as ga,xd as ha,Yy as ia,Zy as ja,Vy as ka,ew as la,tw as ma,nw as na,sw as oa,hp as pa,Pd as qa,Xe as ra,$m as sa,Cm as ta,Kb as ua,Jb as va,Mm as wa,Em as xa,Dm as ya,Lm as za,Bm as Aa,Es as Ba,Vd as Ca,ec as Da,Um as Ea,tc as Fa,nc as Ga,jm as Ha};
191
+ //# sourceMappingURL=chunk-3HT5A67F.js.map