agentix-cli 0.225.0 → 0.226.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/{App-WOQYUQUF.js → App-PRA4ELTK.js} +2 -2
  2. package/dist/{ChatApp-VW5HOOTA.js → ChatApp-ZFYU5GL5.js} +2 -2
  3. package/dist/{absorb-eval-2LHNO4GF.js → absorb-eval-TRJJVOJZ.js} +2 -2
  4. package/dist/{adapter-JWGD6DVX.js → adapter-R3ZRSWOT.js} +2 -2
  5. package/dist/{agent-J3UMOPII.js → agent-HSCGRWXM.js} +2 -2
  6. package/dist/{board-dashboard-ZXXRQS64.js → board-dashboard-ZHF34H4B.js} +4 -4
  7. package/dist/{chunk-PFTS5N6F.js → chunk-2CFEXC67.js} +2 -2
  8. package/dist/{chunk-MZKJNM2B.js → chunk-3G3XXCHY.js} +2 -2
  9. package/dist/{chunk-F3MDKK4R.js → chunk-3QJZ5TXT.js} +2 -2
  10. package/dist/{chunk-IWEIHEYQ.js → chunk-4GUFZT5S.js} +84 -84
  11. package/dist/{chunk-IWEIHEYQ.js.map → chunk-4GUFZT5S.js.map} +1 -1
  12. package/dist/{chunk-6SJXK4YI.js → chunk-5DEGAL4M.js} +2 -2
  13. package/dist/{chunk-SK7MIYPL.js → chunk-AU6ABL2P.js} +2 -2
  14. package/dist/{chunk-AN4RDGDN.js → chunk-BEH3UJGT.js} +2 -2
  15. package/dist/{chunk-PS2D57LK.js → chunk-CUNUXJSF.js} +18 -18
  16. package/dist/chunk-CUNUXJSF.js.map +1 -0
  17. package/dist/{chunk-G5USBVZT.js → chunk-DDYGJEH4.js} +2 -2
  18. package/dist/{chunk-ASDEZXRC.js → chunk-DQNMJXEM.js} +2 -2
  19. package/dist/{chunk-BY4N4HGH.js → chunk-FAZMGEPF.js} +2 -2
  20. package/dist/{chunk-UJEJSMUY.js → chunk-FWJHLDAX.js} +2 -2
  21. package/dist/{chunk-ROJ6BZEK.js → chunk-IKSCPOUA.js} +195 -195
  22. package/dist/chunk-IKSCPOUA.js.map +1 -0
  23. package/dist/{chunk-6VYSGHAV.js → chunk-J3PUOD3I.js} +3 -3
  24. package/dist/{chunk-7FIGBBUO.js → chunk-KLWQ4KLG.js} +2 -2
  25. package/dist/{chunk-AQ3N5LWH.js → chunk-L5LKL2N7.js} +2 -2
  26. package/dist/{chunk-VYMLXUWH.js → chunk-LMH4Z5QE.js} +2 -2
  27. package/dist/{chunk-DLOWQJFW.js → chunk-LZBOQ3SA.js} +2 -2
  28. package/dist/{chunk-5N2GPVLB.js → chunk-MRSJOAWK.js} +34 -34
  29. package/dist/{chunk-5N2GPVLB.js.map → chunk-MRSJOAWK.js.map} +1 -1
  30. package/dist/{chunk-TRI4WHEG.js → chunk-N4XPOJMC.js} +2 -2
  31. package/dist/{chunk-T236NZTE.js → chunk-NCADCW3E.js} +2 -2
  32. package/dist/{chunk-OR5OZETS.js → chunk-PVNAUVBQ.js} +2 -2
  33. package/dist/{chunk-A2EXL7MB.js → chunk-S656M5R5.js} +2 -2
  34. package/dist/{chunk-VSDWUHCW.js → chunk-TU6D4I4T.js} +2 -2
  35. package/dist/{chunk-Q4LITWNN.js → chunk-W7XVPLDN.js} +2 -2
  36. package/dist/{chunk-LAQJLHXA.js → chunk-Y7ASJTMM.js} +2 -2
  37. package/dist/{chunk-SGR7G6YB.js → chunk-YCXODM2J.js} +2 -2
  38. package/dist/{chunk-77QBR5QP.js → chunk-YEX3NOLR.js} +2 -2
  39. package/dist/{chunk-HNLPHLER.js → chunk-YGGPPZTW.js} +2 -2
  40. package/dist/{chunk-6HWAJGKK.js → chunk-YM5JAK3F.js} +2 -2
  41. package/dist/{chunk-2XMOQWPV.js → chunk-ZN5SZLO4.js} +2 -2
  42. package/dist/cli.js +1 -1
  43. package/dist/{client-WBAN7SIQ.js → client-CUI3YEXS.js} +2 -2
  44. package/dist/{config-TY2QKNR6.js → config-WZ5O3SCZ.js} +2 -2
  45. package/dist/{config-mutate-VB6NCK6M.js → config-mutate-BX4WUTRK.js} +2 -2
  46. package/dist/{config-mutator-HRNIMXSB.js → config-mutator-2SK2P355.js} +2 -2
  47. package/dist/{contributions-67KUV6CB.js → contributions-AOVWT4GQ.js} +2 -2
  48. package/dist/{doctor-5WZTRVM3.js → doctor-KMKVMWIH.js} +2 -2
  49. package/dist/{follow-up-tool-NU3KH33N.js → follow-up-tool-GOVILMAF.js} +2 -2
  50. package/dist/{hub-4WJAAUKG.js → hub-JLASJLAR.js} +2 -2
  51. package/dist/index.js +1 -1
  52. package/dist/{org-tool-DJL6XFQG.js → org-tool-TZOPMOVD.js} +2 -2
  53. package/dist/{program-2KSXAPE5.js → program-ERNKLXGC.js} +24 -24
  54. package/dist/{promote-ORYKGBHJ.js → promote-JL6T7KS7.js} +2 -2
  55. package/dist/{query-RXUOG4EE.js → query-ZSGNVHAX.js} +2 -2
  56. package/dist/{query-settings-BGWU2AWP.js → query-settings-PPJICZ26.js} +2 -2
  57. package/dist/{registry-DCBPVW67.js → registry-EZBD7QJ3.js} +2 -2
  58. package/dist/{request-planner-QQ7QRGUO.js → request-planner-HF7ZY7HX.js} +2 -2
  59. package/dist/{review-candidates-6GBZP6ND.js → review-candidates-XCEOBHCM.js} +2 -2
  60. package/dist/{routing-4YTBWI2S.js → routing-CVVEL76N.js} +2 -2
  61. package/dist/{schedule-tool-NEDTJ2F3.js → schedule-tool-UMSHKANT.js} +2 -2
  62. package/dist/{scheduler-UNFXNWE7.js → scheduler-L6KEZI43.js} +2 -2
  63. package/dist/{seat-QLNJ4XWT.js → seat-KEBD5OUK.js} +2 -2
  64. package/dist/{select-7COYHI64.js → select-FSKHWU4T.js} +2 -2
  65. package/dist/{set-enabled-J2ETDYZM.js → set-enabled-N2EESOLU.js} +2 -2
  66. package/dist/{sprint-tool-SHJGD4VA.js → sprint-tool-K4EDAGGZ.js} +2 -2
  67. package/dist/{tool-ACXYKM37.js → tool-HZRDVPDJ.js} +2 -2
  68. package/dist/{tool-Z55ODG2D.js → tool-ISMGGPUZ.js} +2 -2
  69. package/dist/{tool-KRAQJFPP.js → tool-MN65SRXS.js} +2 -2
  70. package/dist/tool-T6RJUVPW.js +2 -0
  71. package/dist/{tool-7UHWZYXC.js → tool-V7ZNX6RY.js} +2 -2
  72. package/dist/{wiki-P6LO7NSS.js → wiki-FVOQWOT5.js} +2 -2
  73. package/dist/wiki-enrich-RKTYIZOM.js +2 -0
  74. package/package.json +1 -1
  75. package/dist/chunk-PS2D57LK.js.map +0 -1
  76. package/dist/chunk-ROJ6BZEK.js.map +0 -1
  77. package/dist/tool-D4M7NOMX.js +0 -2
  78. package/dist/wiki-enrich-AHG5LWVU.js +0 -2
  79. /package/dist/{App-WOQYUQUF.js.map → App-PRA4ELTK.js.map} +0 -0
  80. /package/dist/{ChatApp-VW5HOOTA.js.map → ChatApp-ZFYU5GL5.js.map} +0 -0
  81. /package/dist/{absorb-eval-2LHNO4GF.js.map → absorb-eval-TRJJVOJZ.js.map} +0 -0
  82. /package/dist/{adapter-JWGD6DVX.js.map → adapter-R3ZRSWOT.js.map} +0 -0
  83. /package/dist/{agent-J3UMOPII.js.map → agent-HSCGRWXM.js.map} +0 -0
  84. /package/dist/{board-dashboard-ZXXRQS64.js.map → board-dashboard-ZHF34H4B.js.map} +0 -0
  85. /package/dist/{chunk-PFTS5N6F.js.map → chunk-2CFEXC67.js.map} +0 -0
  86. /package/dist/{chunk-MZKJNM2B.js.map → chunk-3G3XXCHY.js.map} +0 -0
  87. /package/dist/{chunk-F3MDKK4R.js.map → chunk-3QJZ5TXT.js.map} +0 -0
  88. /package/dist/{chunk-6SJXK4YI.js.map → chunk-5DEGAL4M.js.map} +0 -0
  89. /package/dist/{chunk-SK7MIYPL.js.map → chunk-AU6ABL2P.js.map} +0 -0
  90. /package/dist/{chunk-AN4RDGDN.js.map → chunk-BEH3UJGT.js.map} +0 -0
  91. /package/dist/{chunk-G5USBVZT.js.map → chunk-DDYGJEH4.js.map} +0 -0
  92. /package/dist/{chunk-ASDEZXRC.js.map → chunk-DQNMJXEM.js.map} +0 -0
  93. /package/dist/{chunk-BY4N4HGH.js.map → chunk-FAZMGEPF.js.map} +0 -0
  94. /package/dist/{chunk-UJEJSMUY.js.map → chunk-FWJHLDAX.js.map} +0 -0
  95. /package/dist/{chunk-6VYSGHAV.js.map → chunk-J3PUOD3I.js.map} +0 -0
  96. /package/dist/{chunk-7FIGBBUO.js.map → chunk-KLWQ4KLG.js.map} +0 -0
  97. /package/dist/{chunk-AQ3N5LWH.js.map → chunk-L5LKL2N7.js.map} +0 -0
  98. /package/dist/{chunk-VYMLXUWH.js.map → chunk-LMH4Z5QE.js.map} +0 -0
  99. /package/dist/{chunk-DLOWQJFW.js.map → chunk-LZBOQ3SA.js.map} +0 -0
  100. /package/dist/{chunk-TRI4WHEG.js.map → chunk-N4XPOJMC.js.map} +0 -0
  101. /package/dist/{chunk-T236NZTE.js.map → chunk-NCADCW3E.js.map} +0 -0
  102. /package/dist/{chunk-OR5OZETS.js.map → chunk-PVNAUVBQ.js.map} +0 -0
  103. /package/dist/{chunk-A2EXL7MB.js.map → chunk-S656M5R5.js.map} +0 -0
  104. /package/dist/{chunk-VSDWUHCW.js.map → chunk-TU6D4I4T.js.map} +0 -0
  105. /package/dist/{chunk-Q4LITWNN.js.map → chunk-W7XVPLDN.js.map} +0 -0
  106. /package/dist/{chunk-LAQJLHXA.js.map → chunk-Y7ASJTMM.js.map} +0 -0
  107. /package/dist/{chunk-SGR7G6YB.js.map → chunk-YCXODM2J.js.map} +0 -0
  108. /package/dist/{chunk-77QBR5QP.js.map → chunk-YEX3NOLR.js.map} +0 -0
  109. /package/dist/{chunk-HNLPHLER.js.map → chunk-YGGPPZTW.js.map} +0 -0
  110. /package/dist/{chunk-6HWAJGKK.js.map → chunk-YM5JAK3F.js.map} +0 -0
  111. /package/dist/{chunk-2XMOQWPV.js.map → chunk-ZN5SZLO4.js.map} +0 -0
  112. /package/dist/{client-WBAN7SIQ.js.map → client-CUI3YEXS.js.map} +0 -0
  113. /package/dist/{config-TY2QKNR6.js.map → config-WZ5O3SCZ.js.map} +0 -0
  114. /package/dist/{config-mutate-VB6NCK6M.js.map → config-mutate-BX4WUTRK.js.map} +0 -0
  115. /package/dist/{config-mutator-HRNIMXSB.js.map → config-mutator-2SK2P355.js.map} +0 -0
  116. /package/dist/{contributions-67KUV6CB.js.map → contributions-AOVWT4GQ.js.map} +0 -0
  117. /package/dist/{doctor-5WZTRVM3.js.map → doctor-KMKVMWIH.js.map} +0 -0
  118. /package/dist/{follow-up-tool-NU3KH33N.js.map → follow-up-tool-GOVILMAF.js.map} +0 -0
  119. /package/dist/{hub-4WJAAUKG.js.map → hub-JLASJLAR.js.map} +0 -0
  120. /package/dist/{org-tool-DJL6XFQG.js.map → org-tool-TZOPMOVD.js.map} +0 -0
  121. /package/dist/{program-2KSXAPE5.js.map → program-ERNKLXGC.js.map} +0 -0
  122. /package/dist/{promote-ORYKGBHJ.js.map → promote-JL6T7KS7.js.map} +0 -0
  123. /package/dist/{query-RXUOG4EE.js.map → query-ZSGNVHAX.js.map} +0 -0
  124. /package/dist/{query-settings-BGWU2AWP.js.map → query-settings-PPJICZ26.js.map} +0 -0
  125. /package/dist/{registry-DCBPVW67.js.map → registry-EZBD7QJ3.js.map} +0 -0
  126. /package/dist/{request-planner-QQ7QRGUO.js.map → request-planner-HF7ZY7HX.js.map} +0 -0
  127. /package/dist/{review-candidates-6GBZP6ND.js.map → review-candidates-XCEOBHCM.js.map} +0 -0
  128. /package/dist/{routing-4YTBWI2S.js.map → routing-CVVEL76N.js.map} +0 -0
  129. /package/dist/{schedule-tool-NEDTJ2F3.js.map → schedule-tool-UMSHKANT.js.map} +0 -0
  130. /package/dist/{scheduler-UNFXNWE7.js.map → scheduler-L6KEZI43.js.map} +0 -0
  131. /package/dist/{seat-QLNJ4XWT.js.map → seat-KEBD5OUK.js.map} +0 -0
  132. /package/dist/{select-7COYHI64.js.map → select-FSKHWU4T.js.map} +0 -0
  133. /package/dist/{set-enabled-J2ETDYZM.js.map → set-enabled-N2EESOLU.js.map} +0 -0
  134. /package/dist/{sprint-tool-SHJGD4VA.js.map → sprint-tool-K4EDAGGZ.js.map} +0 -0
  135. /package/dist/{tool-ACXYKM37.js.map → tool-HZRDVPDJ.js.map} +0 -0
  136. /package/dist/{tool-Z55ODG2D.js.map → tool-ISMGGPUZ.js.map} +0 -0
  137. /package/dist/{tool-KRAQJFPP.js.map → tool-MN65SRXS.js.map} +0 -0
  138. /package/dist/{tool-D4M7NOMX.js.map → tool-T6RJUVPW.js.map} +0 -0
  139. /package/dist/{tool-7UHWZYXC.js.map → tool-V7ZNX6RY.js.map} +0 -0
  140. /package/dist/{wiki-P6LO7NSS.js.map → wiki-FVOQWOT5.js.map} +0 -0
  141. /package/dist/{wiki-enrich-AHG5LWVU.js.map → wiki-enrich-RKTYIZOM.js.map} +0 -0
@@ -1,59 +1,59 @@
1
- import{Aa as mi,Ba as fi,Da as hi,G as ei,Ia as yi,Ka as wi,N as Yt,O as ti,X as Vt,Z as ni,a as _o,b as Eo,d as es,f as $e,i as Qo,j as Xo,ja as si,k as Qt,ka as ri,la as oi,n as Xt,na as ii,oa as ai,pa as di,q as Yo,qa as ci,r as Vo,ta as ui,ua as li,v as Zo,xa as gi,za as pi}from"./chunk-5N2GPVLB.js";import{b as Po}from"./chunk-MEFPXHQJ.js";import{a as rs}from"./chunk-W4YR2RO2.js";import{a as Ro}from"./chunk-IH65GDJR.js";import{a as Oo,b as Do,c as No,e as Bo,g as ss,h as jo,i as dt,l as Fo}from"./chunk-7FIGBBUO.js";import{a as ts,b as Lo}from"./chunk-J3SOEFRE.js";import{a as ns,b as Uo}from"./chunk-SIU6STB2.js";import{e as Ho,i as Wo,j as qo,k as Go}from"./chunk-X5C5W3E4.js";import{d as Ko}from"./chunk-KWWBDLE6.js";import{f as Jo,g as zo}from"./chunk-HVMUYEQP.js";import{h as Mo,i as Co}from"./chunk-BE64IJWM.js";import{a as uo,c as lo}from"./chunk-MYVHVJWZ.js";import{a as go,b as po,c as mo,d as fo,l as wo,q as bo}from"./chunk-74MHOALB.js";import{a as ho,b as yo}from"./chunk-LY4G7PCW.js";import{a as xo,b as To}from"./chunk-DPG6VHPX.js";import{c as So}from"./chunk-BERWTVG2.js";import{a as ko,b as Zn}from"./chunk-A7JSRDJL.js";import{d as Io}from"./chunk-Z5CMA4JN.js";import{b as $o}from"./chunk-OR5OZETS.js";import{g as vo,h as Ao}from"./chunk-77QBR5QP.js";import{c as Hr,d as Wr}from"./chunk-AHWWJ7AF.js";import{b as ro,c as oo,f as io}from"./chunk-VYMLXUWH.js";import{s as no,v as Je,w as so,y as pe,z as zt}from"./chunk-HNLPHLER.js";import{a as be,b as Ae,f as at}from"./chunk-72SZI2UW.js";import{a as Ge,b as Qn}from"./chunk-FCPTN6NF.js";import{d as co}from"./chunk-7IW25T4K.js";import{e as ze,h as ao,i as Le}from"./chunk-QUFIUXMQ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{Ab as Hu,Ba as Kt,Db as Xr,Dc as qu,Ea as zr,Ib as Wu,Ob as Yr,Pb as Jt,Qb as Vr,Rb as it,Sb as Zr,Tb as eo,Zb as to,vb as Qr,yb as Vn}from"./chunk-PS2D57LK.js";import{f as Jr,g as Ke,h as ju}from"./chunk-KEUW6YLL.js";import{j as Yn,r as Fu}from"./chunk-N47Y5ADQ.js";import{a as qr,b as we,c as Gr,d as Kr,e as Xn}from"./chunk-VQRY4IDI.js";var Gu="[agentx:mid-turn",bi="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",xi="Got it, I passed that on to the work in progress.";function en(n,e,t){return`${n}\0${e}\0${t}`}var Ku=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function Ju(n){return!!n&&!Ku.has(n)}function Si(n,e){return!Ju(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Zt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function zu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Gu} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
2
- `)}function vh(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:zu(n)}}):""}zt();at();var os="task-edge";function Ii(n){return{task:Ti(n.message,2e3),agent:n.agent,channel:n.channel??null,continuesExistingSession:n.isFollowUp??!1,...n.agentPrompt?{agentInstructions:Ti(n.agentPrompt,600)}:{}}}var ki={needsEdge:be("This task is harder than a strong everyday model does reliably, and needs the most capable model available.",{true:"It is at the limit of what a strong model gets right: designing or changing the architecture of a system, a root cause that earlier attempts did not find, a subtle concurrency, security or data-loss problem, a long build with many dependent steps and nobody checking in between, a decision that cannot be undone and turns on fine reasoning, or research that must weigh sources that disagree.",false:"It is ordinary work for a strong model: a routine code change or review, a clear bug with a known cause, answering a question, writing a message or a summary, a status report, a lookup, routing or acknowledging something, or a scheduled check."}),subagentsHelp:be("This task would be done faster or better if separate workers did parts of it at the same time.",{true:"It has several parts that do not depend on each other (many files, repositories, issues, sources or items to handle the same way), or it needs a wide search whose raw results the main worker does not need to keep, or it asks for an independent second review of the work.",false:"It is one line of work where each step needs the result of the step before, or it is small: one file, one question, one message, one command."})},Qu={workAsked:Ae({asked:"The message asks outright for something to be done or answered.",implied:"The message describes a problem, a complaint or something that does not work, and asks for nothing. Work to find the cause or fix it is implied.",none:"The message only informs, thanks, agrees or chats. No work is wanted."},"What does the sender of this message want from the agent?"),designChange:be("Fixing the problem this message describes needs a change to how the system is designed, not one local fix.",{true:"The problem comes from how parts of the system work together, shows up in many places or over time, and its cause is not stated, so someone must investigate and design a change.",false:"The cause and the place are clear and one small change fixes it, or the message describes no problem."})};function vi(n){return n?{...ki,...Qu}:ki}function Ai(n){let e=n?.workAsked?.probabilities?.implied;return typeof e=="number"&&Number.isFinite(e)?e:null}function Ti(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}function me(n){return`${n.agentId}:${n.channel}:${n.chatId}`}var ct="CLAUDE_CODE_SUBAGENT_MODEL";function Xu(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})`:n.opts&&(n.opts.subagentModel??null)!==(e.subagentModel??null)?`sub-agent model changed (${n.opts.subagentModel??"default"} -> ${e.subagentModel??"default"})`: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"}},$i=class{handles=new Map;sweeper;handleWorkspace=new Map;unaskedReplyHandler;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,backgroundMaxMs:e.backgroundMaxMs??3*60*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,keepBackground:e.keepBackground,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}setUnaskedReplyHandler(e){this.unaskedReplyHandler=e}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=me(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Xu(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,{onUnaskedReply:a=>this.unaskedReplyHandler?.(a)});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=me(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=me(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}backgroundOpen(e){let t=this.handles.get(me(e));if(!t||t.state()==="dead")return 0;let s=t.snapshot();return Math.max(s.backgroundTasks??0,s.unaskedTurn?1:0)}async kill(e,t="operator"){let s=me(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=me(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,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,a=i>0||!!r.unaskedTurn,d=a&&(this.cfg.keepBackground?.()??!0);if(o>=(d?this.cfg.backgroundMaxMs:this.cfg.staleTimeoutMs)){this.handles.delete(t),this.handleWorkspace.delete(t);let u=a?`stale with background work (idle ${Math.round(o/1e3)}s, ${i} open)`:`stale (idle ${Math.round(o/1e3)}s)`;s.kill(u),this.cfg.log(`[process-registry] killed stale ${t}: ${u}`);continue}if(a)continue;let c=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(c>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(c/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let u=this.handleWorkspace.get(t);if(u){let l=null;try{l=this.cfg.currentWorkspaceHash(s.key,u)}catch(g){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${g?.message||g}`);continue}if(l!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let g=r.claudeMdHash??"unmarked",m=l??"unmarked";s.kill(`claude-md drifted (${g} \u2192 ${m})`),this.cfg.log(`[process-registry] killed drifted ${t} (${g} \u2192 ${m})`)}}}}}};var Yu=.7,Vu=.7,ds=.8,Zu=.7,el="[Implied request] This message describes a problem and does not say what to do. Start your reply with one sentence that states the job as you understand it, then do that job. If it could mean two different jobs, or the work cannot be undone, ask one question first.",tl="[Sub-agents] This job has parts that do not depend on each other. Start sub-agents (the Agent tool, named Task in older Claude Code) for those parts in one message so they run at the same time, give each a complete brief, and check their results yourself before you report.";function Mi(){try{return Je(os)!=="off"}catch{return!1}}function Ci(n,e){if(n==="claude-code"){let t=e?.edgeModels?.[n];return t&&/^(claude-|fable$|opus$|sonnet$)/.test(t)?t:void 0}if(n==="codex-cli"){let t=e?.edgeModels?.[n];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}function nl(n){let e=n?.indexOf("--tools")??-1;if(e<0)return!0;let t=(n[e+1]??"").split(",").map(s=>s.trim());return t.includes("Agent")||t.includes("Task")}async function Ri(n){let e=null,t=null,s=(_,L=null,B=null)=>({upgraded:!1,subagents:!1,needsEdge:L,subagentsHelp:B,...e!==null||t!==null?{impliedWork:!1,impliedP:e,designChange:t}:{},reason:_}),r=n.impliedWork??"off",o=r!=="off";if(ro(n.channel))return s(`${n.channel} requests retain the configured model`);let i;try{i=await pe(os,Ii(n),vi(o),{incumbent:{needsEdge:0,subagentsHelp:0,...o?{workAsked:"asked",designChange:0}:{}},features:{agent:n.agent,channel:n.channel??"unknown"},timeoutMs:1500})}catch{return s("edge seat threw \u2014 keeping the agent's model")}if(!i)return s("edge seat unavailable \u2014 keeping the agent's model");let a=i.answers,d=is(a.needsEdge?.noul),c=is(a.subagentsHelp?.noul),u=n.upgradeAt??Yu,l=n.subagentsAt??Vu;o&&(e=Ai(i.answers),t=is(a.designChange?.noul));let g=e!==null&&e>=ds,m=g&&t!==null&&t>=Zu,h=r==="active",y=d!==null&&d>=u,S=y||h&&m,x=h&&g,C=n.tier==="claude-code"&&c!==null&&c>=l,N=`edge ${tn(d)}, sub-agents ${tn(c)}`+(o?`, implied ${tn(e)}, design ${tn(t)}`:""),w=r==="shadow"&&g?` \u2014 implied work (shadow): would state the job${m&&!y?" and move up":""}`:"";if(i.mode!=="active")return s(`shadow \u2014 would ${S||g&&m?"move up":"keep the model"}${C?" and ask for sub-agents":""}${g?" and state the implied job":""} (${N})`,d,c);let v=S&&n.edgeModel?n.edgeModel:void 0,R=!!v&&v!==n.currentModel;return!v&&!C&&!x?s(`${S?"needs the edge model, but none is configured":"the agent's model is enough"} (${N})${w}`,d,c):{...v?{model:v}:{},upgraded:R,subagents:C,needsEdge:d,subagentsHelp:c,...o?{impliedWork:x,impliedP:e,designChange:t}:{},reason:[R?`${y?"hard task":"implied hard task"} \u2192 ${v} for this job`:"",v&&!R?`${y?"hard task":"implied hard task"}, already on the edge model (${v})`:"",C?"sub-agents advised":"",x?"implied work: the agent states the job":""].filter(Boolean).join(", ")+` (${N})${w}`}}function _i(n,e){return n?.model?n.upgraded?n.model:void 0:e}function Ei(n,e){if(!n)return{};let s=e.tier==="claude-code"&&nl(e.claudeArgs),r=[n.impliedWork?el:"",n.subagents&&s?tl:""].filter(Boolean);return{...n.upgraded&&n.model?{model:n.model}:{},...n.upgraded&&n.model&&s?{subagentModel:n.model}:{},...r.length?{turnNote:r.join(`
3
- `)}:{}}}function is(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function tn(n){return n===null?"-":n.toFixed(2)}zt();at();var nn="tool-set",Pi=["answer","code","full"],Oi={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},sl=.1;function Ni(n){return{task:Di(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Di(n.agentPrompt,600)}:{}}}var Li={bundle:Ae({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 Bi(n,e=sl){let s=n?.bundle?.probabilities;if(!s)return"full";let r=cs(s.answer),o=cs(s.code),i=cs(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Ui(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Oi.answer.includes(t))?"answer":e.every(t=>Oi.code.includes(t))?"code":"full"}function ji(n,e){return Pi.indexOf(n)<Pi.indexOf(e)}function cs(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Di(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Fi=!1;function Hi(n,e){let t=Je(nn);if(t!=="off")return t==="active"&&!Fi&&(Fi=!0,e(`[decisions] seat "${nn}" is set to active, but only shadow is built: it records and changes nothing`)),pe(nn,Ni(n),Li,{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=Bi(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Wi(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Ui(r);so(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}`+(ji(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function rl(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function qi(n,e){let t=rl(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 us(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)`}zt();at();var Gi="session-continuity",Ki={continues:be("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:be("Does the new request refer to something stated earlier in the conversation?")};function Ji(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:ls(n.message,1200),previousRequest:n.previousMessage?ls(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>ls(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function zi(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 ls(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function Qi(n,e){let t=co(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function Gh(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=Qi(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function Kh(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:Qi(n,e).token}var Xi=null;function Jh(n){Xi=n}function sn(n,e){let t;try{t=Xi?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as gn}from"execa";import{spawn as ol}from"node:child_process";import{createHash as il}from"node:crypto";import{createInterface as al}from"node:readline";var Me=class extends Error{},dl=n=>ol("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),gs=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(),al({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)+`
4
- `)}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()}},ps=class{constructor(e=dl,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=il("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[C])=>x.localeCompare(C))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Me("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(([,C])=>!C.connection.busy);if(!x)throw new Me("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new gs(e,this.launchProcess)}}catch{throw new Me("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,g,m=!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),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let 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(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let N=new Promise((w,v)=>{i.failTurn=v,i.notify=(R,_)=>{if(_?.threadId!==u)return;let L=_.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:R.replace("/","."),...L?{item:{...L,type:B[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),R==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=_.delta,e.onDelta?.(_.delta,d)),R==="thread/tokenUsage/updated"){let H=_.tokenUsage.last;g=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}R==="turn/completed"&&(_.turn.status==="completed"?w():v(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return N.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await N,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:g,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Me(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:g,error:x.message,duration:Date.now()-t}}finally{clearTimeout(S),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())}}},Yi=new ps;import{execFile as El}from"child_process";import{StringDecoder as mt}from"string_decoder";import{mkdtempSync as ma,readFileSync as fa,rmSync as ha}from"fs";import{join as un}from"path";import{tmpdir as ya}from"os";function rn(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 on(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function an(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 Be=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 Vi=null;function ut(){return Vi}function ny(n){Vi=n}import{spawn as cl}from"child_process";import{randomUUID as ul}from"crypto";import{existsSync as ll,readFileSync as gl}from"fs";import{resolve as pl}from"path";function ml(n){let e=pl(n,"CLAUDE.md");if(!ll(e))return null;try{let t=gl(e,"utf8");return bo(t)}catch{return null}}var fl=20*60*1e3,hl=5e3,lt=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},gt=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function yl(n,e){return n.AGENTX_AGENT_ID=e.agentId,sn(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var wl=200;function bl(n){return n.type==="result"||n.type==="system"&&n.subtype==="init"}function xl(n,e){return e&&(n[ct]=e),n}var Zi=class{constructor(e={}){this.opts=e}spawn(e,t,s){return new ms(e,t,this.opts,s)}},ms=class{constructor(e,t,s,r={}){this.key=e;this.opts=t;this.factoryOpts=s;this.hooks=r;let o=s.binary??"claude",i=this.buildArgs(t),a=this.log=s.log??(()=>{});this.child=cl(o,i,{cwd:t.workspace,env:Le(xl(yl({...process.env},e),t.subagentModel),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:ml(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",d=>this.onStdout(d)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",d=>a(`[claude pid=${this.snap.pid}] stderr: ${d.trim()}`)),this.child.on("exit",d=>{this.exited=!0,this.exitCode=d,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${d}`};let c=this.waiters.splice(0);for(let u of c)u(null)}),this.child.on("error",d=>{a(`[claude pid=${this.snap.pid}] spawn error: ${d.message}`),this.killReason=`spawn-error: ${d.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new Be;passedOn=new WeakSet;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=ul(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
1
+ import{Aa as mi,Ba as fi,Da as hi,G as ei,Ia as yi,Ka as wi,N as Vt,O as ti,X as Zt,Z as ni,a as _o,b as Eo,d as ts,f as $e,i as Qo,j as Xo,ja as si,k as Xt,ka as ri,la as oi,n as Yt,na as ii,oa as ai,pa as di,q as Yo,qa as ci,r as Vo,ta as ui,ua as li,v as Zo,xa as gi,za as pi}from"./chunk-MRSJOAWK.js";import{b as Po}from"./chunk-MEFPXHQJ.js";import{a as os}from"./chunk-W4YR2RO2.js";import{a as Ro}from"./chunk-IH65GDJR.js";import{a as Oo,b as Do,c as No,e as Bo,g as rs,h as Uo,i as dt,l as Fo}from"./chunk-KLWQ4KLG.js";import{a as ns,b as Lo}from"./chunk-J3SOEFRE.js";import{a as ss,b as jo}from"./chunk-SIU6STB2.js";import{e as Ho,i as Wo,j as qo,k as Go}from"./chunk-X5C5W3E4.js";import{d as Ko}from"./chunk-KWWBDLE6.js";import{f as Jo,g as zo}from"./chunk-HVMUYEQP.js";import{h as Mo,i as Co}from"./chunk-BE64IJWM.js";import{a as uo,c as lo}from"./chunk-MYVHVJWZ.js";import{a as go,b as po,c as mo,d as fo,l as wo,q as bo}from"./chunk-74MHOALB.js";import{a as ho,b as yo}from"./chunk-LY4G7PCW.js";import{a as xo,b as To}from"./chunk-DPG6VHPX.js";import{c as So}from"./chunk-BERWTVG2.js";import{a as ko,b as es}from"./chunk-A7JSRDJL.js";import{d as Io}from"./chunk-Z5CMA4JN.js";import{b as $o}from"./chunk-PVNAUVBQ.js";import{g as vo,h as Ao}from"./chunk-YEX3NOLR.js";import{c as Hr,d as Wr}from"./chunk-AHWWJ7AF.js";import{b as ro,c as oo,f as io}from"./chunk-LMH4Z5QE.js";import{s as no,v as Je,w as so,y as pe,z as Qt}from"./chunk-YGGPPZTW.js";import{a as be,b as Ae,f as at}from"./chunk-72SZI2UW.js";import{a as Ge,b as Xn}from"./chunk-FCPTN6NF.js";import{d as co}from"./chunk-7IW25T4K.js";import{e as ze,h as ao,i as Le}from"./chunk-QUFIUXMQ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{Ab as Hu,Ba as Jt,Db as Xr,Dc as qu,Ea as zr,Ib as Wu,Ob as Yr,Pb as zt,Qb as Vr,Rb as it,Sb as Zr,Tb as eo,Zb as to,vb as Qr,yb as Zn}from"./chunk-CUNUXJSF.js";import{f as Jr,g as Ke,h as Uu}from"./chunk-KEUW6YLL.js";import{j as Vn,r as Fu}from"./chunk-N47Y5ADQ.js";import{a as qr,b as we,c as Gr,d as Kr,e as Yn}from"./chunk-VQRY4IDI.js";var Gu="[agentx:mid-turn",bi="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",xi="Got it, I passed that on to the work in progress.";function tn(n,e,t){return`${n}\0${e}\0${t}`}var Ku=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function Ju(n){return!!n&&!Ku.has(n)}function Si(n,e){return!Ju(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var en=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function zu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Gu} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
2
+ `)}function vh(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:zu(n)}}):""}Qt();at();var is="task-edge";function Ii(n){return{task:Ti(n.message,2e3),agent:n.agent,channel:n.channel??null,continuesExistingSession:n.isFollowUp??!1,...n.agentPrompt?{agentInstructions:Ti(n.agentPrompt,600)}:{}}}var ki={needsEdge:be("This task is harder than a strong everyday model does reliably, and needs the most capable model available.",{true:"It is at the limit of what a strong model gets right: designing or changing the architecture of a system, a root cause that earlier attempts did not find, a subtle concurrency, security or data-loss problem, a long build with many dependent steps and nobody checking in between, a decision that cannot be undone and turns on fine reasoning, or research that must weigh sources that disagree.",false:"It is ordinary work for a strong model: a routine code change or review, a clear bug with a known cause, answering a question, writing a message or a summary, a status report, a lookup, routing or acknowledging something, or a scheduled check."}),subagentsHelp:be("This task would be done faster or better if separate workers did parts of it at the same time.",{true:"It has several parts that do not depend on each other (many files, repositories, issues, sources or items to handle the same way), or it needs a wide search whose raw results the main worker does not need to keep, or it asks for an independent second review of the work.",false:"It is one line of work where each step needs the result of the step before, or it is small: one file, one question, one message, one command."})},Qu={workAsked:Ae({asked:"The message asks outright for something to be done or answered.",implied:"The message describes a problem, a complaint or something that does not work, and asks for nothing. Work to find the cause or fix it is implied.",none:"The message only informs, thanks, agrees or chats. No work is wanted."},"What does the sender of this message want from the agent?"),designChange:be("Fixing the problem this message describes needs a change to how the system is designed, not one local fix.",{true:"The problem comes from how parts of the system work together, shows up in many places or over time, and its cause is not stated, so someone must investigate and design a change.",false:"The cause and the place are clear and one small change fixes it, or the message describes no problem."})};function vi(n){return n?{...ki,...Qu}:ki}function Ai(n){let e=n?.workAsked?.probabilities?.implied;return typeof e=="number"&&Number.isFinite(e)?e:null}function Ti(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}function me(n){return`${n.agentId}:${n.channel}:${n.chatId}`}var ct="CLAUDE_CODE_SUBAGENT_MODEL";function Xu(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})`:n.opts&&(n.opts.subagentModel??null)!==(e.subagentModel??null)?`sub-agent model changed (${n.opts.subagentModel??"default"} -> ${e.subagentModel??"default"})`: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"}},$i=class{handles=new Map;sweeper;handleWorkspace=new Map;unaskedReplyHandler;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,backgroundMaxMs:e.backgroundMaxMs??3*60*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,keepBackground:e.keepBackground,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}setUnaskedReplyHandler(e){this.unaskedReplyHandler=e}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=me(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Xu(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,{onUnaskedReply:a=>this.unaskedReplyHandler?.(a)});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=me(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=me(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}backgroundOpen(e){let t=this.handles.get(me(e));if(!t||t.state()==="dead")return 0;let s=t.snapshot();return Math.max(s.backgroundTasks??0,s.unaskedTurn?1:0)}async kill(e,t="operator"){let s=me(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=me(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,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,a=i>0||!!r.unaskedTurn,d=a&&(this.cfg.keepBackground?.()??!0);if(o>=(d?this.cfg.backgroundMaxMs:this.cfg.staleTimeoutMs)){this.handles.delete(t),this.handleWorkspace.delete(t);let u=a?`stale with background work (idle ${Math.round(o/1e3)}s, ${i} open)`:`stale (idle ${Math.round(o/1e3)}s)`;s.kill(u),this.cfg.log(`[process-registry] killed stale ${t}: ${u}`);continue}if(a)continue;let c=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(c>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(c/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let u=this.handleWorkspace.get(t);if(u){let l=null;try{l=this.cfg.currentWorkspaceHash(s.key,u)}catch(g){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${g?.message||g}`);continue}if(l!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let g=r.claudeMdHash??"unmarked",m=l??"unmarked";s.kill(`claude-md drifted (${g} \u2192 ${m})`),this.cfg.log(`[process-registry] killed drifted ${t} (${g} \u2192 ${m})`)}}}}}};var Yu=.7,Vu=.7,cs=.8,Zu=.7,el="[Implied request] This message describes a problem and does not say what to do. Start your reply with one sentence that states the job as you understand it, then do that job. If it could mean two different jobs, or the work cannot be undone, ask one question first.",tl="[Sub-agents] This job has parts that do not depend on each other. Start sub-agents (the Agent tool, named Task in older Claude Code) for those parts in one message so they run at the same time, give each a complete brief, and check their results yourself before you report.";function Mi(){try{return Je(is)!=="off"}catch{return!1}}function Ci(n,e){if(n==="claude-code"){let t=e?.edgeModels?.[n];return t&&/^(claude-|fable$|opus$|sonnet$)/.test(t)?t:void 0}if(n==="codex-cli"){let t=e?.edgeModels?.[n];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}function nl(n){let e=n?.indexOf("--tools")??-1;if(e<0)return!0;let t=(n[e+1]??"").split(",").map(s=>s.trim());return t.includes("Agent")||t.includes("Task")}async function Ri(n){let e=null,t=null,s=(_,L=null,B=null)=>({upgraded:!1,subagents:!1,needsEdge:L,subagentsHelp:B,...e!==null||t!==null?{impliedWork:!1,impliedP:e,designChange:t}:{},reason:_}),r=n.impliedWork??"off",o=r!=="off";if(ro(n.channel))return s(`${n.channel} requests retain the configured model`);let i;try{i=await pe(is,Ii(n),vi(o),{incumbent:{needsEdge:0,subagentsHelp:0,...o?{workAsked:"asked",designChange:0}:{}},features:{agent:n.agent,channel:n.channel??"unknown"},timeoutMs:1500})}catch{return s("edge seat threw \u2014 keeping the agent's model")}if(!i)return s("edge seat unavailable \u2014 keeping the agent's model");let a=i.answers,d=as(a.needsEdge?.noul),c=as(a.subagentsHelp?.noul),u=n.upgradeAt??Yu,l=n.subagentsAt??Vu;o&&(e=Ai(i.answers),t=as(a.designChange?.noul));let g=e!==null&&e>=cs,m=g&&t!==null&&t>=Zu,h=r==="active",y=d!==null&&d>=u,S=y||h&&m,x=h&&g,C=n.tier==="claude-code"&&c!==null&&c>=l,N=`edge ${nn(d)}, sub-agents ${nn(c)}`+(o?`, implied ${nn(e)}, design ${nn(t)}`:""),w=r==="shadow"&&g?` \u2014 implied work (shadow): would state the job${m&&!y?" and move up":""}`:"";if(i.mode!=="active")return s(`shadow \u2014 would ${S||g&&m?"move up":"keep the model"}${C?" and ask for sub-agents":""}${g?" and state the implied job":""} (${N})`,d,c);let v=S&&n.edgeModel?n.edgeModel:void 0,R=!!v&&v!==n.currentModel;return!v&&!C&&!x?s(`${S?"needs the edge model, but none is configured":"the agent's model is enough"} (${N})${w}`,d,c):{...v?{model:v}:{},upgraded:R,subagents:C,needsEdge:d,subagentsHelp:c,...o?{impliedWork:x,impliedP:e,designChange:t}:{},reason:[R?`${y?"hard task":"implied hard task"} \u2192 ${v} for this job`:"",v&&!R?`${y?"hard task":"implied hard task"}, already on the edge model (${v})`:"",C?"sub-agents advised":"",x?"implied work: the agent states the job":""].filter(Boolean).join(", ")+` (${N})${w}`}}function _i(n,e){return n?.model?n.upgraded?n.model:void 0:e}function Ei(n,e){if(!n)return{};let s=e.tier==="claude-code"&&nl(e.claudeArgs),r=[n.impliedWork?el:"",n.subagents&&s?tl:""].filter(Boolean);return{...n.upgraded&&n.model?{model:n.model}:{},...n.upgraded&&n.model&&s?{subagentModel:n.model}:{},...r.length?{turnNote:r.join(`
3
+ `)}:{}}}function as(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function nn(n){return n===null?"-":n.toFixed(2)}Qt();at();var sn="tool-set",Pi=["answer","code","full"],Oi={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},sl=.1;function Ni(n){return{task:Di(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Di(n.agentPrompt,600)}:{}}}var Li={bundle:Ae({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 Bi(n,e=sl){let s=n?.bundle?.probabilities;if(!s)return"full";let r=us(s.answer),o=us(s.code),i=us(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function ji(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Oi.answer.includes(t))?"answer":e.every(t=>Oi.code.includes(t))?"code":"full"}function Ui(n,e){return Pi.indexOf(n)<Pi.indexOf(e)}function us(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Di(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Fi=!1;function Hi(n,e){let t=Je(sn);if(t!=="off")return t==="active"&&!Fi&&(Fi=!0,e(`[decisions] seat "${sn}" is set to active, but only shadow is built: it records and changes nothing`)),pe(sn,Ni(n),Li,{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=Bi(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Wi(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=ji(r);so(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}`+(Ui(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function rl(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function qi(n,e){let t=rl(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 ls(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)`}Qt();at();var Gi="session-continuity",Ki={continues:be("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:be("Does the new request refer to something stated earlier in the conversation?")};function Ji(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:gs(n.message,1200),previousRequest:n.previousMessage?gs(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>gs(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function zi(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 gs(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function Qi(n,e){let t=co(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function Gh(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=Qi(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function Kh(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:Qi(n,e).token}var Xi=null;function Jh(n){Xi=n}function rn(n,e){let t;try{t=Xi?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as pn}from"execa";import{spawn as ol}from"node:child_process";import{createHash as il}from"node:crypto";import{createInterface as al}from"node:readline";var Me=class extends Error{},dl=n=>ol("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),ps=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(),al({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)+`
4
+ `)}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()}},ms=class{constructor(e=dl,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=il("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[C])=>x.localeCompare(C))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Me("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(([,C])=>!C.connection.busy);if(!x)throw new Me("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new ps(e,this.launchProcess)}}catch{throw new Me("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,g,m=!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),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let 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(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let N=new Promise((w,v)=>{i.failTurn=v,i.notify=(R,_)=>{if(_?.threadId!==u)return;let L=_.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:R.replace("/","."),...L?{item:{...L,type:B[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),R==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=_.delta,e.onDelta?.(_.delta,d)),R==="thread/tokenUsage/updated"){let H=_.tokenUsage.last;g=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}R==="turn/completed"&&(_.turn.status==="completed"?w():v(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return N.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await N,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:g,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Me(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:g,error:x.message,duration:Date.now()-t}}finally{clearTimeout(S),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())}}},Yi=new ms;import{execFile as El}from"child_process";import{StringDecoder as mt}from"string_decoder";import{mkdtempSync as ma,readFileSync as fa,rmSync as ha}from"fs";import{join as ln}from"path";import{tmpdir as ya}from"os";function on(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 an(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function dn(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 Be=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 Vi=null;function ut(){return Vi}function ny(n){Vi=n}import{spawn as cl}from"child_process";import{randomUUID as ul}from"crypto";import{existsSync as ll,readFileSync as gl}from"fs";import{resolve as pl}from"path";function ml(n){let e=pl(n,"CLAUDE.md");if(!ll(e))return null;try{let t=gl(e,"utf8");return bo(t)}catch{return null}}var fl=20*60*1e3,hl=5e3,lt=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},gt=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function yl(n,e){return n.AGENTX_AGENT_ID=e.agentId,rn(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var wl=200;function bl(n){return n.type==="result"||n.type==="system"&&n.subtype==="init"}function xl(n,e){return e&&(n[ct]=e),n}var Zi=class{constructor(e={}){this.opts=e}spawn(e,t,s){return new fs(e,t,this.opts,s)}},fs=class{constructor(e,t,s,r={}){this.key=e;this.opts=t;this.factoryOpts=s;this.hooks=r;let o=s.binary??"claude",i=this.buildArgs(t),a=this.log=s.log??(()=>{});this.child=cl(o,i,{cwd:t.workspace,env:Le(xl(yl({...process.env},e),t.subagentModel),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:ml(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",d=>this.onStdout(d)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",d=>a(`[claude pid=${this.snap.pid}] stderr: ${d.trim()}`)),this.child.on("exit",d=>{this.exited=!0,this.exitCode=d,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${d}`};let c=this.waiters.splice(0);for(let u of c)u(null)}),this.child.on("error",d=>{a(`[claude pid=${this.snap.pid}] spawn error: ${d.message}`),this.killReason=`spawn-error: ${d.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new Be;passedOn=new WeakSet;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=ul(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
5
5
  `);let d=e.deadlineMs??fl,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new lt(d)),l=!1,g=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let h=await this.nextEvent(m);if(h===null&&this.killReason)throw new gt(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,g&&(yield{type:g.type,raw:g});else if(h.type==="system"&&h.subtype==="init")g=h;else if(h.type==="result"){g=null;let y=typeof h.result=="string"?h.result:"",S=this.passUnaskedReply(h)?"passed to its job":"dropped";this.log(`[claude pid=${this.snap.pid}] ${S} 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 m=this.snap.state==="busy";this.snap={...this.snap,...m?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},hl);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(`
6
- `))!==-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.snap.state==="busy"||bl(r))&&(this.pendingEvents.push(r),this.snap.state!=="busy"&&this.pendingEvents.length>wl&&this.pendingEvents.shift())}}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);let s=e.type==="result"&&this.snap.state!=="busy";this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t},s&&this.passUnaskedReply(e)}passUnaskedReply(e){if(this.passedOn.has(e))return!0;let t=this.hooks.onUnaskedReply;if(!t)return!1;this.passedOn.add(e);let s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;try{t({key:this.key,text:typeof e.result=="string"?e.result:"",...s?{sessionId:s}:{},...typeof e.total_cost_usd=="number"?{costUsd:e.total_cost_usd}:{},at:Date.now()})}catch(r){this.log(`[claude pid=${this.snap.pid}] unasked reply handler failed: ${r?.message||r}`)}return!0}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"}}};Xn();Fu();Qn();import{resolve as ea,join as ta}from"path";var Sl=4e3;function dn(n){try{let e=ta(ea(n.root),".agentx","db.sqlite"),t=Yn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ge(),r=n.input.command?n.input.command.slice(0,Sl):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
6
+ `))!==-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.snap.state==="busy"||bl(r))&&(this.pendingEvents.push(r),this.snap.state!=="busy"&&this.pendingEvents.length>wl&&this.pendingEvents.shift())}}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);let s=e.type==="result"&&this.snap.state!=="busy";this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t},s&&this.passUnaskedReply(e)}passUnaskedReply(e){if(this.passedOn.has(e))return!0;let t=this.hooks.onUnaskedReply;if(!t)return!1;this.passedOn.add(e);let s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;try{t({key:this.key,text:typeof e.result=="string"?e.result:"",...s?{sessionId:s}:{},...typeof e.total_cost_usd=="number"?{costUsd:e.total_cost_usd}:{},at:Date.now()})}catch(r){this.log(`[claude pid=${this.snap.pid}] unasked reply handler failed: ${r?.message||r}`)}return!0}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"}}};Yn();Fu();Xn();import{resolve as ea,join as ta}from"path";var Sl=4e3;function cn(n){try{let e=ta(ea(n.root),".agentx","db.sqlite"),t=Vn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ge(),r=n.input.command?n.input.command.slice(0,Sl):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
7
7
  (id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
8
8
  verdict, effective_action, mode, severity, approver, ms)
9
9
  VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
10
10
  @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}
11
- `),null}}function yy(n){let e=ta(ea(n.root),".agentx","db.sqlite"),t=Yn({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)}Xn();var kl=50,Tl=6*60*60*1e3,cn=null,Xe=new Map;function Sy(n){cn=n===null?null:String(n)}function sa(){return cn}function Il(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 ra(n,e,t){if(!we(n))return{args:[]};if(!cn)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Il(cn,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 oa(n,e){return!we(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 vl(n){for(let[e,t]of Xe)n-t.at>Tl&&Xe.delete(e)}function Al(n,e){let t=Date.now();vl(t);let s=Xe.get(n)??{at:t,blocks:[]};s.blocks.length<kl&&s.blocks.push(e),s.at=t,Xe.set(n,s)}function ia(n){if(!n)return[];let e=Xe.get(n);return Xe.delete(n),e?.blocks??[]}function $l(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`[agentx-autonomy] read-only call allowed at autonomy "${n}"`}})}function na(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function ky(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=qr.safeParse(e.level),a=i.success?Gr(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"?$l(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},g={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:u,resolvedTarget:null};return dn({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:g,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Al(e.taskId,l),{stdout:na(`[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:na(`[agentx-autonomy] Guard error (fail-closed): ${i?.message??i}`),blocked:null}}}eo();var Ml=6*60*60*1e3,pt=new Map;function Cl(n){for(let[e,t]of pt)n-t.at>Ml&&pt.delete(e)}function aa(n,e){let t=Date.now();Cl(t),pt.set(n,{at:t,limits:e})}function da(n){pt.delete(n)}function Rl(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 ca(n,e,t){let s=sa();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:Rl(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 ua(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 fs(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function _l(n,e,t){if(n.tools.some(s=>it(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=>it(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function $y(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?pt.get(e.taskId):void 0;if(!r)return{stdout:fs("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=_l(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 dn({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:fs(`[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:fs(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var Pl=5e3;function V(n){let e=rn(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}
12
- `)}return{error:on(e),errorKind:e.kind}}function wa(){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 ln(){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 la(){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 Ce(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let d of r.peers){let c=d.handle?` (mention: ${d.handle})`:"",u=d.role?` \u2014 ${d.role}`:"";o.push(`\u2022 ${d.name}${c}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
11
+ `),null}}function yy(n){let e=ta(ea(n.root),".agentx","db.sqlite"),t=Vn({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)}Yn();var kl=50,Tl=6*60*60*1e3,un=null,Xe=new Map;function Sy(n){un=n===null?null:String(n)}function sa(){return un}function Il(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 ra(n,e,t){if(!we(n))return{args:[]};if(!un)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Il(un,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 oa(n,e){return!we(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 vl(n){for(let[e,t]of Xe)n-t.at>Tl&&Xe.delete(e)}function Al(n,e){let t=Date.now();vl(t);let s=Xe.get(n)??{at:t,blocks:[]};s.blocks.length<kl&&s.blocks.push(e),s.at=t,Xe.set(n,s)}function ia(n){if(!n)return[];let e=Xe.get(n);return Xe.delete(n),e?.blocks??[]}function $l(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`[agentx-autonomy] read-only call allowed at autonomy "${n}"`}})}function na(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function ky(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=qr.safeParse(e.level),a=i.success?Gr(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"?$l(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},g={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:u,resolvedTarget:null};return cn({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:g,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Al(e.taskId,l),{stdout:na(`[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:na(`[agentx-autonomy] Guard error (fail-closed): ${i?.message??i}`),blocked:null}}}eo();var Ml=6*60*60*1e3,pt=new Map;function Cl(n){for(let[e,t]of pt)n-t.at>Ml&&pt.delete(e)}function aa(n,e){let t=Date.now();Cl(t),pt.set(n,{at:t,limits:e})}function da(n){pt.delete(n)}function Rl(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 ca(n,e,t){let s=sa();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:Rl(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 ua(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 hs(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function _l(n,e,t){if(n.tools.some(s=>it(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=>it(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function $y(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?pt.get(e.taskId):void 0;if(!r)return{stdout:hs("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=_l(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 cn({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:hs(`[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:hs(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var Pl=5e3;function V(n){let e=on(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}
12
+ `)}return{error:an(e),errorKind:e.kind}}function wa(){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 gn(){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 la(){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 Ce(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(`
13
13
  `))}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)),e.turnNote&&(s.push(""),s.push(e.turnNote)),s.push(""),s.push(e.message),s.join(`
14
- `)}function ba(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 hs(n,e){return!e||e.trim().length===0?n:`[System]
14
+ `)}function ba(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 ys(n,e){return!e||e.trim().length===0?n:`[System]
15
15
  ${e.trim()}
16
16
 
17
17
  [User]
18
- ${n}`}function Ol(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(hs(e,s)),o}function Dl(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 ga(n){return JSON.stringify(n)}function xa(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${ga(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(ga).join(",")}]`]}function Sa(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...xa()),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(hs(e,r)),a}function pn(n,e){let t=ze(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(":"),ft(t,e)}function ft(n,e){n.AGENTX_AGENT_ID=e.agentId,sn(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);let t=ht(e.context);return n.AGENTX_QUEUE_CHANNEL=t.channel,n.AGENTX_QUEUE_CHAT=t.chatId,n}function ka(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),e.subagentModel&&(n[ct]=e.subagentModel),n}function ht(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function Nl(n,e){let t=pn(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:ho(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 Ll(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function xe(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function ys(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=xe(t.cached_input_tokens,t.cachedInputTokens),r=xe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:xe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:xe(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:xe(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=ys(s,e+1);if(r)return r}}function Ta(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 ws(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=ws(t,e+1);if(s)return s}}}function Bl(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
19
- `))if(i.trim())try{let a=JSON.parse(i);t=ys(a)||t,s=Ta(a)||s,r=ws(a)||r,o=Ia(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Ia(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return pa(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return pa(e)}}}function pa(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 Ul(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 bs(n,e,t,s,r){let o=Ul(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}
20
- `)}function jl(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 Fl(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||an(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 va(n,e,t,s,r){let o=Date.now(),i=Ce(n,e,t),a=$a(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=ba(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(bs(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:g,exitCode:m,killed:h}=await new Promise(x=>{let C=Le(ka(ft(ze(n.workspace),e),e),n.billing),N=!1,w=El("claude",d,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...C,HOME:C.HOME||"/home/"+(C.USER||"user")}},(v,R,_)=>{x({stdout:R||"",stderr:_||"",exitCode:v?v.code??1:0,killed:N})});if(w.stdin?.end(),r){let v=()=>{N=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{w.kill("SIGTERM")}catch{}setTimeout(()=>{try{w.killed||w.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?v():r.addEventListener("abort",v,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&m!==0){let x,C=Date.now()-o;return m===143&&C<u-Pl?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(C/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:C}:(m===143?x=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?x=wa():x=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...V(x),duration:Date.now()-o})}let y=jl(l);if(y)return{content:"",...V(y),duration:Date.now()-o};let S=Fl(l);return{content:S.text,duration:Date.now()-o,claudeSessionId:S.sessionId,usage:S.usage,numTurns:S.numTurns,costUsd:S.costUsd,billedModel:S.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function Aa(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=Ce(n,e,s),c=$a(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let u=ba(n,d,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...c.args]);bs(e.agentId,n,e.model,r,"stream");let l="",g="",m="",h=L=>{let B=g&&!m?`
18
+ ${n}`}function Ol(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(ys(e,s)),o}function Dl(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 ga(n){return JSON.stringify(n)}function xa(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${ga(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(ga).join(",")}]`]}function Sa(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...xa()),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(ys(e,r)),a}function mn(n,e){let t=ze(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(":"),ft(t,e)}function ft(n,e){n.AGENTX_AGENT_ID=e.agentId,rn(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);let t=ht(e.context);return n.AGENTX_QUEUE_CHANNEL=t.channel,n.AGENTX_QUEUE_CHAT=t.chatId,n}function ka(n,e){return e.isolated&&(n.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1"),e.subagentModel&&(n[ct]=e.subagentModel),n}function ht(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function Nl(n,e){let t=mn(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:ho(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 Ll(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function xe(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function ws(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=xe(t.cached_input_tokens,t.cachedInputTokens),r=xe(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens);return{inputTokens:Math.max(0,r-s),outputTokens:xe(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:xe(t.cache_read_input_tokens,t.cacheReadTokens)||s,cacheCreateTokens:xe(t.cache_creation_input_tokens,t.cacheCreateTokens)}}for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=ws(s,e+1);if(r)return r}}function Ta(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 bs(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=bs(t,e+1);if(s)return s}}}function Bl(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
19
+ `))if(i.trim())try{let a=JSON.parse(i);t=ws(a)||t,s=Ta(a)||s,r=bs(a)||r,o=Ia(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function Ia(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return pa(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return pa(e)}}}function pa(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 jl(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 xs(n,e,t,s,r){let o=jl(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}
20
+ `)}function Ul(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 Fl(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||dn(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 va(n,e,t,s,r){let o=Date.now(),i=Ce(n,e,t),a=$a(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let d=ba(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(xs(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:g,exitCode:m,killed:h}=await new Promise(x=>{let C=Le(ka(ft(ze(n.workspace),e),e),n.billing),N=!1,w=El("claude",d,{cwd:e.cwd??n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...C,HOME:C.HOME||"/home/"+(C.USER||"user")}},(v,R,_)=>{x({stdout:R||"",stderr:_||"",exitCode:v?v.code??1:0,killed:N})});if(w.stdin?.end(),r){let v=()=>{N=!0,c=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{w.kill("SIGTERM")}catch{}setTimeout(()=>{try{w.killed||w.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?v():r.addEventListener("abort",v,{once:!0})}});if(h)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!l&&m!==0){let x,C=Date.now()-o;return m===143&&C<u-Pl?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(C/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:C}:(m===143?x=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:m==="ENOENT"||/ENOENT|spawn claude/i.test(g||"")?x=wa():x=g?.trim()||`Claude Code exited with code ${m}`,{content:"",...V(x),duration:Date.now()-o})}let y=Ul(l);if(y)return{content:"",...V(y),duration:Date.now()-o};let S=Fl(l);return{content:S.text,duration:Date.now()-o,claudeSessionId:S.sessionId,usage:S.usage,numTurns:S.numTurns,costUsd:S.costUsd,billedModel:S.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function Aa(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=Ce(n,e,s),c=$a(e);if("error"in c)return{content:"",error:c.error,duration:Date.now()-a};let u=ba(n,d,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...c.args]);xs(e.agentId,n,e.model,r,"stream");let l="",g="",m="",h=L=>{let B=g&&!m?`
21
21
 
22
22
  `:"";m+=L,l=g+(g?`
23
23
 
24
- `:"")+m,t(B+L,l)},y=new Be,S=!1,x,C,N,w,v,R,_;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),B=Le(ka(ft(ze(n.workspace),e),e),n.billing),H=gn("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:B,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},J=new Promise(Q=>{q=Q}),M=!1,A;if(i){let Q=()=>{M=!0,A=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{H.kill("SIGTERM")}catch{}setTimeout(()=>{try{H.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?Q():i.addEventListener("abort",Q,{once:!0})}let k="",U=new mt("utf8");H.stdout&&H.stdout.on("data",Q=>{k+=U.write(Q);let re=k.split(`
25
- `);k=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 ne=D.message.usage,ee=(ne.input_tokens||0)+(ne.cache_read_input_tokens||0)+(ne.cache_creation_input_tokens||0);ee>0&&(w=ee)}if(D.type==="assistant"&&D.message?.content){for(let ne of D.message.content)if(ne.type==="text"&&ne.text){let ee=ne.text.slice(m.length);ee&&h(ee)}}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")_=D.result;else{let ne=(typeof D.result=="string",D.result);if(typeof ne=="string"&&ne.length>m.length){let ee=ne.slice(m.length);ee&&h(ee)}}D.usage&&(C={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=an(D.modelUsage)||x,typeof D.session_id=="string"&&(N=D.session_id),typeof D.num_turns=="number"&&(v=D.num_turns),typeof D.total_cost_usd=="number"&&(R=D.total_cost_usd)}D.type==="result"&&(y.pending===0?q():(S||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
+ `:"")+m,t(B+L,l)},y=new Be,S=!1,x,C,N,w,v,R,_;try{let L=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),B=Le(ka(ft(ze(n.workspace),e),e),n.billing),H=pn("claude",u,{cwd:e.cwd??n.workspace,timeout:L,reject:!1,env:B,extendEnv:!1,buffer:!1,stdin:"ignore"}),q=()=>{},J=new Promise(Q=>{q=Q}),M=!1,A;if(i){let Q=()=>{M=!0,A=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{H.kill("SIGTERM")}catch{}setTimeout(()=>{try{H.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?Q():i.addEventListener("abort",Q,{once:!0})}let k="",j=new mt("utf8");H.stdout&&H.stdout.on("data",Q=>{k+=j.write(Q);let re=k.split(`
25
+ `);k=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 ne=D.message.usage,ee=(ne.input_tokens||0)+(ne.cache_read_input_tokens||0)+(ne.cache_creation_input_tokens||0);ee>0&&(w=ee)}if(D.type==="assistant"&&D.message?.content){for(let ne of D.message.content)if(ne.type==="text"&&ne.text){let ee=ne.text.slice(m.length);ee&&h(ee)}}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")_=D.result;else{let ne=(typeof D.result=="string",D.result);if(typeof ne=="string"&&ne.length>m.length){let ee=ne.slice(m.length);ee&&h(ee)}}D.usage&&(C={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=dn(D.modelUsage)||x,typeof D.session_id=="string"&&(N=D.session_id),typeof D.num_turns=="number"&&(v=D.num_turns),typeof D.total_cost_usd=="number"&&(R=D.total_cost_usd)}D.type==="result"&&(y.pending===0?q():(S||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
26
26
  `),S=!0,m&&(g=l,m=""))),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}
27
27
  `))}catch{oe.trim()&&!oe.startsWith("{")&&h(oe+`
28
- `)}});let W=await zl(H,J),P=U.end();if(P&&(k+=P),M)return{content:"",error:A||"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=wa():oe=Q.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...V(oe),duration:Date.now()-a}}return _?{content:"",...V(_),duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,billedModel:x,claudeSessionId:N}:{content:l,duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,costUsd:R,billedModel:x,claudeSessionId:N}}catch(L){return{content:l||"",...V(L.message),duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,billedModel:x,claudeSessionId:N}}}async function Hl(n,e,t,s){let r=Date.now(),o=Ce(n,e,t),i=ma(un(ya(),"agentx-codex-")),a=un(i,"last-message.txt"),d=Sa(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let c=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await gn("codex",d,{cwd:e.cwd??n.workspace,timeout:c,reject:!1,env:pn(n,e),extendEnv:!1,stdin:"ignore"}),l=Bl(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,h;return m.timedOut?h=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?h=l.apiError:m.signal?h=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?h=ln():h=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...V(h),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let g="";try{g=fa(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,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||"")?ln():c?.message;return{content:"",...V(u||"Codex CLI failed"),duration:Date.now()-r}}finally{ha(i,{recursive:!0,force:!0})}}async function Wl(n,e,t,s,r,o){let i=Date.now(),a=Ce(n,e,s),d=ma(un(ya(),"agentx-codex-")),c=un(d,"last-message.txt"),u=Sa(n,a,!0,e.model,e.systemPromptAppend,c,r),l="",g,m,h,y;try{let S=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),x=gn("codex",u,{cwd:e.cwd??n.workspace,timeout:S,reject:!1,env:pn(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let C="",N="",w=!1,v=new mt("utf8"),R=new mt("utf8"),_=Math.min(S,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,B=()=>{L&&clearTimeout(L),L=setTimeout(()=>{w=!0,x.kill("SIGTERM",{forceKillAfterTimeout:5e3})},_)};B(),x.stderr?.on("data",A=>{B(),N+=R.write(A),N.length>16e3&&(N=N.slice(-16e3))}),x.stdout?.on("data",A=>{B(),C+=v.write(A);let k=C.split(`
29
- `);C=k.pop()||"";for(let U of k)if(U.trim())try{let W=JSON.parse(U);if(o)try{o(W)}catch{}g=ys(W)||g,m=Ta(W)||m,h=ws(W)||h,y=Ia(W)||y;let P=Ll(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+=U+`
30
- `,t(U+`
31
- `,l)}});let H=await x;L&&clearTimeout(L);let q=v.end();q&&(C+=q);let J=R.end();if(J&&(N+=J),H.exitCode!==0&&!l||y){let A=N||(typeof H.stderr=="string"?H.stderr:""),k=H,U;return w?U=`Codex CLI produced no output for ${Math.round(_/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:k.timedOut?U=`Codex CLI timed out after ${Math.round(S/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?U=y:k.signal?U=A.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+A)?U=ln():U=A.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...V(U),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}let M="";try{M=fa(c,"utf8").trim()}catch{}if(M&&M!==l){let A=M.startsWith(l)?M.slice(l.length):M;l=M,A&&t(A,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}catch(S){let x=/ENOENT|spawn codex/i.test(S?.message||"")?ln():S?.message;return{content:l,...V(x||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}finally{ha(d,{recursive:!0,force:!0})}}async function ql(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=Ce(n,e,s),u=Ol(n,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",g,m=e.freshSession?void 0:r,h,y,S=!0,x;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),N=Nl(n,e);if(n.persistentProcess)try{y=await lo.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:N,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",y.url),N=y.env,o?.({type:"opencode.ready",reused:y.reused,startupMs:Date.now()-d})}catch(A){if(!(A instanceof uo))throw A;A.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:A.message})}if(i?.aborted)throw new Error("task cancelled by operator");let w=gn("opencode",u,{cwd:e.cwd??n.workspace,timeout:C,reject:!1,env:N,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let v=!1,R,_=()=>{y?.invalidate(),v=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{w.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",_,{once:!0}),x=()=>i?.removeEventListener("abort",_),i?.aborted&&_();let L="",B="",H=new mt("utf8"),q=new mt("utf8"),J=A=>{if(A.trim())try{let k=JSON.parse(A);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(m=k.sessionID);let U=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;U&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-d,reused:y?.reused??!1}),l+=U,t?.(U,l));let W=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;W&&a?.(W);let P=k.type==="step_finish"?k.part?.tokens:void 0;P&&(g={inputTokens:xe(P.input),outputTokens:xe(P.output),cacheReadTokens:xe(P.cache?.read),cacheCreateTokens:xe(P.cache?.write)}),h=Dl(k)||h}catch{l+=A+`
28
+ `)}});let W=await zl(H,J),P=j.end();if(P&&(k+=P),M)return{content:"",error:A||"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=wa():oe=Q.trim()||`Claude Code exited with code ${re.exitCode??"unknown"}`,{content:"",...V(oe),duration:Date.now()-a}}return _?{content:"",...V(_),duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,billedModel:x,claudeSessionId:N}:{content:l,duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,costUsd:R,billedModel:x,claudeSessionId:N}}catch(L){return{content:l||"",...V(L.message),duration:Date.now()-a,usage:C,contextTokens:w,numTurns:v,billedModel:x,claudeSessionId:N}}}async function Hl(n,e,t,s){let r=Date.now(),o=Ce(n,e,t),i=ma(ln(ya(),"agentx-codex-")),a=ln(i,"last-message.txt"),d=Sa(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let c=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await pn("codex",d,{cwd:e.cwd??n.workspace,timeout:c,reject:!1,env:mn(n,e),extendEnv:!1,stdin:"ignore"}),l=Bl(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,h;return m.timedOut?h=`Codex CLI timed out after ${Math.round(c/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:l.apiError?h=l.apiError:m.signal?h=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?h=gn():h=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...V(h),duration:Date.now()-r,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||s}}let g="";try{g=fa(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,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||"")?gn():c?.message;return{content:"",...V(u||"Codex CLI failed"),duration:Date.now()-r}}finally{ha(i,{recursive:!0,force:!0})}}async function Wl(n,e,t,s,r,o){let i=Date.now(),a=Ce(n,e,s),d=ma(ln(ya(),"agentx-codex-")),c=ln(d,"last-message.txt"),u=Sa(n,a,!0,e.model,e.systemPromptAppend,c,r),l="",g,m,h,y;try{let S=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),x=pn("codex",u,{cwd:e.cwd??n.workspace,timeout:S,reject:!1,env:mn(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let C="",N="",w=!1,v=new mt("utf8"),R=new mt("utf8"),_=Math.min(S,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),L,B=()=>{L&&clearTimeout(L),L=setTimeout(()=>{w=!0,x.kill("SIGTERM",{forceKillAfterTimeout:5e3})},_)};B(),x.stderr?.on("data",A=>{B(),N+=R.write(A),N.length>16e3&&(N=N.slice(-16e3))}),x.stdout?.on("data",A=>{B(),C+=v.write(A);let k=C.split(`
29
+ `);C=k.pop()||"";for(let j of k)if(j.trim())try{let W=JSON.parse(j);if(o)try{o(W)}catch{}g=ws(W)||g,m=Ta(W)||m,h=bs(W)||h,y=Ia(W)||y;let P=Ll(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+=j+`
30
+ `,t(j+`
31
+ `,l)}});let H=await x;L&&clearTimeout(L);let q=v.end();q&&(C+=q);let J=R.end();if(J&&(N+=J),H.exitCode!==0&&!l||y){let A=N||(typeof H.stderr=="string"?H.stderr:""),k=H,j;return w?j=`Codex CLI produced no output for ${Math.round(_/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:k.timedOut?j=`Codex CLI timed out after ${Math.round(S/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?j=y:k.signal?j=A.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+A)?j=gn():j=A.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...V(j),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}let M="";try{M=fa(c,"utf8").trim()}catch{}if(M&&M!==l){let A=M.startsWith(l)?M.slice(l.length):M;l=M,A&&t(A,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}catch(S){let x=/ENOENT|spawn codex/i.test(S?.message||"")?gn():S?.message;return{content:l,...V(x||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:h||r}}finally{ha(d,{recursive:!0,force:!0})}}async function ql(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=Ce(n,e,s),u=Ol(n,c,e.model,e.systemPromptAppend,e.freshSession?void 0:r),l="",g,m=e.freshSession?void 0:r,h,y,S=!0,x;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),N=Nl(n,e);if(n.persistentProcess)try{y=await lo.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:N,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",y.url),N=y.env,o?.({type:"opencode.ready",reused:y.reused,startupMs:Date.now()-d})}catch(A){if(!(A instanceof uo))throw A;A.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:A.message})}if(i?.aborted)throw new Error("task cancelled by operator");let w=pn("opencode",u,{cwd:e.cwd??n.workspace,timeout:C,reject:!1,env:N,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let v=!1,R,_=()=>{y?.invalidate(),v=!0,R=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{w.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",_,{once:!0}),x=()=>i?.removeEventListener("abort",_),i?.aborted&&_();let L="",B="",H=new mt("utf8"),q=new mt("utf8"),J=A=>{if(A.trim())try{let k=JSON.parse(A);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(m=k.sessionID);let j=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;j&&(l||o?.({type:"opencode.first_output",elapsedMs:Date.now()-d,reused:y?.reused??!1}),l+=j,t?.(j,l));let W=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;W&&a?.(W);let P=k.type==="step_finish"?k.part?.tokens:void 0;P&&(g={inputTokens:xe(P.input),outputTokens:xe(P.output),cacheReadTokens:xe(P.cache?.read),cacheCreateTokens:xe(P.cache?.write)}),h=Dl(k)||h}catch{l+=A+`
32
32
  `,t?.(A+`
33
33
  `,l)}};w.stdout?.on("data",A=>{L+=H.write(A);let k=L.split(`
34
- `);L=k.pop()||"";for(let U of k)J(U)}),w.stderr?.on("data",A=>{B+=q.write(A)});let M=await w;if(i&&i.removeEventListener("abort",_),L+=H.end(),L.trim()&&J(L),B+=q.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(M.exitCode!==0||h){let A=M,k;return A.timedOut?k=`OpenCode timed out after ${Math.round(C/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?k=h:A.code==="ENOENT"||/ENOENT|spawn opencode/i.test((A.shortMessage||"")+" "+B)?k=la():k=B.trim()||`OpenCode exited with code ${A.exitCode??"unknown"}`,{content:"",...V(k),duration:Date.now()-d,usage:g,opencodeSessionId:m}}return S=!1,{content:l.trim(),duration:Date.now()-d,usage:g,billedModel:e.model||n.model,opencodeSessionId:m}}catch(C){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let N=/ENOENT|spawn opencode/i.test(C?.message||"")?la():C?.message;return{content:l,...V(N||"OpenCode failed"),duration:Date.now()-d,usage:g,opencodeSessionId:m}}finally{x?.(),y?.release(S)}}async function Gl(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Ce(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:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Kl(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(S))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let S=n.provider||"claude-code",x=s?`${s}
34
+ `);L=k.pop()||"";for(let j of k)J(j)}),w.stderr?.on("data",A=>{B+=q.write(A)});let M=await w;if(i&&i.removeEventListener("abort",_),L+=H.end(),L.trim()&&J(L),B+=q.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(M.exitCode!==0||h){let A=M,k;return A.timedOut?k=`OpenCode timed out after ${Math.round(C/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?k=h:A.code==="ENOENT"||/ENOENT|spawn opencode/i.test((A.shortMessage||"")+" "+B)?k=la():k=B.trim()||`OpenCode exited with code ${A.exitCode??"unknown"}`,{content:"",...V(k),duration:Date.now()-d,usage:g,opencodeSessionId:m}}return S=!1,{content:l.trim(),duration:Date.now()-d,usage:g,billedModel:e.model||n.model,opencodeSessionId:m}}catch(C){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let N=/ENOENT|spawn opencode/i.test(C?.message||"")?la():C?.message;return{content:l,...V(N||"OpenCode failed"),duration:Date.now()-d,usage:g,opencodeSessionId:m}}finally{x?.(),y?.release(S)}}async function Gl(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Ce(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:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Kl(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(S))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let S=n.provider||"claude-code",x=s?`${s}
35
35
 
36
- ${e.message}`:e.message,C=e.context?.sender,N=typeof C=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(C),w=e.context?.channel==="web-chat"&&N?{userId:C,agentId:e.agentId||"acme-public"}:void 0,v=fo(n),R=Object.keys(v).length>0,_={task:x,cwd:e.cwd??n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?v:void 0,beforeMcpCall:R?(J,M)=>wo(J,M,v,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-J3UMOPII.js"),M="",A,k,U,W;for await(let P of J(_)){if(d)try{d(P)}catch{}if(P.type==="text_delta")M+=P.text,r(P.text,M);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!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}A=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}P.result.tokensUsed!=null&&(A=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!M?g?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${W}`),duration:Date.now()-c}:((k===void 0||U===void 0)&&A&&(k=Math.round(A*.7),U=A-k),{content:M||"Done.",tokensUsed:A,usage:k!==void 0||U!==void 0?{inputTokens:k||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-J3UMOPII.js"),B=await L(_),H=B.inputTokens,q=B.outputTokens;if((H===void 0||q===void 0)&&B.tokensUsed){let J=B.tokensUsed;H=Math.round(J*.7),q=J-H}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(S){return g?y():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Jl=1e3;async function zl(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"}),Jl),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 Ql(n,e,t,s,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let M=a.list().length;g=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,subagentModel:e.subagentModel}),m=a.list().length>M}catch(M){return M instanceof Qe,null}m&&bs(e.agentId,n,e.model,s,"persistent");let h=Ce(n,e,t),y="",S,x,C,N,w,v,R,_="",L="",B=M=>{if(!i||!M)return;let A;if(L&&M.startsWith(L)?A=M.slice(L.length):A=_&&!_.endsWith(`
36
+ ${e.message}`:e.message,C=e.context?.sender,N=typeof C=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(C),w=e.context?.channel==="web-chat"&&N?{userId:C,agentId:e.agentId||"acme-public"}:void 0,v=fo(n),R=Object.keys(v).length>0,_={task:x,cwd:e.cwd??n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?v:void 0,beforeMcpCall:R?(J,M)=>wo(J,M,v,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-HSCGRWXM.js"),M="",A,k,j,W;for await(let P of J(_)){if(d)try{d(P)}catch{}if(P.type==="text_delta")M+=P.text,r(P.text,M);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!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}A=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(j=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}P.result.tokensUsed!=null&&(A=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!M?g?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${W}`),duration:Date.now()-c}:((k===void 0||j===void 0)&&A&&(k=Math.round(A*.7),j=A-k),{content:M||"Done.",tokensUsed:A,usage:k!==void 0||j!==void 0?{inputTokens:k||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-HSCGRWXM.js"),B=await L(_),H=B.inputTokens,q=B.outputTokens;if((H===void 0||q===void 0)&&B.tokensUsed){let J=B.tokensUsed;H=Math.round(J*.7),q=J-H}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(S){return g?y():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Jl=1e3;async function zl(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"}),Jl),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 Ql(n,e,t,s,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let M=a.list().length;g=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,subagentModel:e.subagentModel}),m=a.list().length>M}catch(M){return M instanceof Qe,null}m&&xs(e.agentId,n,e.model,s,"persistent");let h=Ce(n,e,t),y="",S,x,C,N,w,v,R,_="",L="",B=M=>{if(!i||!M)return;let A;if(L&&M.startsWith(L)?A=M.slice(L.length):A=_&&!_.endsWith(`
37
37
  `)?`
38
38
 
39
- ${M}`:M,L=M,!!A){_+=A;try{i(A,_)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let M=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let A of g.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:M})){if(J=!0,r)try{r(A.raw)}catch{}if(A.type==="assistant"){let k=A.raw.message?.content??[];for(let W of k)W.type==="text"&&typeof W.text=="string"?(y=W.text,B(W.text)):W.type==="tool_use"&&(L="");let U=A.raw.message?.usage;if(U){let W=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);W>0&&(N=W)}}if(A.type==="result"){let k=A.raw;if(k.is_error){let U=V(typeof k.result=="string"?k.result:"claude error");S=U.error,x=U.errorKind}else typeof k.result=="string"&&k.result.length>0&&(y=k.result,_||B(k.result));typeof k.session_id=="string"&&(R=k.session_id),k.usage&&(C={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(w=k.num_turns),typeof k.message?.model=="string"?v=k.message.model:typeof k.model=="string"?v=k.model:v=an(k.modelUsage)||v}}}catch(M){if(H)S="task cancelled by operator",x="cancelled";else if(J)if(M instanceof gt)S=`Claude Code was stopped mid-turn (${M.reason}), before its time limit`,x="interrupted";else if(M instanceof lt){let A=V(`Claude Code timed out after ${Math.round(M.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=A.error,x=A.errorKind}else{let A=V(`persistent claude process error: ${M?.message||String(M)}`);S=A.error,x=A.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${M?.message||M}); 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 H&&!S&&(S="task cancelled by operator",x="cancelled"),{content:H?"":y,error:S,errorKind:x,duration:Date.now()-d,usage:C,contextTokens:N,numTurns:w,billedModel:v,claudeSessionId:R}}function $a(n){let e=we(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?ra(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ca(t.args,n.taskId,n.agentId)}function Xl(n){return we(n.autonomy)||!!n.personLimits}async function Yl(n,e,t,s,r,o,i){let a=we(e.autonomy)?e.autonomy:void 0,d=a&&oa(a,n.tier)||e.personLimits&&ua(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?`${Kr(a)}
39
+ ${M}`:M,L=M,!!A){_+=A;try{i(A,_)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let M=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let A of g.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:M})){if(J=!0,r)try{r(A.raw)}catch{}if(A.type==="assistant"){let k=A.raw.message?.content??[];for(let W of k)W.type==="text"&&typeof W.text=="string"?(y=W.text,B(W.text)):W.type==="tool_use"&&(L="");let j=A.raw.message?.usage;if(j){let W=(j.input_tokens||0)+(j.cache_read_input_tokens||0)+(j.cache_creation_input_tokens||0);W>0&&(N=W)}}if(A.type==="result"){let k=A.raw;if(k.is_error){let j=V(typeof k.result=="string"?k.result:"claude error");S=j.error,x=j.errorKind}else typeof k.result=="string"&&k.result.length>0&&(y=k.result,_||B(k.result));typeof k.session_id=="string"&&(R=k.session_id),k.usage&&(C={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(w=k.num_turns),typeof k.message?.model=="string"?v=k.message.model:typeof k.model=="string"?v=k.model:v=dn(k.modelUsage)||v}}}catch(M){if(H)S="task cancelled by operator",x="cancelled";else if(J)if(M instanceof gt)S=`Claude Code was stopped mid-turn (${M.reason}), before its time limit`,x="interrupted";else if(M instanceof lt){let A=V(`Claude Code timed out after ${Math.round(M.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=A.error,x=A.errorKind}else{let A=V(`persistent claude process error: ${M?.message||String(M)}`);S=A.error,x=A.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${M?.message||M}); 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 H&&!S&&(S="task cancelled by operator",x="cancelled"),{content:H?"":y,error:S,errorKind:x,duration:Date.now()-d,usage:C,contextTokens:N,numTurns:w,billedModel:v,claudeSessionId:R}}function $a(n){let e=we(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?ra(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ca(t.args,n.taskId,n.agentId)}function Xl(n){return we(n.autonomy)||!!n.personLimits}async function Yl(n,e,t,s,r,o,i){let a=we(e.autonomy)?e.autonomy:void 0,d=a&&oa(a,n.tier)||e.personLimits&&ua(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?`${Kr(a)}
40
40
 
41
41
  ${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)
42
- `),e.personLimits&&aa(c,e.personLimits);try{let g=t?await Aa(n,u,t,s,r,o,i):await va(n,u,s,r,i);if(!a)return g;let m=ia(c);return{...g,autonomy:a,...m.length?{autonomyBlocks:m}:{}}}finally{e.personLimits&&da(c)}}async function Ma(n,e,t,s,r,o,i,a,d){if(Xl(e))return Yl(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let c=await Ql(n,e,r,o,i,a,s);if(c!==null)return c}return s?Aa(n,e,s,r,o,i,a):va(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let c=await Yi.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:pn(n,e),args:xa(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:hs(Ce(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...c,...c.error?V(c.error):{}}}catch(c){if(!(c instanceof Me))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Wl(n,e,s,r,o,i):Hl(n,e,r,o);case"opencode":return ql(n,e,s,r,o,i,a,d);case"sdk":{let c=n.provider||"claude",u=t[c]?.apiKey;return u?Gl(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 Kl(n,e,l,r,s,{thinking:u?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ye,writeFileSync as Ca,mkdirSync as Vl,existsSync as mn,readdirSync as xs}from"fs";import{resolve as Ve}from"path";var Ss=12e3,yt=30,Zl=720,eg=40,tg=18e4,ng="[Compacted conversation summary",sg=7*864e5,rg=[/\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 og(n){return n?rg.some(e=>e.test(n)):!1}var ig=[{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 _a(n){if(!n)return null;let e=0;for(let t of ig)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Ra(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 Ea(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 Pa(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 ag(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 fn=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ve(e,".agentx/sessions"),mn(this.sessionsDir)||Vl(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zl),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??eg),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??tg),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:yt,maxChars:Ss});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 Ve(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(mn(o))try{let c=JSON.parse(Ye(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(!mn(i))return null;try{return JSON.parse(Ye(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Ra(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);Ra(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)||mn(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??yt),a=Math.max(200,r.maxChars??Ss),d=[],c=0;for(let g=o.messages.length-1;g>=0&&d.length<i;g--){let m=o.messages[g];if(c+=m.content.length,d.push(m),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 g of d){let m=ag(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let h=g.name||(g.role==="user"?"User":"Agent");u.push(`${h}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
43
- `)}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=xs(this.sessionsDir).filter(w=>w.startsWith(`${a}:`)&&w.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$/,g=d.filter(w=>{let v=w.match(l);if(!v)return!1;let R=v[1];return R>=c&&R<=u}),m=[],h=0,y=e.query?.toLowerCase(),S=e.participants?.length?new Set(e.participants):void 0;for(let w of g){let v;try{v=JSON.parse(Ye(Ve(this.sessionsDir,w),"utf-8"))}catch{continue}if(v.agentId===e.agentId&&!(e.channel&&v.channel!==e.channel)&&!(e.chatId&&v.chatId!==e.chatId))for(let R of v.messages)h++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(S&&R.role==="user"&&!S.has(R.name??"")||y&&!R.content.toLowerCase().includes(y)||m.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:v.channel,chatId:v.chatId,day:v.day,sessionFile:w}))}m.sort((w,v)=>v.ts.localeCompare(w.ts));let x=m.slice(0,t),C=x.length>0?x[x.length-1].ts:null,N=m.length>t;return{turns:x,oldestTs:C,hasMore:N,totalScanned:h}}recentByChatId(e){let t=Math.min(Math.max(e.limit??yt,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=xs(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 g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),d=[];for(let l of a){let g;try{g=JSON.parse(Ye(Ve(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<s||d.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let c=new Set,u=[];for(let l of d){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;c.has(g)||(c.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.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!==""&&!og(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=xs(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(Ye(Ve(this.sessionsDir,c),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,h=l.map(y=>` [${y.timestamp.slice(11,16)}] ${y.name||y.role}: ${y.content.slice(0,200)}`);d.push(`From ${m} (${u.channel}):
42
+ `),e.personLimits&&aa(c,e.personLimits);try{let g=t?await Aa(n,u,t,s,r,o,i):await va(n,u,s,r,i);if(!a)return g;let m=ia(c);return{...g,autonomy:a,...m.length?{autonomyBlocks:m}:{}}}finally{e.personLimits&&da(c)}}async function Ma(n,e,t,s,r,o,i,a,d){if(Xl(e))return Yl(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let c=await Ql(n,e,r,o,i,a,s);if(c!==null)return c}return s?Aa(n,e,s,r,o,i,a):va(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let c=await Yi.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:e.cwd??n.workspace,env:mn(n,e),args:xa(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:ys(Ce(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...c,...c.error?V(c.error):{}}}catch(c){if(!(c instanceof Me))throw c;if(i?.({type:"codex.fallback",reason:c.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Wl(n,e,s,r,o,i):Hl(n,e,r,o);case"opencode":return ql(n,e,s,r,o,i,a,d);case"sdk":{let c=n.provider||"claude",u=t[c]?.apiKey;return u?Gl(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 Kl(n,e,l,r,s,{thinking:u?.thinking},d,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ye,writeFileSync as Ca,mkdirSync as Vl,existsSync as fn,readdirSync as Ss}from"fs";import{resolve as Ve}from"path";var ks=12e3,yt=30,Zl=720,eg=40,tg=18e4,ng="[Compacted conversation summary",sg=7*864e5,rg=[/\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 og(n){return n?rg.some(e=>e.test(n)):!1}var ig=[{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 _a(n){if(!n)return null;let e=0;for(let t of ig)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Ra(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 Ea(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 Pa(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 ag(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 hn=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Ve(e,".agentx/sessions"),fn(this.sessionsDir)||Vl(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Zl),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??eg),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??tg),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:yt,maxChars:ks});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 Ve(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(fn(o))try{let c=JSON.parse(Ye(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(!fn(i))return null;try{return JSON.parse(Ye(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Ra(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);Ra(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)||fn(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??yt),a=Math.max(200,r.maxChars??ks),d=[],c=0;for(let g=o.messages.length-1;g>=0&&d.length<i;g--){let m=o.messages[g];if(c+=m.content.length,d.push(m),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 g of d){let m=ag(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let h=g.name||(g.role==="user"?"User":"Agent");u.push(`${h}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
43
+ `)}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=Ss(this.sessionsDir).filter(w=>w.startsWith(`${a}:`)&&w.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$/,g=d.filter(w=>{let v=w.match(l);if(!v)return!1;let R=v[1];return R>=c&&R<=u}),m=[],h=0,y=e.query?.toLowerCase(),S=e.participants?.length?new Set(e.participants):void 0;for(let w of g){let v;try{v=JSON.parse(Ye(Ve(this.sessionsDir,w),"utf-8"))}catch{continue}if(v.agentId===e.agentId&&!(e.channel&&v.channel!==e.channel)&&!(e.chatId&&v.chatId!==e.chatId))for(let R of v.messages)h++,!(!R.timestamp||R.timestamp<o||R.timestamp>=i)&&(S&&R.role==="user"&&!S.has(R.name??"")||y&&!R.content.toLowerCase().includes(y)||m.push({ts:R.timestamp,role:R.role,senderName:R.name??"",content:R.content,channel:v.channel,chatId:v.chatId,day:v.day,sessionFile:w}))}m.sort((w,v)=>v.ts.localeCompare(w.ts));let x=m.slice(0,t),C=x.length>0?x[x.length-1].ts:null,N=m.length>t;return{turns:x,oldestTs:C,hasMore:N,totalScanned:h}}recentByChatId(e){let t=Math.min(Math.max(e.limit??yt,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Ss(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 g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=r:!1}),d=[];for(let l of a){let g;try{g=JSON.parse(Ye(Ve(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<s||d.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let c=new Set,u=[];for(let l of d){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;c.has(g)||(c.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.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!==""&&!og(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Ss(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(Ye(Ve(this.sessionsDir,c),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,h=l.map(y=>` [${y.timestamp.slice(11,16)}] ${y.name||y.role}: ${y.content.slice(0,200)}`);d.push(`From ${m} (${u.channel}):
44
44
  ${h.join(`
45
45
  `)}`)}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(`
46
- `)}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(ng)}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 Ve(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ye(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()},Ca(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>sg?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>yt&&(e.messages=e.messages.slice(-yt));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>Ss&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ne.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);Ca(t,JSON.stringify(e,null,2))}catch{}}};var Oa="_capture-runs.jsonl",dg=1e6;function ks(n,e,t){try{Io(n,e,dg)}catch(s){t(`[wiki-capture] could not record a capture outcome in ${n}: ${String(s?.message??s)}`)}}function Da(n,e,t,s,r=new Date){let o=t.reason??"filtered";s(`[${e}] not captured in the wiki: ${o}`),ks(n,{at:r.toISOString(),agent:e,outcome:"skipped",reason:o},s)}function Na(n,e,t,s,r=()=>new Date){try{t()}catch(o){return s(`[${e}] wiki entry not written: ${String(o?.message??o)}`),ks(n,{at:r().toISOString(),agent:e,outcome:"failed"},s),!1}return ks(n,{at:r().toISOString(),agent:e,outcome:"captured"},s),!0}function ow(n,e){let t={total:0,captured:0,skipped:0,failed:0,skippedBy:{}};for(let s of n.split(`
47
- `)){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 hn=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 cg(n){return n.split(`
48
- `).map(e=>{if(!ko(e))return e;let t=e.match(/^(\s*[-*•]\s*)(.*)$/);return t?`${t[1]}${Zn}${t[2]}`:`${Zn}${e}`}).join(`
46
+ `)}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(ng)}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 Ve(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Ye(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()},Ca(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>sg?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>yt&&(e.messages=e.messages.slice(-yt));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>ks&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ne.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);Ca(t,JSON.stringify(e,null,2))}catch{}}};var Oa="_capture-runs.jsonl",dg=1e6;function Ts(n,e,t){try{Io(n,e,dg)}catch(s){t(`[wiki-capture] could not record a capture outcome in ${n}: ${String(s?.message??s)}`)}}function Da(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 Na(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 ow(n,e){let t={total:0,captured:0,skipped:0,failed:0,skippedBy:{}};for(let s of n.split(`
47
+ `)){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 yn=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 cg(n){return n.split(`
48
+ `).map(e=>{if(!ko(e))return e;let t=e.match(/^(\s*[-*•]\s*)(.*)$/);return t?`${t[1]}${es}${t[2]}`:`${es}${e}`}).join(`
49
49
  `)}var ug={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}},La=4;function Fa(n,e=ug){let t=gg(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*La;for(let i of t){if(!i.content)continue;let a=i.maxTokens*La,d=Ba(i.content,a,i.keep);if(r+d.length>o){let c=o-r;c>100&&s.push(Ba(d,c,i.keep));break}s.push(d),r+=d.length}return s.join(`
50
50
 
51
51
  `)}function Ba(n,e,t="head"){if(n.length<=e)return n;if(t!=="tail")return n.slice(0,e)+"...";let s=`...
52
52
  `,r=n.indexOf(`
53
- `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=ja(n,i);if(!Ua.test(a.slice(0,a.indexOf(`
54
- `)+1||void 0))){let d=u=>n.slice(0,n.length-u.length).match(lg)?.pop(),c=d(a);if(c&&c.length+1<i/2){a=ja(n,i-c.length-1);let u=Ua.test(a.slice(0,a.indexOf(`
53
+ `),o=r>0&&r+1+s.length<e/2?n.slice(0,r+1):"",i=e-o.length-s.length,a=Ua(n,i);if(!ja.test(a.slice(0,a.indexOf(`
54
+ `)+1||void 0))){let d=u=>n.slice(0,n.length-u.length).match(lg)?.pop(),c=d(a);if(c&&c.length+1<i/2){a=Ua(n,i-c.length-1);let u=ja.test(a.slice(0,a.indexOf(`
55
55
  `)+1||void 0))?"":d(a);u&&(a=u+`
56
- `+a)}}return o+s+a}var Ua=/^— \d\d:\d\d —(\n|$)/,lg=/^— \d\d:\d\d —$/gm;function ja(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
56
+ `+a)}}return o+s+a}var ja=/^— \d\d:\d\d —(\n|$)/,lg=/^— \d\d:\d\d —$/gm;function Ua(n,e){let t=n.slice(n.length-e),s=t.indexOf(`
57
57
  `);return s>=0&&s<e/2?t.slice(s+1):t}function gg(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(pg(n,t("channel",200))),s.push(mg(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(`
58
58
  `)[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(`
59
59
  `);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(`
@@ -62,14 +62,14 @@ ${h.join(`
62
62
  `),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:]`,cg(n.rotationMemo.memo)].join(`
63
63
  `),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 pg(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(`
64
64
  `),tags:r,rules:s}}function mg(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(`
65
- `),tags:s}}function fg(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 hg="resumeDelivery";function uw(n){if(!n||n.kind!=="direct"||!n.context||n.context[hg]||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 yg=32e3;function Ha(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=yg?e:null}catch{return null}}function lw(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 Is={enabled:!0,maxContinuations:1};function pw(n){return n?.enabled?n.maxContinuations:0}var wg=2*6e4,bg=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function xg(n,e){if(!n||e!=="timeout")return null;let t=n.match(bg);return t?Number(t[2]):null}function Wa(n){let e=xg(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<wg)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 qa(n,e){return`${n} It was not continued (${e}).`}var Ts=15,Sg=160;function Ga(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,Ts).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,Sg);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>Ts&&s.push(`\u2026and ${e.length-Ts} 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(`
66
- `)}var kg=["done","continue","waiting","blocked"];var Ka=n=>(n??"").toLowerCase().split("@")[0];function vs(n,e){return!!n?.enabled&&n.channels.includes(Ka(e))}var Tg=["a2a","events"];function Ja(n){return Tg.includes(Ka(n))}var Ue=n=>typeof n=="string"?n.trim():"";function hw(n){let e=Ue(n.state);switch(e){case"done":{let t=Ue(n.proof);return t?{state:e,proof:t}:"done needs its proof: a link, an id, or what you checked"}case"continue":{let t=Ue(n.left),s=Ue(n.when);return t?{state:e,left:t,...s?{when:s}:{}}:"continue needs what is left (left)"}case"waiting":{let t=Ue(n.on),s=Ue(n.until);return t?{state:e,on:t,...s?{until:s}:{}}:"waiting needs on whom or what (on)"}case"blocked":{let t=Ue(n.why);return t?{state:e,why:t}:"blocked needs why"}default:return`state must be one of ${kg.join(", ")}`}}var za=/^[\s>`*_•-]*(?:\[job state\][\s`*_]*|(?:job\s+)?state[`*_]*\s*:[\s`*_]*)(done|continue|waiting|blocked)\b[`*_]*\s*(?:[—–:\-]\s*)?(.*)$/i,Ig=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}\S*)?$/;function vg(n){let e=n.replace(/^on\s+/i,"").match(/^(.*?)[,;]?\s+until\s+(.+)$/i),t=(e?e[1]:n.replace(/^on\s+/i,"")).trim();return t?{state:"waiting",on:t,...e?{until:e[2].trim()}:{}}:null}function Ag(n){let e=n.match(/^(.+?)\s*\(([^()]+)\)$/);if(e)return{state:"continue",left:e[1].trim(),when:e[2].trim()};let t=n.lastIndexOf(","),s=t>0?n.slice(t+1).trim().replace(/^(?:at|on|when)\s+/i,""):"";return s&&Ig.test(s)&&Number.isFinite(Date.parse(s))?{state:"continue",left:n.slice(0,t).trim(),when:s}:{state:"continue",left:n}}function wt(n){if(!n)return null;let e=n.trimEnd().split(`
67
- `).slice(-5).reverse();for(let t of e){let s=t.match(za);if(!s)continue;let r=s[1].toLowerCase(),o=s[2].replace(/[\s`*]+$/,"").trim();if(!o)return null;switch(r){case"done":return{state:r,proof:o};case"continue":return Ag(o);case"waiting":return vg(o);case"blocked":return{state:r,why:o}}}return null}function As(n){return n.split(`
65
+ `),tags:s}}function fg(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 hg="resumeDelivery";function uw(n){if(!n||n.kind!=="direct"||!n.context||n.context[hg]||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 yg=32e3;function Ha(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=yg?e:null}catch{return null}}function lw(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 vs={enabled:!0,maxContinuations:1};function pw(n){return n?.enabled?n.maxContinuations:0}var wg=2*6e4,bg=/^(Claude Code|Codex CLI|OpenCode|Orchestrator) timed out after (\d+)m\b/;function xg(n,e){if(!n||e!=="timeout")return null;let t=n.match(bg);return t?Number(t[2]):null}function Wa(n){let e=xg(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<wg)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 qa(n,e){return`${n} It was not continued (${e}).`}var Is=15,Sg=160;function Ga(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,Is).forEach((r,o)=>{let i=(r.inputSummary??"").replace(/\s+/g," ").trim().slice(0,Sg);s.push(`${o+1}. ${r.action??"tool"}${i?`: ${i}`:""}`)}),e.length>Is&&s.push(`\u2026and ${e.length-Is} 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(`
66
+ `)}var kg=["done","continue","waiting","blocked"];var Ka=n=>(n??"").toLowerCase().split("@")[0];function As(n,e){return!!n?.enabled&&n.channels.includes(Ka(e))}var Tg=["a2a","events"];function Ja(n){return Tg.includes(Ka(n))}var je=n=>typeof n=="string"?n.trim():"";function hw(n){let e=je(n.state);switch(e){case"done":{let t=je(n.proof);return t?{state:e,proof:t}:"done needs its proof: a link, an id, or what you checked"}case"continue":{let t=je(n.left),s=je(n.when);return t?{state:e,left:t,...s?{when:s}:{}}:"continue needs what is left (left)"}case"waiting":{let t=je(n.on),s=je(n.until);return t?{state:e,on:t,...s?{until:s}:{}}:"waiting needs on whom or what (on)"}case"blocked":{let t=je(n.why);return t?{state:e,why:t}:"blocked needs why"}default:return`state must be one of ${kg.join(", ")}`}}var za=/^[\s>`*_•-]*(?:\[job state\][\s`*_]*|(?:job\s+)?state[`*_]*\s*:[\s`*_]*)(done|continue|waiting|blocked)\b[`*_]*\s*(?:[—–:\-]\s*)?(.*)$/i,Ig=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}\S*)?$/;function vg(n){let e=n.replace(/^on\s+/i,"").match(/^(.*?)[,;]?\s+until\s+(.+)$/i),t=(e?e[1]:n.replace(/^on\s+/i,"")).trim();return t?{state:"waiting",on:t,...e?{until:e[2].trim()}:{}}:null}function Ag(n){let e=n.match(/^(.+?)\s*\(([^()]+)\)$/);if(e)return{state:"continue",left:e[1].trim(),when:e[2].trim()};let t=n.lastIndexOf(","),s=t>0?n.slice(t+1).trim().replace(/^(?:at|on|when)\s+/i,""):"";return s&&Ig.test(s)&&Number.isFinite(Date.parse(s))?{state:"continue",left:n.slice(0,t).trim(),when:s}:{state:"continue",left:n}}function wt(n){if(!n)return null;let e=n.trimEnd().split(`
67
+ `).slice(-5).reverse();for(let t of e){let s=t.match(za);if(!s)continue;let r=s[1].toLowerCase(),o=s[2].replace(/[\s`*]+$/,"").trim();if(!o)return null;switch(r){case"done":return{state:r,proof:o};case"continue":return Ag(o);case"waiting":return vg(o);case"blocked":return{state:r,why:o}}}return null}function $s(n){return n.split(`
68
68
  `).filter(e=>!za.test(e)).join(`
69
69
  `).trimEnd()}function yw(n){return n?n.trimEnd().split(`
70
70
  `).slice(-5).some(e=>/^\s*\[job stalled\]/i.test(e))?{state:"stalled"}:wt(n):null}function bt(n){switch(n.state){case"done":return`done \u2014 ${n.proof}`;case"continue":return`continue \u2014 ${n.left}${n.when?` (${n.when})`:""}`;case"waiting":return`waiting on ${n.on}${n.until?` until ${n.until}`:""}`;case"blocked":return`blocked \u2014 ${n.why}`}}var Qa=`[Job state] Before you end this run, state the job's state with the agentx_job_state tool, or as your last line: \`State: done \u2014 <proof>\`, \`State: continue \u2014 <what is left, when>\`, \`State: waiting \u2014 <on whom, until when>\` or \`State: blocked \u2014 <why>\`. A schedule's answer of exactly ${Oo} already means done: write it alone.
71
- `,Xa="[Job state] Your run ended without stating the job's state. Reply with one line only, nothing else: `State: done \u2014 <proof>`, `State: continue \u2014 <what is left, when>`, `State: waiting \u2014 <on whom, until when>` or `State: blocked \u2014 <why>`. Do not redo or continue the work in this turn.";function Ya(n){return`[Job stalled] ${n} ended its run without saying whether the work is done, continuing, waiting or blocked, and gave no state when asked. Treat the work as stalled: check on it or hand it again.`}zr();function Va(n){return new Date(n).toISOString().slice(11,16)}function Za(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Va(n)} UTC, running at ${Va(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 yn=class{queues=new Map;defaultMode;wasTaken;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);r.running=!1;let o=r.pending.filter(i=>!(i.midTurnId&&this.wasTaken?.(i.midTurnId)));if(r.pending=[],o.length===0)return[];switch(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(`
72
- `),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 $g=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,Mg=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.-]+`,ed=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,td=new RegExp(String.raw`(?<![\w/.-])((?:${$g}\/)+${Mg})([#!])(\d+)\b`,"g");function wn(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(ed.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${td.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function Cg(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(ed)){let s=wn(t[0]);s&&e.add(s)}for(let t of n.matchAll(td))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function xw(n){let e=n.context&&typeof n.context=="object"?n.context:null;return wn(n.home)??wn(e?.home)}var Rg="[agentx:same-home]";function nd(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`${Rg} 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 sd(n){let e=wn(n.home),t=Cg(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as _g,writeFileSync as rd,appendFileSync as Eg,mkdirSync as Pg,existsSync as od}from"fs";import{resolve as $s}from"path";var id=50,Og="claude-haiku-4-5-20251001",Dg=`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.
71
+ `,Xa="[Job state] Your run ended without stating the job's state. Reply with one line only, nothing else: `State: done \u2014 <proof>`, `State: continue \u2014 <what is left, when>`, `State: waiting \u2014 <on whom, until when>` or `State: blocked \u2014 <why>`. Do not redo or continue the work in this turn.";function Ya(n){return`[Job stalled] ${n} ended its run without saying whether the work is done, continuing, waiting or blocked, and gave no state when asked. Treat the work as stalled: check on it or hand it again.`}zr();function Va(n){return new Date(n).toISOString().slice(11,16)}function Za(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Va(n)} UTC, running at ${Va(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 wn=class{queues=new Map;defaultMode;wasTaken;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);r.running=!1;let o=r.pending.filter(i=>!(i.midTurnId&&this.wasTaken?.(i.midTurnId)));if(r.pending=[],o.length===0)return[];switch(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(`
72
+ `),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 $g=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,Mg=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.-]+`,ed=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,td=new RegExp(String.raw`(?<![\w/.-])((?:${$g}\/)+${Mg})([#!])(\d+)\b`,"g");function bn(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(ed.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${td.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function Cg(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(ed)){let s=bn(t[0]);s&&e.add(s)}for(let t of n.matchAll(td))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function xw(n){let e=n.context&&typeof n.context=="object"?n.context:null;return bn(n.home)??bn(e?.home)}var Rg="[agentx:same-home]";function nd(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`${Rg} 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 sd(n){let e=bn(n.home),t=Cg(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as _g,writeFileSync as rd,appendFileSync as Eg,mkdirSync as Pg,existsSync as od}from"fs";import{resolve as Ms}from"path";var id=50,Og="claude-haiku-4-5-20251001",Dg=`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.
73
73
 
74
74
  Extract patterns like:
75
75
  - "When asked about X, the approach that works is Y"
@@ -85,43 +85,43 @@ SKIP:
85
85
  Output a JSON array:
86
86
  [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
87
87
 
88
- If nothing worth extracting, output: []`,bn=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=$s(e,".agentx/patterns"),od(this.patternsDir)||Pg(this.patternsDir,{recursive:!0})}filePath(e){return $s(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!od(t))return[];try{return _g(t,"utf-8").split(`
88
+ If nothing worth extracting, output: []`,xn=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ms(e,".agentx/patterns"),od(this.patternsDir)||Pg(this.patternsDir,{recursive:!0})}filePath(e){return Ms(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!od(t))return[];try{return _g(t,"utf-8").split(`
89
89
  `).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()};Eg(this.filePath(e),JSON.stringify(s)+`
90
- `)}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=$s(this.patternsDir,`${t}_bm25_cache.json`),a=Wr(o,i),c=Hr(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(`
90
+ `)}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=Ms(this.patternsDir,`${t}_bm25_cache.json`),a=Wr(o,i),c=Hr(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(`
91
91
  `)}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&&rd(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
92
92
  `)+`
93
93
  `)}prune(e){let t=this.getAll(e);t.length<=id||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,id),rd(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
94
94
  `)+`
95
95
  `))}};async function ad(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:Dg},{role:"user",content:`User: ${e.slice(0,500)}
96
96
 
97
- Agent: ${t.slice(0,1e3)}`}],{model:Og,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 Ng}from"events";var Lg=2e4,Cs=class{inner=new Ng;envelopeListeners=new Set;ring=new Fo;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(Bg(e,t))}catch{}return s}publish(e){let t=dt(),s=e.id??jo(),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:ss(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>Lg&&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:ss(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 Bg(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 Ms;function Z(){return Ms||(Ms=new Cs),Ms}Qn();zr();var Ug=/\breq-[0-9A-HJKMNP-TV-Z]{26}\b/,jg=15*6e4,dd=45*6e4,cd=1500,ud="[agentx:same-work",Fg=new Set(["app","telegram","whatsapp","voice","slack","discord","email","sms","ntfy","dashboard","web-chat","tui","admin","test-drive","workflow-editor","guest","public-api"]);function Hg(n){return!!n&&Fg.has(n)}var Wg=new Set(["a2a","cron","workflow","reminder","events","business"]);function ld(n){return!!n&&Wg.has(n)}function gd(n,e){return!n||Hg(e)||n.startsWith(ud)?null:Ug.exec(n)?.[0]??null}var xn=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??jg,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`),Kt({kind:"same_work_waited",agentId:e,ref:t,detail:"the same request reached this agent twice while one run was on it"})),d=!0,await Promise.race([y.done,(this.opts.sleep??Gg)(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 m=this.ended.get(o);return{note:m&&this.now()-m.at<=dd?qg(t,m,this.now()):"",waitedMs:this.now()-i,release:({text:y,ok:S,ran:x=!0})=>{this.holders.get(o)===l&&this.holders.delete(o),x&&this.ended.set(o,{at:this.now(),text:y,ok:S}),this.prune(),c()}}}prune(){let e=this.now()-dd;for(let[t,s]of this.ended)s.at<e&&this.ended.delete(t)}};function qg(n,e,t){let s=Math.max(0,Math.round((t-e.at)/6e4)),r=e.text.length>cd?e.text.slice(0,cd-1)+"\u2026":e.text;return[`${ud} 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(`
98
- `)}function Gg(n){return new Promise(e=>setTimeout(e,n))}var Kg="[agentx:notices",Sn=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),Jg(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 Jg(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[`${Kg} 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(`
99
- `)}Qn();var pd=["manual","notify","auto"];function zg(n){return typeof n=="string"&&pd.includes(n)}var Rs={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Qg=7*24*60*6e4,xt=class{constructor(e={},t){this.store=t;this.opts={...Rs,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-Qg;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:Ge(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:Xg(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 Xg(n,e){return n.length<=e?n:`${n.slice(0,e)}
100
- \u2026[truncated ${n.length-e} chars]`}qu();import{z as Yg}from"zod";var fd=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Vg(n){if(n==null)return{ok:!0,subscriptions:fd};let e=Yg.array(to).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 Zg=15,ep=1500,md=200;function hd(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function tp(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 Uw(n,e,t={}){let s=tp(e,n.cursor),r=s.length?hd(s):n.cursor,o=s.filter(c=>n.subscriptions.some(u=>Ho(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}=np(o,i,t);return{text:a,cursor:r,matched:o.length,shown:d}}function np(n,e,t={}){let s=Math.max(3,t.maxLines??Zg),r=Math.max(200,t.maxChars??ep),o=n.map(a=>sp(`- ${qo(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(`
101
- `);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 sp(n){return n.length<=md?n:`${n.slice(0,md-1)}\u2026`}import{existsSync as rp,mkdirSync as op,readFileSync as ip,renameSync as ap,writeFileSync as dp}from"node:fs";import{homedir as cp}from"node:os";import{dirname as up,join as lp}from"node:path";function gp(n){return{load:()=>rp(n)?JSON.parse(ip(n,"utf-8")):{},save:e=>{op(up(n),{recursive:!0});let t=`${n}.tmp`;dp(t,JSON.stringify(e,null,2),{mode:384}),ap(t,n)}}}function pp(){if(!process.env.VITEST)return gp(process.env.AGENTX_ATTACH_BINDINGS_FILE??lp(cp(),".agentx","attach-bindings.json"))}var _s;function yd(){return _s||(_s=new xt({},pp())),_s}Xn();import{readFileSync as mp}from"fs";import{homedir as fp}from"os";import{join as hp}from"path";var St=null,yp=6e4;function wp(){try{let n=hp(fp(),".claude.json"),e=mp(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function bp(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 xp(n=!1){let e=Date.now();return!n&&St&&e-St.checkedAt<yp||(St=bp(wp(),e)),St}function wd(n){let e=xp();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 Sd={warnRatio:.8},Ze={...Sd},kd=5*60*60*1e3,Td=60*60*1e3,Se=[];function Id(n){Ze={...Sd,...n||{}}}function vd(n){let e=n-kd,t=0;for(;t<Se.length&&Se[t]<e;)t++;t>0&&Se.splice(0,t)}function Ad(n=Date.now()){vd(n),Se.push(n)}var je=new Map,Sp=15*60*1e3,kp=24*60*60*1e3,Os=new Map;function kn(n){return n.resetsAt??n.seenAt+Sp}function Es(n,e,t){n.status!=="rejected"||n.usingOverage||Os.set(n.window,{window:n.window,heldSince:n.seenAt,...n.resetsAt&&{resetsAt:n.resetsAt},liftedAt:e,how:t})}function Zw(n=Date.now()){let e=new Map(Os);for(let t of je.values()){if(t.status!=="rejected"||t.usingOverage)continue;let s=kn(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<kp).sort((t,s)=>s.liftedAt-t.liftedAt)}var Ps=null;function Ds(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;Ps={...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 eb(){return Ps?{...Ps}:null}function $d(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function Tp(n){let e=$d(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ip(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=Tp(s.resetsAt??s.resets_at),a=$d(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 Md(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Cd(n,e){let t=Md(n);return!t||!e||e.toLowerCase().includes(t)}function Ns(n,e=Date.now(),t){let s=Ip(n,e);if(!s)return null;if(s.status!=="rejected"){for(let[r,o]of je)if(o.status==="rejected"){if(r===s.window){kn(o)>e&&Es(o,e,"served");continue}(!Md(r)||t&&Cd(r,t))&&(kn(o)>e&&Es(o,e,"served"),je.delete(r))}}else Os.delete(s.window);return je.set(s.window,s),s}function Rd(n=Date.now()){return[...je.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:kn(e)>n)}function vp(n=Date.now(),e){return Rd(n).find(t=>Cd(t.window,e))??null}function tb(n=Date.now()){let e=Rd(n);for(let t of e)Es(t,n,"operator"),je.delete(t.window);return e}function Ap(){return[...je.values()].sort((n,e)=>e.seenAt-n.seenAt)}function bd(n){return typeof n=="number"&&n>0}function _d(n=Date.now()){vd(n);let e=n-Td,t=0;for(let o=Se.length-1;o>=0&&Se[o]>=e;o--)t++;let s=Se.length,r={lastHour:t,last5h:s,maxPerHour:bd(Ze.maxPerHour)?Ze.maxPerHour:void 0,maxPer5h:bd(Ze.maxPer5h)?Ze.maxPer5h:void 0,provider:Ap()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function xd(n,e){let t=Se[Se.length-n];return t===void 0?void 0:t+e}function Ed(n){return n.replace(/_/g," ")}function Pd(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function Od(n,e=Date.now(),t){let s=_d(e);if(n)return null;let r=vp(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Ed(r.window)} window as rejected. Cold dispatches are held until it resets ${Pd(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s,retryAt:r.resetsAt}: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,retryAt:xd(s.maxPerHour,Td)}: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,retryAt:xd(s.maxPer5h,kd)}:null}function Dd(n=Date.now()){let e=_d(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 ${Ed(t.window)} window nearing its limit${r}, resets ${Pd(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 $p,mkdirSync as Mp,readFileSync as Cp,renameSync as Rp,writeFileSync as _p}from"fs";import{dirname as Ep}from"path";var Ls=200,Tn=class{constructor(e=Ls,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($p(e))try{let t=JSON.parse(Cp(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{Mp(Ep(this.file),{recursive:!0});let e=`${this.file}.tmp`;_p(e,JSON.stringify(Object.fromEntries(this.held))),Rp(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var Bs=new Map;function Nd(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function Ld(n,e,t,s=Date.now()){let r=Bs.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},Bs.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 Bd(n){let e=Bs.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 Up,readFileSync as jp}from"fs";import{resolve as Fp}from"path";import{existsSync as Pp,readFileSync as Op,unlinkSync as Dp,writeFileSync as Np}from"fs";import{resolve as jd}from"path";var Ud="_agentxManaged";function In(n=process){let e=n.argv[1]?jd(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 ub(n,e){return!e||n.agentx?n:{...n,agentx:e}}function lb(n,e){let t=jd(n,".mcp.json"),s=Pp(t),r=s?Bp(t):null,o=r!==null&&r[Ud]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return Dp(t),"removed";let a={[Ud]:!0,mcpServers:Lp(e)};return Np(t,JSON.stringify(a,null,2)+`
102
- `),s?"updated":"installed"}function Lp(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=yo(s);e[t]=u?{...c,headers:u}:c}else e[t]=i}return e}function Bp(n){try{return JSON.parse(Op(n,"utf-8"))}catch{return null}}var Hp=["github","a2a","workflow","cron"],Wp=["claude-code","codex-cli"],qp={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},Gp="AGENTX_MCP_TOOLS",Kp=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint","agentx_node","agentx_job_state"],Jp=["agentx_agents","agentx_recent","agentx_wiki_query","agentx_lookup"];function Hd(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 Wd(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=[...Kp,...n.contextOnDemand?Jp:[],...s];return Array.from(new Set(r))}function zp(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[Gp]:e.join(",")}}}function qd(n,e,t){if(!Wp.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(Hp.includes(e)?"lean":"full")}function Gd(n){return{...qp,...n?.lean??{}}}function Kd(n){return n.settingSources.includes("project")}function Qp(n,e,t=In(),s){let r=Jd(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=zp(o.agentx??r.agentx??t,Wd(e,s)),o}function Jd(n){let e=Fp(n,".mcp.json");if(!Up(e))return{};try{let s=JSON.parse(jp(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function zd(n,e,t=In(),s){let r=Qp(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Hd(e,s);return i.length&&o.push("--tools",Xd(i).join(",")),o}function Qd(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Fd="ToolSearch";function Xd(n){return n.includes(Fd)?n:[...n,Fd]}function Yd(n,e=In()){let t=Jd(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function Vd(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), a colleague's or a work item's status (agentx_lookup, before asking them), and this machine, its programs, Claude usage limits and running work (agentx_node: answer from it with its check time, never from memory).`].join(`
103
- `)}function Zd(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=Hd(e,t);r.length&&s.push(`tools=${Xd(r).join("+")}`);let o=Wd(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ae,mkdirSync as sh,readdirSync as ke,readFileSync as Ct,rmSync as rh,writeFileSync as oh}from"fs";import{resolve as G}from"path";import{randomUUID as ih}from"crypto";import{existsSync as He,mkdirSync as Us,readFileSync as Xp,readdirSync as Yp,renameSync as Vp,unlinkSync as Zp,writeFileSync as vn}from"fs";import{resolve as Re,relative as An}from"path";import{z as Y}from"zod";var Fe=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 em(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(`
104
- `)){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 $n(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(`
105
- `)}var kt=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Re(process.cwd(),".agentx/procedures"),Us(this.baseDir,{recursive:!0})}pathFor(e){return Re(this.baseDir,`${e}.md`)}get draftsDir(){return Re(this.baseDir,"_drafts")}draftPathFor(e){return Re(this.draftsDir,`${e}.md`)}parseFile(e){let t=Xp(e,"utf-8"),{meta:s,body:r}=em(t),o=Fe.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:An(this.baseDir,e)}:null}listDir(e){if(!He(e))return[];let t=[];for(let s of Yp(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Re(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 He(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return He(t)?this.parseFile(t):null}add(e,t){let s=Fe.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(He(r))throw new Error(`Procedure already exists: ${s.id}`);return vn(r,$n(s)+`
97
+ Agent: ${t.slice(0,1e3)}`}],{model:Og,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 Ng}from"events";var Lg=2e4,Rs=class{inner=new Ng;envelopeListeners=new Set;ring=new Fo;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(Bg(e,t))}catch{}return s}publish(e){let t=dt(),s=e.id??Uo(),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:rs(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>Lg&&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:rs(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 Bg(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 Cs;function Z(){return Cs||(Cs=new Rs),Cs}Xn();zr();var jg=/\breq-[0-9A-HJKMNP-TV-Z]{26}\b/,Ug=15*6e4,dd=45*6e4,cd=1500,ud="[agentx:same-work",Fg=new Set(["app","telegram","whatsapp","voice","slack","discord","email","sms","ntfy","dashboard","web-chat","tui","admin","test-drive","workflow-editor","guest","public-api"]);function Hg(n){return!!n&&Fg.has(n)}var Wg=new Set(["a2a","cron","workflow","reminder","events","business"]);function ld(n){return!!n&&Wg.has(n)}function gd(n,e){return!n||Hg(e)||n.startsWith(ud)?null:jg.exec(n)?.[0]??null}var Sn=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??Ug,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`),Jt({kind:"same_work_waited",agentId:e,ref:t,detail:"the same request reached this agent twice while one run was on it"})),d=!0,await Promise.race([y.done,(this.opts.sleep??Gg)(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 m=this.ended.get(o);return{note:m&&this.now()-m.at<=dd?qg(t,m,this.now()):"",waitedMs:this.now()-i,release:({text:y,ok:S,ran:x=!0})=>{this.holders.get(o)===l&&this.holders.delete(o),x&&this.ended.set(o,{at:this.now(),text:y,ok:S}),this.prune(),c()}}}prune(){let e=this.now()-dd;for(let[t,s]of this.ended)s.at<e&&this.ended.delete(t)}};function qg(n,e,t){let s=Math.max(0,Math.round((t-e.at)/6e4)),r=e.text.length>cd?e.text.slice(0,cd-1)+"\u2026":e.text;return[`${ud} 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(`
98
+ `)}function Gg(n){return new Promise(e=>setTimeout(e,n))}var Kg="[agentx:notices",kn=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),Jg(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 Jg(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[`${Kg} 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(`
99
+ `)}Xn();var pd=["manual","notify","auto"];function zg(n){return typeof n=="string"&&pd.includes(n)}var _s={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Qg=7*24*60*6e4,xt=class{constructor(e={},t){this.store=t;this.opts={..._s,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-Qg;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:Ge(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:Xg(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 Xg(n,e){return n.length<=e?n:`${n.slice(0,e)}
100
+ \u2026[truncated ${n.length-e} chars]`}qu();import{z as Yg}from"zod";var fd=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Vg(n){if(n==null)return{ok:!0,subscriptions:fd};let e=Yg.array(to).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 Zg=15,ep=1500,md=200;function hd(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function tp(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 jw(n,e,t={}){let s=tp(e,n.cursor),r=s.length?hd(s):n.cursor,o=s.filter(c=>n.subscriptions.some(u=>Ho(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}=np(o,i,t);return{text:a,cursor:r,matched:o.length,shown:d}}function np(n,e,t={}){let s=Math.max(3,t.maxLines??Zg),r=Math.max(200,t.maxChars??ep),o=n.map(a=>sp(`- ${qo(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(`
101
+ `);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 sp(n){return n.length<=md?n:`${n.slice(0,md-1)}\u2026`}import{existsSync as rp,mkdirSync as op,readFileSync as ip,renameSync as ap,writeFileSync as dp}from"node:fs";import{homedir as cp}from"node:os";import{dirname as up,join as lp}from"node:path";function gp(n){return{load:()=>rp(n)?JSON.parse(ip(n,"utf-8")):{},save:e=>{op(up(n),{recursive:!0});let t=`${n}.tmp`;dp(t,JSON.stringify(e,null,2),{mode:384}),ap(t,n)}}}function pp(){if(!process.env.VITEST)return gp(process.env.AGENTX_ATTACH_BINDINGS_FILE??lp(cp(),".agentx","attach-bindings.json"))}var Es;function yd(){return Es||(Es=new xt({},pp())),Es}Yn();import{readFileSync as mp}from"fs";import{homedir as fp}from"os";import{join as hp}from"path";var St=null,yp=6e4;function wp(){try{let n=hp(fp(),".claude.json"),e=mp(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function bp(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 xp(n=!1){let e=Date.now();return!n&&St&&e-St.checkedAt<yp||(St=bp(wp(),e)),St}function wd(n){let e=xp();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 Sd={warnRatio:.8},Ze={...Sd},kd=5*60*60*1e3,Td=60*60*1e3,Se=[];function Id(n){Ze={...Sd,...n||{}}}function vd(n){let e=n-kd,t=0;for(;t<Se.length&&Se[t]<e;)t++;t>0&&Se.splice(0,t)}function Ad(n=Date.now()){vd(n),Se.push(n)}var Ue=new Map,Sp=15*60*1e3,kp=24*60*60*1e3,Ds=new Map;function Tn(n){return n.resetsAt??n.seenAt+Sp}function Ps(n,e,t){n.status!=="rejected"||n.usingOverage||Ds.set(n.window,{window:n.window,heldSince:n.seenAt,...n.resetsAt&&{resetsAt:n.resetsAt},liftedAt:e,how:t})}function Zw(n=Date.now()){let e=new Map(Ds);for(let t of Ue.values()){if(t.status!=="rejected"||t.usingOverage)continue;let s=Tn(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<kp).sort((t,s)=>s.liftedAt-t.liftedAt)}var Os=null;function Ns(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;Os={...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 eb(){return Os?{...Os}:null}function $d(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function Tp(n){let e=$d(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ip(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=Tp(s.resetsAt??s.resets_at),a=$d(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 Md(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Cd(n,e){let t=Md(n);return!t||!e||e.toLowerCase().includes(t)}function Ls(n,e=Date.now(),t){let s=Ip(n,e);if(!s)return null;if(s.status!=="rejected"){for(let[r,o]of Ue)if(o.status==="rejected"){if(r===s.window){Tn(o)>e&&Ps(o,e,"served");continue}(!Md(r)||t&&Cd(r,t))&&(Tn(o)>e&&Ps(o,e,"served"),Ue.delete(r))}}else Ds.delete(s.window);return Ue.set(s.window,s),s}function Rd(n=Date.now()){return[...Ue.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:Tn(e)>n)}function vp(n=Date.now(),e){return Rd(n).find(t=>Cd(t.window,e))??null}function tb(n=Date.now()){let e=Rd(n);for(let t of e)Ps(t,n,"operator"),Ue.delete(t.window);return e}function Ap(){return[...Ue.values()].sort((n,e)=>e.seenAt-n.seenAt)}function bd(n){return typeof n=="number"&&n>0}function _d(n=Date.now()){vd(n);let e=n-Td,t=0;for(let o=Se.length-1;o>=0&&Se[o]>=e;o--)t++;let s=Se.length,r={lastHour:t,last5h:s,maxPerHour:bd(Ze.maxPerHour)?Ze.maxPerHour:void 0,maxPer5h:bd(Ze.maxPer5h)?Ze.maxPer5h:void 0,provider:Ap()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function xd(n,e){let t=Se[Se.length-n];return t===void 0?void 0:t+e}function Ed(n){return n.replace(/_/g," ")}function Pd(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function Od(n,e=Date.now(),t){let s=_d(e);if(n)return null;let r=vp(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Ed(r.window)} window as rejected. Cold dispatches are held until it resets ${Pd(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s,retryAt:r.resetsAt}: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,retryAt:xd(s.maxPerHour,Td)}: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,retryAt:xd(s.maxPer5h,kd)}:null}function Dd(n=Date.now()){let e=_d(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 ${Ed(t.window)} window nearing its limit${r}, resets ${Pd(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 $p,mkdirSync as Mp,readFileSync as Cp,renameSync as Rp,writeFileSync as _p}from"fs";import{dirname as Ep}from"path";var Bs=200,In=class{constructor(e=Bs,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($p(e))try{let t=JSON.parse(Cp(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{Mp(Ep(this.file),{recursive:!0});let e=`${this.file}.tmp`;_p(e,JSON.stringify(Object.fromEntries(this.held))),Rp(e,this.file)}catch(e){this.log(`[budget] couldn't save held messages to ${this.file} (${e?.message??e})`)}}};var js=new Map;function Nd(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function Ld(n,e,t,s=Date.now()){let r=js.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},js.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 Bd(n){let e=js.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 jp,readFileSync as Up}from"fs";import{resolve as Fp}from"path";import{existsSync as Pp,readFileSync as Op,unlinkSync as Dp,writeFileSync as Np}from"fs";import{resolve as Ud}from"path";var jd="_agentxManaged";function vn(n=process){let e=n.argv[1]?Ud(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 ub(n,e){return!e||n.agentx?n:{...n,agentx:e}}function lb(n,e){let t=Ud(n,".mcp.json"),s=Pp(t),r=s?Bp(t):null,o=r!==null&&r[jd]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return Dp(t),"removed";let a={[jd]:!0,mcpServers:Lp(e)};return Np(t,JSON.stringify(a,null,2)+`
102
+ `),s?"updated":"installed"}function Lp(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=yo(s);e[t]=u?{...c,headers:u}:c}else e[t]=i}return e}function Bp(n){try{return JSON.parse(Op(n,"utf-8"))}catch{return null}}var Hp=["github","a2a","workflow","cron"],Wp=["claude-code","codex-cli"],qp={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},Gp="AGENTX_MCP_TOOLS",Kp=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow","agentx_waiting","agentx_content","agentx_sprint","agentx_node","agentx_job_state"],Jp=["agentx_agents","agentx_recent","agentx_wiki_query","agentx_lookup"];function Hd(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 Wd(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=[...Kp,...n.contextOnDemand?Jp:[],...s];return Array.from(new Set(r))}function zp(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[Gp]:e.join(",")}}}function qd(n,e,t){if(!Wp.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(Hp.includes(e)?"lean":"full")}function Gd(n){return{...qp,...n?.lean??{}}}function Kd(n){return n.settingSources.includes("project")}function Qp(n,e,t=vn(),s){let r=Jd(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=zp(o.agentx??r.agentx??t,Wd(e,s)),o}function Jd(n){let e=Fp(n,".mcp.json");if(!jp(e))return{};try{let s=JSON.parse(Up(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function zd(n,e,t=vn(),s){let r=Qp(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=Hd(e,s);return i.length&&o.push("--tools",Xd(i).join(",")),o}function Qd(){return["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{}}),"--setting-sources","project,local","--tools",""]}var Fd="ToolSearch";function Xd(n){return n.includes(Fd)?n:[...n,Fd]}function Yd(n,e=vn()){let t=Jd(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function Vd(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), a colleague's or a work item's status (agentx_lookup, before asking them), and this machine, its programs, Claude usage limits and running work (agentx_node: answer from it with its check time, never from memory).`].join(`
103
+ `)}function Zd(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=Hd(e,t);r.length&&s.push(`tools=${Xd(r).join("+")}`);let o=Wd(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as ae,mkdirSync as sh,readdirSync as ke,readFileSync as Rt,rmSync as rh,writeFileSync as oh}from"fs";import{resolve as G}from"path";import{randomUUID as ih}from"crypto";import{existsSync as He,mkdirSync as Us,readFileSync as Xp,readdirSync as Yp,renameSync as Vp,unlinkSync as Zp,writeFileSync as An}from"fs";import{resolve as Re,relative as $n}from"path";import{z as Y}from"zod";var Fe=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 em(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(`
104
+ `)){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(`
105
+ `)}var kt=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Re(process.cwd(),".agentx/procedures"),Us(this.baseDir,{recursive:!0})}pathFor(e){return Re(this.baseDir,`${e}.md`)}get draftsDir(){return Re(this.baseDir,"_drafts")}draftPathFor(e){return Re(this.draftsDir,`${e}.md`)}parseFile(e){let t=Xp(e,"utf-8"),{meta:s,body:r}=em(t),o=Fe.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:$n(this.baseDir,e)}:null}listDir(e){if(!He(e))return[];let t=[];for(let s of Yp(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Re(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 He(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return He(t)?this.parseFile(t):null}add(e,t){let s=Fe.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(He(r))throw new Error(`Procedure already exists: ${s.id}`);return An(r,Mn(s)+`
106
106
 
107
107
  `+t.trim()+`
108
- `),{meta:s,body:t.trim(),path:An(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=Fe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return vn(this.pathFor(e),$n(o)+`
108
+ `),{meta:s,body:t.trim(),path:$n(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=Fe.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return An(this.pathFor(e),Mn(o)+`
109
109
 
110
110
  `+i.trim()+`
111
- `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=Fe.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(He(r))throw new Error(`Draft already exists: ${s.id}`);return Us(this.draftsDir,{recursive:!0}),vn(r,$n(s)+`
111
+ `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=Fe.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(He(r))throw new Error(`Draft already exists: ${s.id}`);return Us(this.draftsDir,{recursive:!0}),An(r,Mn(s)+`
112
112
 
113
113
  `+t.trim()+`
114
- `),{meta:s,body:t.trim(),path:An(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=Fe.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return vn(this.pathFor(e),$n(s)+`
114
+ `),{meta:s,body:t.trim(),path:$n(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=Fe.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return An(this.pathFor(e),Mn(s)+`
115
115
 
116
116
  `+t.body+`
117
- `),Zp(this.draftPathFor(e)),{meta:s,body:t.body,path:An(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!He(t))throw new Error(`Draft not found: ${e}`);let s=Re(this.draftsDir,"_rejected");Us(s,{recursive:!0}),Vp(t,Re(s,`${e}.md`))}isRejected(e){return He(Re(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as tm,mkdirSync as nm,readFileSync as sm,writeFileSync as rm}from"fs";import{dirname as om,resolve as im}from"path";import{z as ie}from"zod";var am=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()}),dm=ie.object({minedThrough:ie.string().optional(),candidates:ie.array(am).default([])});function ec(n){return im(n,"_candidates.json")}function cm(n){let e=ec(n);if(!tm(e))return{candidates:[]};try{let t=dm.safeParse(JSON.parse(sm(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function um(n,e){let t=ec(n);nm(om(t),{recursive:!0}),rm(t,JSON.stringify(e,null,2)+`
118
- `)}function lm(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 gm(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function pm(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function js(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function tc(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 Fs(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=js(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let d=[],c=tc(o,js(a.meta.trigger));c>0&&d.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=tc(o,js(u));l>0&&d.push("title/tags");let g=Math.min(1,c*.7+l*.5);g>=r&&i.push({procedure:a,score:g,reasons:d})}return i.sort((a,d)=>d.score-a.score).slice(0,s)}function Hs(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(`
117
+ `),Zp(this.draftPathFor(e)),{meta:s,body:t.body,path:$n(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!He(t))throw new Error(`Draft not found: ${e}`);let s=Re(this.draftsDir,"_rejected");Us(s,{recursive:!0}),Vp(t,Re(s,`${e}.md`))}isRejected(e){return He(Re(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as tm,mkdirSync as nm,readFileSync as sm,writeFileSync as rm}from"fs";import{dirname as om,resolve as im}from"path";import{z as ie}from"zod";var am=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()}),dm=ie.object({minedThrough:ie.string().optional(),candidates:ie.array(am).default([])});function ec(n){return im(n,"_candidates.json")}function cm(n){let e=ec(n);if(!tm(e))return{candidates:[]};try{let t=dm.safeParse(JSON.parse(sm(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function um(n,e){let t=ec(n);nm(om(t),{recursive:!0}),rm(t,JSON.stringify(e,null,2)+`
118
+ `)}function lm(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 gm(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function pm(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function Fs(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function tc(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 Hs(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=Fs(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let d=[],c=tc(o,Fs(a.meta.trigger));c>0&&d.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=tc(o,Fs(u));l>0&&d.push("title/tags");let g=Math.min(1,c*.7+l*.5);g>=r&&i.push({procedure:a,score:g,reasons:d})}return i.sort((a,d)=>d.score-a.score).slice(0,s)}function Ws(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(`
119
119
  `)})].join(`
120
120
 
121
- `)}zt();at();var qs="turn-progress",nc={progress:Ae({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.")},Ws=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function sc(n){return{agent:n.agent,request:Ws(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:Ws(e.input,300),...e.result!==void 0?{result:Ws(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}at();var rc="turn-handoff",oc="approval-binding",ic={nextStep:Ae({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.")},ac={approves:be("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."})},mm=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,dc=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,fm=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Gs(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:fm.test(e.split(`
122
- `).slice(-3).join(" ")):!1}var hm=/^\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 cc(n){return n.trim().length<=160&&hm.test(n)}function uc(n){return n.trim().length<=160}function lc(n){return{agent:n.agent,channel:n.channel,request:mm(n.request,1500),agentReplyEnding:dc(n.reply,1200)}}function gc(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:dc(n.previousReply,1200)}}var ym=5*6e4,wm=3,bm=12,xm=24*60*6e4,pc=new Set(["cron","heartbeat","bench","a2a","business"]),Sm={observe(){},stop(){}};function mc(n){if(Je(qs)==="off")return Sm;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let g;for(let[m,h]of o)h>1&&(!g||h>g.times)&&(g={call:m,times:h});return g},u=g=>{if(d)return;d=!0,a=s.length;let m=sc({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-bm),repeated:c(),trigger:g});pe(qs,m,nc,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:g}}).finally(()=>{d=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??ym);return l.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let h of m){if(h?.type!=="tool_use")continue;let y=h.input?JSON.stringify(h.input):"",S={tool:h.name||"tool",input:y};s.push(S),typeof h.id=="string"&&r.set(h.id,S);let x=`${S.tool}(${y})`,C=(o.get(x)??0)+1;o.set(x,C),C>=wm&&!i.has(x)&&(i.add(x),u("repetition"))}else if(g?.type==="user")for(let h of m){if(h?.type!=="tool_result")continue;let y=r.get(h.tool_use_id);y&&(y.result=Array.isArray(h.content)?h.content.map(S=>typeof S?.text=="string"?S.text:"").join(""):typeof h.content=="string"?h.content:"",h.is_error&&(y.error=!0))}},stop(){clearInterval(l)}}}var Ks=new Map,fc=(n,e,t)=>`${n}\0${e}\0${t}`;function hc(n){if(pc.has(n.channel)||!Gs(n.reply))return;let e=fc(n.agent,n.channel,n.chatId);pe(rc,lc(n),ic,{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 yc(n){if(pc.has(n.channel))return;let e=fc(n.agent,n.channel,n.chatId),t=Ks.get(e);if(t){Ks.delete(e);let s=no().store;if(s&&Date.now()-t.at<xm)try{s.label(t.callId,"userReply",cc(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!uc(n.message)||!Gs(n.previousReply)||pe(oc,gc({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),ac,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}ju();Hu();var qb={enabled:!0,maxWakes:20,maxCostUsd:10,graceMinutes:10,maxBackgroundMinutes:180},Js="its background work",Mn=6e4,km=1500,Tm=600,bc=Symbol("jobs.wake");function Gb(n){return Im({channel:n.channel,chatId:n.chatId,sender:"system:job-wake"},n.id)}function Im(n,e){return Object.assign(n,{[bc]:e})}function Tt(n){let e=n?n[bc]:void 0;return typeof e=="string"&&e?e:void 0}var Cn=(n,e)=>n.length>e?`${n.slice(0,e-1)}\u2026`:n;function vm(n,e){let t=[`[agentx:job-wake id=${n.id}] The daemon started this run to continue a job you left open (wake ${n.wakeCount+1} of at most ${e.maxWakes}).`,"",`What was asked${n.requester?` (by ${n.requester})`:""}:`,Cn(n.text,km)];return n.home&&t.push("",`Where the work lives: ${n.home.link}`),n.note&&t.push("",`Why you are woken now: ${n.note}`),t.push("","Continue the work now. Do not repeat an outside action you already took (a message sent, a comment posted, a deploy): check first.","Before this run ends, state the job's state: done with its proof, continue (when, and what is left), waiting (on whom, until when) or blocked (why). A run that ends without one leaves the job stalled."),t.join(`
123
- `)}var Am=45*Mn,zs=n=>n.door==="cron",wc=class{constructor(e){this.deps=e;this.now=e.now??Date.now}now;startedAt=new Map;factsOf(e){let t=null,s=()=>t??=this.deps.jobs.runs(e.id);return this.deps.facts?this.deps.facts(e,s):fi(s())}tick(){let e={woken:0,capped:0,stalled:0},t=this.deps.settings();if(!t.enabled)return e;try{this.wakeDue(t,e)}catch(s){this.deps.log(`[jobs] wake failed: ${s?.message??s}`)}try{this.checkOwned(t,e)}catch(s){this.deps.log(`[jobs] invariant check failed: ${s?.message??s}`)}return e}wakeDue(e,t){let{jobs:s,log:r}=this.deps,o=this.now();for(let i of s.dueWakes(o)){if(!this.deps.hasAgent(i.assignee)){s.markStalled(i.id,`its agent ${i.assignee} is not on this node, so it cannot be woken`,o)&&t.stalled++;continue}if(zs(i)){s.markStalled(i.id,`a schedule's job is not woken by the daemon; its next firing continues it. What was left: ${i.note??"not said"}`,o)&&t.stalled++;continue}if(this.startedAt.has(i.id)||this.factsOf(i).liveRun||this.deps.held?.(i))continue;let a=s.costUsd(i.id),d=i.wakeCount>=e.maxWakes?`it was woken ${i.wakeCount} times, the most a job may be (requests.jobs.wake.maxWakes)`:a>=e.maxCostUsd?`its runs cost $${a.toFixed(2)}, the most a job may spend (requests.jobs.wake.maxCostUsd)`:null;if(d){s.markStalled(i.id,`not woken again: ${d}. What was left: ${i.note??"not said"}`,o)&&(t.capped++,r(`[jobs] ${i.id} stalled at its cap: ${d}`));continue}if(!s.takeWake(i.id,o))continue;this.startedAt.set(i.id,o);let c=s.runCount(i.id);t.woken++,r(`[jobs] waking ${i.id} for ${i.assignee} (wake ${i.wakeCount+1})`),Promise.resolve().then(()=>this.deps.start(i,vm(i,e))).then(u=>{let l=u&&typeof u=="object"?u.error:void 0;if(l&&$e(l)||(this.startedAt.get(i.id)===o&&this.startedAt.delete(i.id),!l))return;if(s.runCount(i.id)>c){r(`[jobs] ${i.id}: its wake run ended with an error (${Cn(l,120)}), not armed again`);return}let g=this.now();s.rearmWake(i.id,g+5*Mn,i.note??"the wake could not start",g)&&r(`[jobs] ${i.id}: wake could not start (${Cn(l,120)}), armed again`)}).catch(u=>{this.startedAt.get(i.id)===o&&this.startedAt.delete(i.id),r(`[jobs] ${i.id}: wake failed: ${u?.message??u}`)})}}checkOwned(e,t){let{jobs:s,log:r}=this.deps,o=this.now();for(let[i,a]of this.startedAt)o-a>=Am&&this.startedAt.delete(i);for(let i of s.unheldCandidates()){if(o-i.updatedAt<e.graceMinutes*Mn&&i.state!=="waiting"||this.startedAt.has(i.id))continue;let a=this.factsOf(i);if(pi(i,a,o)||this.deps.held?.(i))continue;let d=mi(i,a,o);s.markStalled(i.id,d,o)&&(t.stalled++,r(`[jobs] ${i.id} stalled: ${d}`))}}runLeftBackground(e,t,s){let r=this.deps.settings();if(!r.enabled||t<=0||e.ownerRequest||zs(e))return!1;let o=this.now();return this.deps.jobs.declare(e.id,{state:"waiting",on:Js,until:o+r.maxBackgroundMinutes*Mn,note:`${t} background task${t===1?"":"s"} still running when the run ended`},{runId:s,now:o})}backgroundEnded(e,t,s){if(!this.deps.settings().enabled)return!1;try{let{jobs:r}=this.deps,o=r.waitingInChat(e.agentId,e.channel,e.chatId,Js)??r.latestInChat(e.agentId,e.channel,e.chatId);if(!o||(s&&s>0&&r.addCost(o.id,s),o.ownerRequest&&o.declaredAt===null)||zs(o)||!(o.waitingOn===Js||o.state==="working")||this.startedAt.has(o.id)||this.factsOf(o).liveRun||this.deps.held?.(o))return!1;let i=this.now(),a=t.replace(/\s+/g," ").trim(),d=`background work you left running has ended.${a?` Its closing reply: ${Cn(a,Tm)}`:""}`,c=this.deps.jobs.armWake(o.id,i,d,i);return c&&this.deps.log(`[jobs] ${o.id}: background work ended, waking it`),c}catch(r){return this.deps.log(`[jobs] background end failed: ${r?.message??r}`),!1}}};Wu();function xc(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 Rn(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function Jb(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=Rn(n);return!t||Rn(e)?e:{...e??{},taskType:t}}eo();function Sc(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(We(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 We(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var et=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 kc(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new et(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as $m,spawn as Mm}from"child_process";import{existsSync as Cm,mkdirSync as Rm,readFileSync as _m,renameSync as Em,statSync as Pm,writeFileSync as Om}from"fs";import{dirname as Dm}from"path";var En={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function Nm(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 Qs(n){try{return!n||!Cm(n)?void 0:$m("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function It(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 Tc(n){let e={...En,...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=It(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??Qs,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let d=Nm(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 Lm=24*60*60*1e3,Bm=7*Lm,_n=class{constructor(e){this.file=e}sessions=[];stamp;fileStamp(){try{let e=Pm(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(_m(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<Bm);try{Rm(Dm(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Om(t,JSON.stringify({sessions:this.sessions},null,2)),Em(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]}},Um=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
124
- `);function jm(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var Fm=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function Ic(n){return n.replace(Fm,"")}function Hm(n){let e=Ic(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 vc(n){let e=n.spawn??((d,c,u)=>Mm(d,c,u)),t=n.python??"python3",s=["-c",Um,"claude",...jm(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=()=>Ic(o).trim().split(`
121
+ `)}Qt();at();var Gs="turn-progress",nc={progress:Ae({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.")},qs=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function sc(n){return{agent:n.agent,request:qs(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:qs(e.input,300),...e.result!==void 0?{result:qs(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}at();var rc="turn-handoff",oc="approval-binding",ic={nextStep:Ae({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.")},ac={approves:be("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."})},mm=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,dc=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,fm=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Ks(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:fm.test(e.split(`
122
+ `).slice(-3).join(" ")):!1}var hm=/^\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 cc(n){return n.trim().length<=160&&hm.test(n)}function uc(n){return n.trim().length<=160}function lc(n){return{agent:n.agent,channel:n.channel,request:mm(n.request,1500),agentReplyEnding:dc(n.reply,1200)}}function gc(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:dc(n.previousReply,1200)}}var ym=5*6e4,wm=3,bm=12,xm=24*60*6e4,pc=new Set(["cron","heartbeat","bench","a2a","business"]),Sm={observe(){},stop(){}};function mc(n){if(Je(Gs)==="off")return Sm;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,d=!1,c=()=>{let g;for(let[m,h]of o)h>1&&(!g||h>g.times)&&(g={call:m,times:h});return g},u=g=>{if(d)return;d=!0,a=s.length;let m=sc({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-bm),repeated:c(),trigger:g});pe(Gs,m,nc,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:g}}).finally(()=>{d=!1})},l=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??ym);return l.unref?.(),{observe(g){let m=Array.isArray(g?.message?.content)?g.message.content:[];if(g?.type==="assistant")for(let h of m){if(h?.type!=="tool_use")continue;let y=h.input?JSON.stringify(h.input):"",S={tool:h.name||"tool",input:y};s.push(S),typeof h.id=="string"&&r.set(h.id,S);let x=`${S.tool}(${y})`,C=(o.get(x)??0)+1;o.set(x,C),C>=wm&&!i.has(x)&&(i.add(x),u("repetition"))}else if(g?.type==="user")for(let h of m){if(h?.type!=="tool_result")continue;let y=r.get(h.tool_use_id);y&&(y.result=Array.isArray(h.content)?h.content.map(S=>typeof S?.text=="string"?S.text:"").join(""):typeof h.content=="string"?h.content:"",h.is_error&&(y.error=!0))}},stop(){clearInterval(l)}}}var Js=new Map,fc=(n,e,t)=>`${n}\0${e}\0${t}`;function hc(n){if(pc.has(n.channel)||!Ks(n.reply))return;let e=fc(n.agent,n.channel,n.chatId);pe(rc,lc(n),ic,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&Js.set(e,{callId:t.callId,at:Date.now()})})}function yc(n){if(pc.has(n.channel))return;let e=fc(n.agent,n.channel,n.chatId),t=Js.get(e);if(t){Js.delete(e);let s=no().store;if(s&&Date.now()-t.at<xm)try{s.label(t.callId,"userReply",cc(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!uc(n.message)||!Ks(n.previousReply)||pe(oc,gc({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),ac,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Uu();Hu();var qb={enabled:!0,maxWakes:20,maxCostUsd:10,graceMinutes:10,maxBackgroundMinutes:180},zs="its background work",Rn=6e4,km=1500,Tm=600,bc=Symbol("jobs.wake");function Gb(n){return Im({channel:n.channel,chatId:n.chatId,sender:"system:job-wake"},n.id)}function Im(n,e){return Object.assign(n,{[bc]:e})}function It(n){let e=n?n[bc]:void 0;return typeof e=="string"&&e?e:void 0}var Tt=(n,e)=>n.length>e?`${n.slice(0,e-1)}\u2026`:n;function vm(n,e){let t=[`[agentx:job-wake id=${n.id}] The daemon started this run to continue a job you left open (wake ${n.wakeCount+1} of at most ${e.maxWakes}).`,"",`What was asked${n.requester?` (by ${n.requester})`:""}:`,Tt(n.text,km)];return n.home&&t.push("",`Where the work lives: ${n.home.link}`),n.note&&t.push("",`Why you are woken now: ${n.note}`),t.push("","Continue the work now. Do not repeat an outside action you already took (a message sent, a comment posted, a deploy): check first.","Before this run ends, state the job's state: done with its proof, continue (when, and what is left), waiting (on whom, until when) or blocked (why). A run that ends without one leaves the job stalled."),t.join(`
123
+ `)}var Am=45*Rn,Cn=n=>n.door==="cron",wc=class{constructor(e){this.deps=e;this.now=e.now??Date.now}now;startedAt=new Map;factsOf(e){let t=null,s=()=>t??=this.deps.jobs.runs(e.id);return this.deps.facts?this.deps.facts(e,s):fi(s())}tick(){let e={woken:0,capped:0,stalled:0},t=this.deps.settings();if(!t.enabled)return e;try{this.wakeDue(t,e)}catch(s){this.deps.log(`[jobs] wake failed: ${s?.message??s}`)}try{this.checkOwned(t,e)}catch(s){this.deps.log(`[jobs] invariant check failed: ${s?.message??s}`)}return e}wakeDue(e,t){let{jobs:s,log:r}=this.deps,o=this.now();for(let i of s.dueWakes(o)){if(!this.deps.hasAgent(i.assignee)){s.markStalled(i.id,`its agent ${i.assignee} is not on this node, so it cannot be woken`,o)&&t.stalled++;continue}if(Cn(i)){s.markStalled(i.id,`a schedule's job is not woken by the daemon; its next firing continues it. What was left: ${i.note??"not said"}`,o)&&t.stalled++;continue}if(this.startedAt.has(i.id)||this.factsOf(i).liveRun||this.deps.held?.(i))continue;let a=s.costUsd(i.id),d=i.wakeCount>=e.maxWakes?`it was woken ${i.wakeCount} times, the most a job may be (requests.jobs.wake.maxWakes)`:a>=e.maxCostUsd?`its runs cost $${a.toFixed(2)}, the most a job may spend (requests.jobs.wake.maxCostUsd)`:null;if(d){s.markStalled(i.id,`not woken again: ${d}. What was left: ${i.note??"not said"}`,o)&&(t.capped++,r(`[jobs] ${i.id} stalled at its cap: ${d}`));continue}if(!s.takeWake(i.id,o))continue;this.startedAt.set(i.id,o);let c=s.runCount(i.id);t.woken++,r(`[jobs] waking ${i.id} for ${i.assignee} (wake ${i.wakeCount+1})`),Promise.resolve().then(()=>this.deps.start(i,vm(i,e))).then(u=>{let l=u&&typeof u=="object"?u.error:void 0;if(l&&$e(l)||(this.startedAt.get(i.id)===o&&this.startedAt.delete(i.id),!l))return;if(s.runCount(i.id)>c){r(`[jobs] ${i.id}: its wake run ended with an error (${Tt(l,120)}), not armed again`);return}let g=this.now();s.rearmWake(i.id,g+5*Rn,i.note??"the wake could not start",g)&&r(`[jobs] ${i.id}: wake could not start (${Tt(l,120)}), armed again`)}).catch(u=>{this.startedAt.get(i.id)===o&&this.startedAt.delete(i.id),r(`[jobs] ${i.id}: wake failed: ${u?.message??u}`)})}}checkOwned(e,t){let{jobs:s,log:r}=this.deps,o=this.now();for(let[i,a]of this.startedAt)o-a>=Am&&this.startedAt.delete(i);for(let i of s.unheldCandidates()){if(o-i.updatedAt<e.graceMinutes*Rn&&i.state!=="waiting"||this.startedAt.has(i.id))continue;let a=this.factsOf(i);if(pi(i,a,o)||this.deps.held?.(i))continue;let d=mi(i,a,o);s.markStalled(i.id,d,o)&&(t.stalled++,r(`[jobs] ${i.id} stalled: ${d}`))}}wakeFor(e,t){let s=this.deps.settings();if(!s.enabled)return!1;try{let r=this.deps.jobs.get(e);if(!r||Cn(r)||r.peer||!this.deps.hasAgent(r.assignee)||r.state==="done"||r.state==="dropped"||r.state==="blocked"||r.state==="stalled"||r.wakeCount>=s.maxWakes||this.deps.jobs.costUsd(r.id)>=s.maxCostUsd||this.startedAt.has(r.id)||this.factsOf(r).liveRun||this.deps.held?.(r))return!1;let o=this.now(),i=r.wakeAt!==null&&r.note?`${t} (also: ${r.note})`:t,a=this.deps.jobs.armWake(r.id,o,i,o);return a&&this.deps.log(`[jobs] ${r.id}: wake armed (${Tt(t.replace(/\s+/g," "),120)})`),a}catch(r){return this.deps.log(`[jobs] wake for ${e} failed: ${r?.message??r}`),!1}}delegatorJob(e,t){try{let s=this.deps.jobs.byDelegation(e)??this.deps.jobs.get(`job-${e}`);if(!s?.parentId)return null;let r=this.deps.jobs.get(s.parentId);return r&&!r.ownerRequest&&r.assignee===t?r.id:null}catch{return null}}alertDelegator(e,t,s){if(s.kind!=="delegation"||!s.taskKey.startsWith("dlg-"))return!1;let r=this.delegatorJob(s.taskKey,e);return r?this.wakeFor(r,t):!1}runLeftBackground(e,t,s){let r=this.deps.settings();if(!r.enabled||t<=0||e.ownerRequest||Cn(e))return!1;let o=this.now();return this.deps.jobs.declare(e.id,{state:"waiting",on:zs,until:o+r.maxBackgroundMinutes*Rn,note:`${t} background task${t===1?"":"s"} still running when the run ended`},{runId:s,now:o})}backgroundEnded(e,t,s){if(!this.deps.settings().enabled)return!1;try{let{jobs:r}=this.deps,o=r.waitingInChat(e.agentId,e.channel,e.chatId,zs)??r.latestInChat(e.agentId,e.channel,e.chatId);if(!o||(s&&s>0&&r.addCost(o.id,s),o.ownerRequest&&o.declaredAt===null)||Cn(o)||!(o.waitingOn===zs||o.state==="working")||this.startedAt.has(o.id)||this.factsOf(o).liveRun||this.deps.held?.(o))return!1;let i=this.now(),a=t.replace(/\s+/g," ").trim(),d=`background work you left running has ended.${a?` Its closing reply: ${Tt(a,Tm)}`:""}`,c=this.deps.jobs.armWake(o.id,i,d,i);return c&&this.deps.log(`[jobs] ${o.id}: background work ended, waking it`),c}catch(r){return this.deps.log(`[jobs] background end failed: ${r?.message??r}`),!1}}};Wu();function xc(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 _n(n){let e=n?.taskType;return typeof e=="string"&&e.trim()?e.trim().slice(0,64):void 0}function Jb(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=_n(n);return!t||_n(e)?e:{...e??{},taskType:t}}eo();function Sc(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(We(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 We(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var et=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 kc(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new et(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as $m,spawn as Mm}from"child_process";import{existsSync as Cm,mkdirSync as Rm,readFileSync as _m,renameSync as Em,statSync as Pm,writeFileSync as Om}from"fs";import{dirname as Dm}from"path";var Pn={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function Nm(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 Qs(n){try{return!n||!Cm(n)?void 0:$m("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function vt(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 Tc(n){let e={...Pn,...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=vt(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??Qs,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let d=Nm(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 Lm=24*60*60*1e3,Bm=7*Lm,En=class{constructor(e){this.file=e}sessions=[];stamp;fileStamp(){try{let e=Pm(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(_m(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<Bm);try{Rm(Dm(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;Om(t,JSON.stringify({sessions:this.sessions},null,2)),Em(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]}},jm=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
124
+ `);function Um(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var Fm=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function Ic(n){return n.replace(Fm,"")}function Hm(n){let e=Ic(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 vc(n){let e=n.spawn??((d,c,u)=>Mm(d,c,u)),t=n.python??"python3",s=["-c",jm,"claude",...Um(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=()=>Ic(o).trim().split(`
125
125
  `).slice(-5).join(`
126
126
  `).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 g=h=>{try{l.pid&&process.kill(-l.pid,h)}catch{try{l.kill(h)}catch{}}},m=setTimeout(()=>{g("SIGTERM"),setTimeout(()=>g("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);m.unref?.(),l.stdout?.on("data",i),l.stderr?.on("data",i),l.on("error",h=>{clearTimeout(m);let 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(m),c)return;let y=Hm(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 Wm=1e5;function qm(n,e){let s=`
127
127
 
@@ -130,21 +130,21 @@ This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.numbe
130
130
  [message cut at ${r} characters]`:n}${s}`}function Gm(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(`
131
131
  `)}function Km(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 Jm(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function Ac(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:Jm(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):Km(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=qm(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:Gm(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}import{spawn as Ym}from"child_process";import{existsSync as Vm,mkdirSync as Zm,mkdtempSync as ef,readFileSync as Pc,renameSync as tf,rmSync as nf,writeFileSync as sf}from"fs";import{homedir as rf,tmpdir as of}from"os";import{dirname as af,join as Ys,resolve as Vs,sep as Rc}from"path";var zm=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function Qm(n){return n.replace(/^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm,"").replace(/`[^`\n]*`/g,"").split(`
132
132
  `).filter(e=>!/^[ \t]*>/.test(e)).join(`
133
- `)}function $c(n,e){return vt(n)?n:`${n}
133
+ `)}function $c(n,e){return At(n)?n:`${n}
134
134
 
135
- <!-- agentx:${e} -->`}function vt(n){if(!n)return null;let e=Qm(n).match(zm);return e?e[1]:null}var Mc="unknown";function ex(n,e){let t=vt(n);return t&&(!e||t===e)?t:null}function tx(n){return`> \u{1F916} **${n}** (via AgentX)
135
+ <!-- agentx:${e} -->`}function At(n){if(!n)return null;let e=Qm(n).match(zm);return e?e[1]:null}var Mc="unknown";function ex(n,e){let t=At(n);return t&&(!e||t===e)?t:null}function tx(n){return`> \u{1F916} **${n}** (via AgentX)
136
136
 
137
- `}function Cc(n,e){if(!e||!n)return null;let t=vt(n);return t&&t!==Mc?t:null}function nx(n,e){return e&&vt(n)===Mc}function sx(n,e,t){let s=Cc(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function rx(n,e,t){let s=Cc(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function ox(n,e){return e||!n?n:Xm(n)}function ix(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function Xm(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return vt(n)?n.replace(/</g,"&lt;"):n}var Oc={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Dc(n){return`spec-tests/issue-${n}`}function Nc(n){return`test: spec tests for #${n}`}function df(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var cf=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function uf(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${cf(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function lf(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 gf(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 pf(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:lf(e),interfaces:gf(`${n.title}
137
+ `}function Cc(n,e){if(!e||!n)return null;let t=At(n);return t&&t!==Mc?t:null}function nx(n,e){return e&&At(n)===Mc}function sx(n,e,t){let s=Cc(n,t);return s?{id:e.id,name:`agent:${s}`,isBot:!0}:e}function rx(n,e,t){let s=Cc(n,t);return s?`${s} (an AgentX agent, posted with ${e}'s account)`:e}function ox(n,e){return e||!n?n:Xm(n)}function ix(n,e,t){return(n??[]).filter(s=>!t||s.agentId===t).flatMap(s=>s[e]??[])}function Xm(n){let e;do e=n,n=n.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"");while(n!==e);return At(n)?n.replace(/</g,"&lt;"):n}var Oc={enabled:!1,paths:["src/daemon"],agent:"spec-tests",maxCostPerIssue:2,maxMinutes:20};function Dc(n){return`spec-tests/issue-${n}`}function Nc(n){return`test: spec tests for #${n}`}function df(n){let e=n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"spec-tests";return{name:n,email:`${e}@spec-tests.agentx.invalid`}}var cf=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function uf(n,e){return e.some(t=>{let s=t.trim().replace(/^\.?\/+/,"").replace(/\/+$/,"");return s?new RegExp(`(^|[^A-Za-z0-9_.\\/-])(\\.\\/)?${cf(s)}(?=$|[^A-Za-z0-9_-])`).test(n):!1})}function lf(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 gf(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 pf(n){let e=n.body??"";return{repo:n.repo,number:n.number,title:n.title,body:e,acceptanceCriteria:lf(e),interfaces:gf(`${n.title}
138
138
  ${e}`)}}var Xs=2e4;function mf(n){let e=n.body.length>Xs?`${n.body.slice(0,Xs)}
139
139
  [issue cut at ${Xs} characters]`:n.body,t=n.acceptanceCriteria.length?n.acceptanceCriteria.map((r,o)=>`${o+1}. ${r}`).join(`
140
140
  `):"(the issue has no checklist; take the requirements from its text)",s=n.interfaces.length?n.interfaces.map(r=>`- \`${r}\``).join(`
141
141
  `):"(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(`
142
142
  `)}function Lc(n,e){let t=Dc(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, "${Nc(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(`
143
- `)}var ff=90*24*60*60*1e3,Pn=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(Pc(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<ff);try{Zm(af(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;sf(t,JSON.stringify({runs:this.runs},null,2)),tf(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]}},hf=10*6e4;function Zs(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+hf))return"spec tests are already running for this issue"}}function Bc(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(!uf(`${t.title}
144
- ${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=Zs(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:pf(t)}}function yf(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function wf(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function bf(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 xf(n){let e=[],t=[];for(let s of n)s.status==="??"&&yf(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 Sf=[["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 kf(n){return Sf.filter(([,e])=>e.test(n)).map(([e])=>e)}var Tf=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],If=n=>`/${Vs(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function vf(n,e){let t=Vs(n),s=a=>t===a||t.startsWith(a.endsWith(Rc)?a:a+Rc),r=rf(),o=[...e,r,...Tf.map(a=>Ys(r,a)),"/proc"].map(a=>Vs(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let d=`/${If(a)}/**`;i.push(`Read(${d})`,`Edit(${d})`)}return i}async function Uc(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Dc(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},d,c=(l,g,m=12e4)=>s("git",l,{cwd:g,timeoutMs:m});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let g=r(),m={...a,...l,finishedAt:g,minutes:Math.round((g-o)/6e4*10)/10};n.store.record(m);let h=m.costUsd===void 0?"cost not reported":`$${m.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${m.status} in ${m.minutes} min, ${h}${m.note?` \u2014 ${m.note}`:""}`),m.status!=="pushed"&&m.note)try{await n.noteOnIssue($c(`Spec tests for #${t.number} (${e.agent}): ${m.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 m};try{let l=await c(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let g=await c(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),m=g.code===0&&g.stdout.trim()?g.stdout.trim():"origin/main";d=(n.makeTempDir??(()=>ef(Ys(of(),`agentx-spec-${t.number}-`))))();let h=await c(["worktree","add","--detach",d,m],n.checkout);if(h.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${m}: ${h.stderr.trim().slice(0,300)}`});let y=await n.runAgent({prompt:mf(t),dir:d,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:vf(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 S=await c(["status","--porcelain","-z","--untracked-files=all"],d);if(S.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not list the files the test agent wrote: ${S.stderr.trim().slice(0,300)}`});let{keep:x,discard:C}=xf(bf(S.stdout));if(C.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${C.join(", ")}`),!x.length)return await u({status:"no-tests",costUsd:y.costUsd,note:`the test agent wrote no new test file${C.length?` (its other changes were discarded: ${C.join(", ")})`:""}.`});let N=0,w=[];for(let M of x){let A=Pc(Ys(d,M),"utf8");N+=wf(A);for(let k of kf(A))w.push(`${k} in ${M}`)}if(w.length)return await u({status:"blocked",costUsd:y.costUsd,testFiles:x,note:`a written file looks like it holds a secret (${w.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let v=df(e.agent),R=["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`],_=await c(["add","--",...x],d);if(_.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not stage the tests: ${_.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).`,B=await c([...R,"commit","--no-verify","-m",Nc(t.number),"-m",L],d);if(B.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,note:`could not commit the tests: ${B.stderr.trim().slice(0,300)}`});let H=(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:H,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let J=await u({status:"pushed",costUsd:y.costUsd,branch:i,commit:H,testFiles:x,testsWritten:N});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(M){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${M?.message||M}`)}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{Vm(d)&&nf(d,{recursive:!0,force:!0})}catch{}}}}var Af=5e3,At=new Set,_c=!1;function $f(){for(let n of At)try{process.kill(-n,"SIGKILL")}catch{}At.clear()}function jc(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,d=[],c=(m,h)=>{if(!a){a=!0;for(let y of d)clearTimeout(y);s({code:m,stdout:r,stderr:h??o,timedOut:i})}},u;try{u=Ym(n,e,{cwd:t.cwd,env:t.env,detached:t.killGroup,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(m){c(-1,m?.message||String(m));return}t.killGroup&&u.pid&&(At.add(u.pid),_c||(_c=!0,process.once("exit",$f)));let l=t.killGraceMs??Af,g=m=>{if(t.killGroup&&u.pid)try{process.kill(-u.pid,m);return}catch{}u.kill(m)};t.timeoutMs&&d.push(setTimeout(()=>{i=!0,g("SIGTERM"),d.push(setTimeout(()=>{g("SIGKILL"),d.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),c(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",m=>{r+=m}),u.stderr?.on("data",m=>{o+=m}),u.stdin?.on("error",()=>{}),u.on("error",m=>{u.pid&&At.delete(u.pid),c(-1,m.message)}),u.on("exit",()=>{if(t.killGroup&&u.pid){At.delete(u.pid);try{process.kill(-u.pid,"SIGKILL")}catch{}}}),u.on("close",m=>c(m??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var tt=async(n,e,t)=>{let s=await jc(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},Mf="Read,Glob,Grep,Write,Edit";function Cf(n){return["-p","-","--output-format","json","--tools",Mf,"--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 Ec(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 Fc=async n=>{let e=await jc("claude",Cf(n),{cwd:n.dir,env:ao(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:Ec(e.stdout,e.code).costUsd};let t=Ec(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 Hc(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 Wc(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 tr,mkdirSync as Rf,readdirSync as _f,statSync as Ef,utimesSync as Pf}from"fs";import{basename as Of,dirname as Df,join as $t,resolve as er}from"path";var Gc={enabled:!1,maxAgeDays:14};function Kc(n,e){if(!e)return null;if(n==="github"){let t=It(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 Nf(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function Lf(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 Jc(n,e,t=Qs){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(Lf(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 zc(n,e){return e.root?er(e.root):$t(Df(er(n)),".agentx-worktrees",Of(er(n)))}var nr=n=>n.trim().slice(0,300);async function Qc(n,e,t,s){let r=(g,m)=>s.exec("git",g,{cwd:m,timeoutMs:12e4}),o=Nf(n),i=zc(e,t),a=$t(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(tr($t(a,".git"))){let g=await r(["rev-parse","--abbrev-ref","HEAD"],a);return g.code===0&&g.stdout.trim()===o?(qc(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${g.code===0?` (it is on ${g.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: ${nr(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 g=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),m=`origin/${o}`;if(g.code!==0){let h=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);m=h.code===0&&h.stdout.trim()?h.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,m]}Rf(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${nr(l.stderr)}`}:(qc(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function qc(n,e){let t=new Date((e??Date.now)());try{Pf(n,t,t)}catch{}}async function Xc(n,e,t){let s=zc(n,e);if(!tr(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of _f(s)){let a=$t(s,i);if(a===t.keep||!tr($t(a,".git")))continue;let d;try{d=Ef(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}: ${nr(u.stderr)}`)}return o}function Yc(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 sr=["owner","critical","normal","background"],eu={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,waitNotice:{afterSeconds:120,channels:["gitlab"]},sampleSeconds:5,classes:{},closeIdle:{enabled:!0,maxPerRound:3,minQuietSeconds:60,settleSeconds:30},priority:{ownerChannels:["voice","app"],ownerPeople:[],criticalAgents:[],backgroundChannels:["cron","heartbeat","routine"]}},tu=n=>(n||"").toLowerCase().split("@")[0];function Bf(n,e){if(n.priority)return n.priority;let t=Uf(n,e);return n.atLeast&&sr.indexOf(n.atLeast)<sr.indexOf(t)?n.atLeast:t}function Uf(n,e){let t=tu(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 jf(n,e){if(n.class)return n.class;let t=tu(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 Vc(n,e){return n.maxSessions>0?n.maxSessions:Math.max(2,Math.round((e-2048)/1024))}function nu(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 Zc(n,e){let t=nu(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 su=["swap:","load:"];function Ff(n,e){return!(e==="critical"&&su.some(t=>n.startsWith(t)))}function rr(n){return n==="critical"?"critical":void 0}function xx(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=rr(n.priority);return t?{...e??{},admissionPriority:t}:e}var On=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:Bf(e,t),cls:jf(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:[],noticed:!1,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=>sr.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=Vc(e,t.memTotalMB),o=Zc(t,e);o.join()!==this.lastReasons.join()&&(this.log(o.length?`[admission] gate closed: ${o.join("; ")}`:"[admission] gate open"),this.lastReasons=o);let i="none",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 g=[],m=d.priority==="critical";(i==="all"||i==="soft"&&!m)&&g.push("behind earlier work");let h=d.priority==="owner"?e.ownerExtraSessions:0,y=r+Math.max(h,d.delegated?e.delegationHeadroom:0);this.running.size>=y&&g.push(`session cap: ${this.running.size}/${y} running`);let S=[],x=o.filter(w=>Ff(w,d.priority));x.length&&!(e.allowOneWhenIdle&&this.running.size===0)&&(S.push(...x),u.length||(a=!0));let C=x.length===o.length||e.allowOneWhenIdle&&this.running.size===0?[]:o.filter(w=>!x.includes(w)),N=this.paceWait(d.priority,e,s);if(N>0&&S.push(`start pace: next start in ${Math.ceil(N/1e3)}s`),g.push(...S),!e.enabled||e.mode==="observe"){if(e.enabled&&g.some(w=>w!=="behind earlier work")&&this.log(`[admission] observe: would hold ${d.agentId} (${d.priority}) \u2014 ${g.join("; ")}`),u.includes("agent busy")){d.blockedBy=u;continue}this.admitEntry(d,c);continue}if(u.length||g.length){d.blockedBy=[...g,...u],g.length?d.nodeHeldSince??=s:d.nodeHeldSince=null,S.length&&(i=S.every(v=>su.some(R=>v.startsWith(R)))&&i!=="all"?"soft":"all"),this.noticeLongWait(d,c);continue}this.admitEntry(d,c,C)}this.closeIdleRound(e,a?o:[],s)}noticeLongWait(e,t){let s=e.req.longWait;if(!(!s||e.noticed||s.afterMs<=0||t<s.afterMs)){e.noticed=!0;try{s.notify({waitedMs:t,blockedBy:[...e.blockedBy]})}catch(r){this.log(`[admission] ${e.agentId} long-wait notice failed: ${r?.message??r}`)}}}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=>me({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(me(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(me).join(", ")}`):this.log(`[admission] gate shut (${r.join("; ")}): closed ${d.length} idle session(s), ${this.waiting.length} waiting`)}admitEntry(e,t,s=[]){this.drop(e);try{e.req.onStart?.()}catch{}let r=this.start(e,t);s.length?this.log(`[admission] started ${e.agentId} (${e.priority}) past the gate (${s.join("; ")})${t>=1e3?` after ${Math.round(t/1e3)}s in the queue`:""}`):t>=1e3&&this.log(`[admission] started ${e.agentId} (${e.priority}) after ${Math.round(t/1e3)}s in the queue`),e.resolve({ok:!0,ticket:r})}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?Vc(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?Zc(s,e):[];return{enabled:e.enabled,mode:e.mode,checkedAt:s?new Date(s.at).toISOString():null,resources:s,limits:s?nu(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())}};function ru(n){let e=t=>n.some(s=>s.startsWith(t));return e("disk:")?"the machine that runs me is short of free disk space":e("memory:")||e("swap:")?"the machine that runs me is short of free memory":e("load:")?"the machine that runs me is very busy":e("session cap")||e("start pace")||e("behind earlier work")||e("class ")?"other work is ahead of it on the machine that runs me":e("agent busy")?"I am working on another request":"the machine that runs me has no room yet"}function kx(n){return`Received. I have not started yet because ${ru(n)}. Your request is in the queue and starts on its own when there is room; I will answer here. If it cannot start after a long wait, I will say so here.`}function ou(n){return`I could not start this request: ${ru(n)}, and that lasted too long. It is no longer in the queue. Please send it again.`}function Hf(n){let e=new Date(Math.ceil(n/6e4)*6e4);return`${String(e.getUTCHours()).padStart(2,"0")}:${String(e.getUTCMinutes()).padStart(2,"0")} UTC`}function Tx(n){return`Received, but I cannot start new work right now: the AI plan limit is reached. It is not queued. Please send it again ${n?`after ${Hf(n)}`:"later"}.`}import{execFile as Wf}from"child_process";import{readFile as qf,statfs as Gf}from"fs/promises";import{cpus as Kf,freemem as Jf,loadavg as zf,platform as Qf,totalmem as Xf}from"os";var Mt=1024*1024;function Yf(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/Mt)}function Vf(n){let e=r=>{let o=n.match(new RegExp(`${r}\\s*=\\s*([\\d.]+)([KMGT]?)`));if(!o)return null;let i={"":1/Mt,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 Zf(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 iu(n,e){return new Promise(t=>{Wf(n,e,{timeout:3e3},(s,r)=>t(s?"":String(r)))})}async function eh(n){let e=Math.round(Xf()/Mt),t=Math.round(Jf()/Mt),s=0,r=0,o=Qf(),i=o==="darwin";if(o==="darwin"){let[d,c]=await Promise.all([iu("vm_stat",[]),iu("sysctl",["-n","vm.swapusage"])]);t=Yf(d)??t;let u=Vf(c);u&&(s=u.totalMB,r=u.usedMB)}else if(o==="linux"){let d=Zf(await qf("/proc/meminfo","utf-8").catch(()=>""));d&&(t=d.availableMB,s=d.swapTotalMB,r=d.swapUsedMB)}let a=null;try{let d=await Gf(n);a=Math.round(Number(d.bavail)*Number(d.bsize)/Mt)}catch{}return{at:Date.now(),memTotalMB:e,memAvailableMB:t,swapTotalMB:s,swapUsedMB:r,swapGrows:i,diskFreeMB:a,load1:Math.round(zf()[0]*100)/100,cpuCount:Math.max(1,Kf().length)}}var Dn=class{constructor(e,t=3e3,s=eh){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 th=250,nh=5e3,ah={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3,"route-edge":5e3},dh=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),au=`[Operating principle]
143
+ `)}var ff=90*24*60*60*1e3,On=class{constructor(e){this.file=e}runs=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(Pc(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<ff);try{Zm(af(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;sf(t,JSON.stringify({runs:this.runs},null,2)),tf(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]}},hf=10*6e4;function Zs(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+hf))return"spec tests are already running for this issue"}}function Bc(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(!uf(`${t.title}
144
+ ${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=Zs(n.previous,e,n.now);return s?{run:!1,reason:s}:{run:!0,input:pf(t)}}function yf(n){return/(^|\/)(test|tests|__tests__|spec)\//.test(n)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(n)}function wf(n){return(n.match(/(^|[^\w.$])(it|test)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(/g)??[]).length}function bf(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 xf(n){let e=[],t=[];for(let s of n)s.status==="??"&&yf(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 Sf=[["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 kf(n){return Sf.filter(([,e])=>e.test(n)).map(([e])=>e)}var Tf=[".ssh",".gnupg",".aws",".config",".claude",".claude.json",".netrc",".git-credentials",".npmrc",".docker",".kube"],If=n=>`/${Vs(n).replace(/\\/g,"/").replace(/^\/+/,"")}`;function vf(n,e){let t=Vs(n),s=a=>t===a||t.startsWith(a.endsWith(Rc)?a:a+Rc),r=rf(),o=[...e,r,...Tf.map(a=>Ys(r,a)),"/proc"].map(a=>Vs(a)),i=[];for(let a of[...new Set(o)]){if(s(a))continue;let d=`/${If(a)}/**`;i.push(`Read(${d})`,`Edit(${d})`)}return i}async function jc(n){let{settings:e,input:t,exec:s}=n,r=n.now??Date.now,o=r(),i=Dc(t.number),a={repo:t.repo,number:t.number,agent:e.agent,codeAgent:n.codeAgent,startedAt:o},d,c=(l,g,m=12e4)=>s("git",l,{cwd:g,timeoutMs:m});n.store.record({...a,status:"running",finishedAt:o,minutes:0});let u=async l=>{let g=r(),m={...a,...l,finishedAt:g,minutes:Math.round((g-o)/6e4*10)/10};n.store.record(m);let h=m.costUsd===void 0?"cost not reported":`$${m.costUsd.toFixed(2)}`;if(n.log(`[spec-tests] ${t.repo}#${t.number}: ${m.status} in ${m.minutes} min, ${h}${m.note?` \u2014 ${m.note}`:""}`),m.status!=="pushed"&&m.note)try{await n.noteOnIssue($c(`Spec tests for #${t.number} (${e.agent}): ${m.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 m};try{let l=await c(["fetch","origin"],n.checkout);if(l.code!==0)return await u({status:"failed",note:`could not fetch the repository: ${l.stderr.trim().slice(0,300)}`});let g=await c(["symbolic-ref","--short","refs/remotes/origin/HEAD"],n.checkout),m=g.code===0&&g.stdout.trim()?g.stdout.trim():"origin/main";d=(n.makeTempDir??(()=>ef(Ys(of(),`agentx-spec-${t.number}-`))))();let h=await c(["worktree","add","--detach",d,m],n.checkout);if(h.code!==0)return await u({status:"failed",note:`could not create a clean worktree of ${m}: ${h.stderr.trim().slice(0,300)}`});let y=await n.runAgent({prompt:mf(t),dir:d,model:e.model,maxBudgetUsd:e.maxCostPerIssue,timeoutMs:e.maxMinutes*6e4,deny:vf(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 S=await c(["status","--porcelain","-z","--untracked-files=all"],d);if(S.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not list the files the test agent wrote: ${S.stderr.trim().slice(0,300)}`});let{keep:x,discard:C}=xf(bf(S.stdout));if(C.length&&n.log(`[spec-tests] ${t.repo}#${t.number}: discarded (only new test files are committed): ${C.join(", ")}`),!x.length)return await u({status:"no-tests",costUsd:y.costUsd,note:`the test agent wrote no new test file${C.length?` (its other changes were discarded: ${C.join(", ")})`:""}.`});let N=0,w=[];for(let M of x){let A=Pc(Ys(d,M),"utf8");N+=wf(A);for(let k of kf(A))w.push(`${k} in ${M}`)}if(w.length)return await u({status:"blocked",costUsd:y.costUsd,testFiles:x,note:`a written file looks like it holds a secret (${w.join(", ")}), so nothing was pushed. The operator should check what the test agent could read.`});let v=df(e.agent),R=["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`],_=await c(["add","--",...x],d);if(_.code!==0)return await u({status:"failed",costUsd:y.costUsd,note:`could not stage the tests: ${_.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).`,B=await c([...R,"commit","--no-verify","-m",Nc(t.number),"-m",L],d);if(B.code!==0)return await u({status:"failed",costUsd:y.costUsd,testFiles:x,note:`could not commit the tests: ${B.stderr.trim().slice(0,300)}`});let H=(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:H,note:`could not push ${i}: ${q.stderr.trim().slice(0,300)}`});let J=await u({status:"pushed",costUsd:y.costUsd,branch:i,commit:H,testFiles:x,testsWritten:N});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(M){n.log(`[spec-tests] ${t.repo}#${t.number}: could not tell the coding session: ${M?.message||M}`)}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{Vm(d)&&nf(d,{recursive:!0,force:!0})}catch{}}}}var Af=5e3,$t=new Set,_c=!1;function $f(){for(let n of $t)try{process.kill(-n,"SIGKILL")}catch{}$t.clear()}function Uc(n,e,t){return new Promise(s=>{let r="",o="",i=!1,a=!1,d=[],c=(m,h)=>{if(!a){a=!0;for(let y of d)clearTimeout(y);s({code:m,stdout:r,stderr:h??o,timedOut:i})}},u;try{u=Ym(n,e,{cwd:t.cwd,env:t.env,detached:t.killGroup,stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"]})}catch(m){c(-1,m?.message||String(m));return}t.killGroup&&u.pid&&($t.add(u.pid),_c||(_c=!0,process.once("exit",$f)));let l=t.killGraceMs??Af,g=m=>{if(t.killGroup&&u.pid)try{process.kill(-u.pid,m);return}catch{}u.kill(m)};t.timeoutMs&&d.push(setTimeout(()=>{i=!0,g("SIGTERM"),d.push(setTimeout(()=>{g("SIGKILL"),d.push(setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),c(-1)},l))},l))},t.timeoutMs)),u.stdout?.on("data",m=>{r+=m}),u.stderr?.on("data",m=>{o+=m}),u.stdin?.on("error",()=>{}),u.on("error",m=>{u.pid&&$t.delete(u.pid),c(-1,m.message)}),u.on("exit",()=>{if(t.killGroup&&u.pid){$t.delete(u.pid);try{process.kill(-u.pid,"SIGKILL")}catch{}}}),u.on("close",m=>c(m??-1)),t.input!==void 0&&u.stdin?.end(t.input)})}var tt=async(n,e,t)=>{let s=await Uc(n,e,t);return{code:s.code,stdout:s.stdout,stderr:s.stderr}},Mf="Read,Glob,Grep,Write,Edit";function Cf(n){return["-p","-","--output-format","json","--tools",Mf,"--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 Ec(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 Fc=async n=>{let e=await Uc("claude",Cf(n),{cwd:n.dir,env:ao(),input:n.prompt,timeoutMs:n.timeoutMs});if(e.timedOut)return{ok:!1,timedOut:!0,costUsd:Ec(e.stdout,e.code).costUsd};let t=Ec(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 Hc(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 Wc(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 tr,mkdirSync as Rf,readdirSync as _f,statSync as Ef,utimesSync as Pf}from"fs";import{basename as Of,dirname as Df,join as Mt,resolve as er}from"path";var Gc={enabled:!1,maxAgeDays:14};function Kc(n,e){if(!e)return null;if(n==="github"){let t=vt(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 Nf(n){return/^\d+$/.test(n.id)?`agentx/issue-${n.id}`:`agentx/${n.id.toLowerCase()}`}function Lf(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 Jc(n,e,t=Qs){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(Lf(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 zc(n,e){return e.root?er(e.root):Mt(Df(er(n)),".agentx-worktrees",Of(er(n)))}var nr=n=>n.trim().slice(0,300);async function Qc(n,e,t,s){let r=(g,m)=>s.exec("git",g,{cwd:m,timeoutMs:12e4}),o=Nf(n),i=zc(e,t),a=Mt(i,o.replace(/^agentx\//,"").replace(/[^A-Za-z0-9._-]+/g,"-"));if(tr(Mt(a,".git"))){let g=await r(["rev-parse","--abbrev-ref","HEAD"],a);return g.code===0&&g.stdout.trim()===o?(qc(a,s.now),{dir:a,branch:o,checkout:e,reused:!0}):{error:`${a} exists but is not on ${o}${g.code===0?` (it is on ${g.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: ${nr(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 g=await r(["rev-parse","--verify","--quiet",`refs/remotes/origin/${o}`],e),m=`origin/${o}`;if(g.code!==0){let h=await r(["symbolic-ref","--short","refs/remotes/origin/HEAD"],e);m=h.code===0&&h.stdout.trim()?h.stdout.trim():"origin/main"}u=["worktree","add","--no-track","-b",o,a,m]}Rf(i,{recursive:!0});let l=await r(u,e);return l.code!==0?{error:`could not create the worktree for ${o}: ${nr(l.stderr)}`}:(qc(a,s.now),{dir:a,branch:o,checkout:e,reused:!1})}function qc(n,e){let t=new Date((e??Date.now)());try{Pf(n,t,t)}catch{}}async function Xc(n,e,t){let s=zc(n,e);if(!tr(s))return[];let r=(t.now??Date.now)(),o=[];for(let i of _f(s)){let a=Mt(s,i);if(a===t.keep||!tr(Mt(a,".git")))continue;let d;try{d=Ef(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}: ${nr(u.stderr)}`)}return o}function Yc(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 sr=["owner","critical","normal","background"],eu={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,waitNotice:{afterSeconds:120,channels:["gitlab"]},sampleSeconds:5,classes:{},closeIdle:{enabled:!0,maxPerRound:3,minQuietSeconds:60,settleSeconds:30},priority:{ownerChannels:["voice","app"],ownerPeople:[],criticalAgents:[],backgroundChannels:["cron","heartbeat","routine"]}},tu=n=>(n||"").toLowerCase().split("@")[0];function Bf(n,e){if(n.priority)return n.priority;let t=jf(n,e);return n.atLeast&&sr.indexOf(n.atLeast)<sr.indexOf(t)?n.atLeast:t}function jf(n,e){let t=tu(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 Uf(n,e){if(n.class)return n.class;let t=tu(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 Vc(n,e){return n.maxSessions>0?n.maxSessions:Math.max(2,Math.round((e-2048)/1024))}function nu(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 Zc(n,e){let t=nu(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 su=["swap:","load:"];function Ff(n,e){return!(e==="critical"&&su.some(t=>n.startsWith(t)))}function rr(n){return n==="critical"?"critical":void 0}function xx(n){let e=n.context&&typeof n.context=="object"?n.context:void 0,t=rr(n.priority);return t?{...e??{},admissionPriority:t}:e}var Dn=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:Bf(e,t),cls:Uf(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:[],noticed:!1,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=>sr.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=Vc(e,t.memTotalMB),o=Zc(t,e);o.join()!==this.lastReasons.join()&&(this.log(o.length?`[admission] gate closed: ${o.join("; ")}`:"[admission] gate open"),this.lastReasons=o);let i="none",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 g=[],m=d.priority==="critical";(i==="all"||i==="soft"&&!m)&&g.push("behind earlier work");let h=d.priority==="owner"?e.ownerExtraSessions:0,y=r+Math.max(h,d.delegated?e.delegationHeadroom:0);this.running.size>=y&&g.push(`session cap: ${this.running.size}/${y} running`);let S=[],x=o.filter(w=>Ff(w,d.priority));x.length&&!(e.allowOneWhenIdle&&this.running.size===0)&&(S.push(...x),u.length||(a=!0));let C=x.length===o.length||e.allowOneWhenIdle&&this.running.size===0?[]:o.filter(w=>!x.includes(w)),N=this.paceWait(d.priority,e,s);if(N>0&&S.push(`start pace: next start in ${Math.ceil(N/1e3)}s`),g.push(...S),!e.enabled||e.mode==="observe"){if(e.enabled&&g.some(w=>w!=="behind earlier work")&&this.log(`[admission] observe: would hold ${d.agentId} (${d.priority}) \u2014 ${g.join("; ")}`),u.includes("agent busy")){d.blockedBy=u;continue}this.admitEntry(d,c);continue}if(u.length||g.length){d.blockedBy=[...g,...u],g.length?d.nodeHeldSince??=s:d.nodeHeldSince=null,S.length&&(i=S.every(v=>su.some(R=>v.startsWith(R)))&&i!=="all"?"soft":"all"),this.noticeLongWait(d,c);continue}this.admitEntry(d,c,C)}this.closeIdleRound(e,a?o:[],s)}noticeLongWait(e,t){let s=e.req.longWait;if(!(!s||e.noticed||s.afterMs<=0||t<s.afterMs)){e.noticed=!0;try{s.notify({waitedMs:t,blockedBy:[...e.blockedBy]})}catch(r){this.log(`[admission] ${e.agentId} long-wait notice failed: ${r?.message??r}`)}}}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=>me({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(me(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(me).join(", ")}`):this.log(`[admission] gate shut (${r.join("; ")}): closed ${d.length} idle session(s), ${this.waiting.length} waiting`)}admitEntry(e,t,s=[]){this.drop(e);try{e.req.onStart?.()}catch{}let r=this.start(e,t);s.length?this.log(`[admission] started ${e.agentId} (${e.priority}) past the gate (${s.join("; ")})${t>=1e3?` after ${Math.round(t/1e3)}s in the queue`:""}`):t>=1e3&&this.log(`[admission] started ${e.agentId} (${e.priority}) after ${Math.round(t/1e3)}s in the queue`),e.resolve({ok:!0,ticket:r})}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?Vc(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?Zc(s,e):[];return{enabled:e.enabled,mode:e.mode,checkedAt:s?new Date(s.at).toISOString():null,resources:s,limits:s?nu(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())}};function ru(n){let e=t=>n.some(s=>s.startsWith(t));return e("disk:")?"the machine that runs me is short of free disk space":e("memory:")||e("swap:")?"the machine that runs me is short of free memory":e("load:")?"the machine that runs me is very busy":e("session cap")||e("start pace")||e("behind earlier work")||e("class ")?"other work is ahead of it on the machine that runs me":e("agent busy")?"I am working on another request":"the machine that runs me has no room yet"}function kx(n){return`Received. I have not started yet because ${ru(n)}. Your request is in the queue and starts on its own when there is room; I will answer here. If it cannot start after a long wait, I will say so here.`}function ou(n){return`I could not start this request: ${ru(n)}, and that lasted too long. It is no longer in the queue. Please send it again.`}function Hf(n){let e=new Date(Math.ceil(n/6e4)*6e4);return`${String(e.getUTCHours()).padStart(2,"0")}:${String(e.getUTCMinutes()).padStart(2,"0")} UTC`}function Tx(n){return`Received, but I cannot start new work right now: the AI plan limit is reached. It is not queued. Please send it again ${n?`after ${Hf(n)}`:"later"}.`}import{execFile as Wf}from"child_process";import{readFile as qf,statfs as Gf}from"fs/promises";import{cpus as Kf,freemem as Jf,loadavg as zf,platform as Qf,totalmem as Xf}from"os";var Ct=1024*1024;function Yf(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/Ct)}function Vf(n){let e=r=>{let o=n.match(new RegExp(`${r}\\s*=\\s*([\\d.]+)([KMGT]?)`));if(!o)return null;let i={"":1/Ct,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 Zf(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 iu(n,e){return new Promise(t=>{Wf(n,e,{timeout:3e3},(s,r)=>t(s?"":String(r)))})}async function eh(n){let e=Math.round(Xf()/Ct),t=Math.round(Jf()/Ct),s=0,r=0,o=Qf(),i=o==="darwin";if(o==="darwin"){let[d,c]=await Promise.all([iu("vm_stat",[]),iu("sysctl",["-n","vm.swapusage"])]);t=Yf(d)??t;let u=Vf(c);u&&(s=u.totalMB,r=u.usedMB)}else if(o==="linux"){let d=Zf(await qf("/proc/meminfo","utf-8").catch(()=>""));d&&(t=d.availableMB,s=d.swapTotalMB,r=d.swapUsedMB)}let a=null;try{let d=await Gf(n);a=Math.round(Number(d.bavail)*Number(d.bsize)/Ct)}catch{}return{at:Date.now(),memTotalMB:e,memAvailableMB:t,swapTotalMB:s,swapUsedMB:r,swapGrows:i,diskFreeMB:a,load1:Math.round(zf()[0]*100)/100,cpuCount:Math.max(1,Kf().length)}}var Nn=class{constructor(e,t=3e3,s=eh){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 th=250,nh=5e3,ah={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3,"route-edge":5e3},dh=new Set(["requests","a2a","api","cron","workflow","test","mesh","subagent","mcp","events","reminder","heartbeat","system","internal","business","selftest","compaction"]),au=`[Operating principle]
145
145
  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.`,ch="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 uh(n){return n==="claude-code"?`${au}
146
146
  ${ch}`:n==="codex-cli"?au:""}function du(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var mu;function a0(n){mu=n}function d0(){return mu}function lh(n){let e=n.split(`
147
- `);for(let t=e.length-1;t>=0;t--){let s=So(e[t].trim());if(s)return s.length>160?s.slice(0,159)+"\u2026":s}}var cu=64*1024,gh=5*60*1e3,ph=3e4,mh=300,fh=25*6e4,nt=".agentx/task-history",hh=30;function Rt(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function yh(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 wh(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=Wo(n,e,Z().recent());return Go(t,s)}function bh(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 xh(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",g=r.get(l)||[];g.push(u.meta.title),r.set(l,g)}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(`
147
+ `);for(let t=e.length-1;t>=0;t--){let s=So(e[t].trim());if(s)return s.length>160?s.slice(0,159)+"\u2026":s}}var cu=64*1024,gh=5*60*1e3,ph=3e4,mh=300,fh=25*6e4,nt=".agentx/task-history",hh=30;function _t(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function yh(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 wh(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=Wo(n,e,Z().recent());return Go(t,s)}function bh(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 xh(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",g=r.get(l)||[];g.push(u.meta.title),r.set(l,g)}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(`
148
148
  `),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:
149
149
  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(`
150
150
  `)}var or=8*1024;function Sh(n,e){if(n)try{wi(n)}catch{}return e}function uu(n){if(n.length<=or)return n;let e=n.length-or;return n.slice(0,or)+`\u2026[+${e}]`}function lu(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 kh(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 gu(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=Z();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?uu(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?uu(a):null,at:r})}return}}function Th(){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
@@ -159,45 +159,45 @@ ${ch}`:n==="codex-cli"?au:""}function du(n,e){return e!=="claude-code"&&e!=="cod
159
159
  `;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}`:""}
160
160
  `}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`
161
161
  > codex ${o}${i?` ${i}`:""}
162
- `;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${Rt(String(a),800)}`:""}
163
- `}if(s==="error"||s==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${Rt(String(r),800)}
162
+ `;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${_t(String(a),800)}`:""}
163
+ `}if(s==="error"||s==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${_t(String(r),800)}
164
164
  `}if(s==="system"&&t.subtype==="init"){let r=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${r}${o}
165
165
  `}if(s==="assistant"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>n.length&&(r+=o.text.slice(n.length),n=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")r+=`
166
- \u{1F4AD} ${Rt(o.thinking,600)}
167
- `;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?Rt(JSON.stringify(o.input),400):"";r+=`
166
+ \u{1F4AD} ${_t(o.thinking,600)}
167
+ `;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?_t(JSON.stringify(o.input),400):"";r+=`
168
168
  \u2192 ${i}(${a})
169
- `}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}${Rt(i,800)}
169
+ `}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}${_t(i,800)}
170
170
  `}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
171
- `:""}}var pu=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Po;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;admission;admissionTickets=new WeakMap;voiceClaims=new Set;midTurn=new Zt;workLanes=new xn({log:e=>this.log(e)});notices=new Sn;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new _o;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;jobStates=new Map;jobStateListener;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 fn(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new $o(void 0,void 0,"graph"),this.memoryStore=new Eo,this.patternStore=new bn,this.rateLimiter=new hn,this.tokenTracker=new Co,this.messageQueue=new yn,this.messageQueue.wasTaken=s=>this.midTurn.isTaken(s),this.admission=new On(()=>this.admissionSettings(),new Dn(ae(G(process.cwd(),".agentx"))?G(process.cwd(),".agentx"):process.cwd()),s=>this.log(s),Date.now,s=>ut()?.closeIdle(s)??[]),Id({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),Qo(Yo(e)),Xo(ei(e)),this.budgetHolds=new Tn(Ls,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 vo({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Ao({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}recordJobState(e,t){return this.runningTaskOwner(e)?(this.jobStates.set(e,t),!0):!1}setJobStateListener(e){this.jobStateListener=e}tellJobState(e,t){try{this.jobStateListener?.(e,t)}catch(s){this.log(`[job-state] ledger write failed: ${s?.message??s}`)}}takeJobState(e,t){let s=e.runningTaskId,r=s?this.jobStates.get(s):void 0;return s&&this.jobStates.delete(s),r??wt(t.content)}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}admissionSettings(){let e=this.config.admission??eu;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=Vr(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 hi(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 g=this.sessions.getSession(e.agentId,s,r);i=Ea(g.messages,e.message??""),d=Pa(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.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 pe(Gi,Ji(c),Ki,{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"||!zi(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),Z().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(`
172
- `)[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 _n(G(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...En,...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=It(t.context?.chatId),a=this.cloudSessionStore();return Tc({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={...En,...e.cloudSessions??{}},i=Date.now(),a=Le(ft(ze(e.workspace),t),e.billing),d=l=>vc({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),c=await this.planSpecTests(t.agentId,s),u=await Ac({route:s,agentId:t.agentId,message:c?`${t.message}
171
+ `:""}}var pu=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Po;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;runNote;traceToolCalls;workflowAutoRunner;workflowRuns;messageQueue;admission;admissionTickets=new WeakMap;voiceClaims=new Set;midTurn=new en;workLanes=new Sn({log:e=>this.log(e)});notices=new kn;budgetHolds;budgetReleaseTimer=null;classifier;graphStore;handoverStore=new _o;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;jobStates=new Map;jobStateListener;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 hn(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new $o(void 0,void 0,"graph"),this.memoryStore=new Eo,this.patternStore=new xn,this.rateLimiter=new yn,this.tokenTracker=new Co,this.messageQueue=new wn,this.messageQueue.wasTaken=s=>this.midTurn.isTaken(s),this.admission=new Dn(()=>this.admissionSettings(),new Nn(ae(G(process.cwd(),".agentx"))?G(process.cwd(),".agentx"):process.cwd()),s=>this.log(s),Date.now,s=>ut()?.closeIdle(s)??[]),Id({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),Qo(Yo(e)),Xo(ei(e)),this.budgetHolds=new In(Bs,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 vo({baseDir:G(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Ao({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}recordJobState(e,t){return this.runningTaskOwner(e)?(this.jobStates.set(e,t),!0):!1}setJobStateListener(e){this.jobStateListener=e}tellJobState(e,t){try{this.jobStateListener?.(e,t)}catch(s){this.log(`[job-state] ledger write failed: ${s?.message??s}`)}}takeJobState(e,t){let s=e.runningTaskId,r=s?this.jobStates.get(s):void 0;return s&&this.jobStates.delete(s),r??wt(t.content)}setTraceToolCalls(e){this.traceToolCalls=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}admissionSettings(){let e=this.config.admission??eu;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=Vr(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 hi(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 g=this.sessions.getSession(e.agentId,s,r);i=Ea(g.messages,e.message??""),d=Pa(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.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 pe(Gi,Ji(c),Ki,{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"||!zi(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),Z().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(`
172
+ `)[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 En(G(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Pn,...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=vt(t.context?.chatId),a=this.cloudSessionStore();return Tc({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={...Pn,...e.cloudSessions??{}},i=Date.now(),a=Le(ft(ze(e.workspace),t),e.billing),d=l=>vc({...l,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),c=await this.planSpecTests(t.agentId,s),u=await Ac({route:s,agentId:t.agentId,message:c?`${t.message}
173
173
  ${Lc(c.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d,log:l=>this.log(l),trace:l=>{try{Z().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&&!Zs(this.specTestStore().get(c.repo,c.number),this.specTestSettings())){let l=u.cloudSession.id;this.startSpecTests(t.agentId,c,s.cwd,g=>d({cwd:s.cwd,prompt:g,sessionId:l}).then(m=>{if(!m.ok)throw new Error(m.reason)}))}return{content:u.content,error:u.error,cloudSession:u.cloudSession,duration:Date.now()-i}}async inTaskWorktree(e,t){let s={...Gc,...e.worktrees??{}};if(!s.enabled)return{def:e,task:t};let r=Kc(t.context?.channel,t.context?.chatId);if(!r)return{def:e,task:t};let o=`${r.repo?`${r.repo}#`:""}${r.id}`,i=Jc(r,[t.context?.runbookPath,e.workspace].filter(g=>!!g));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=Qc(r,i.dir,s,{exec:tt,log:g=>this.log(g)}),this.worktreesPending.set(a,d),d.finally(()=>this.worktreesPending.delete(a)).catch(()=>{}));let c;try{c=await d}catch(g){c={error:g?.message||String(g)}}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()),Xc(i.dir,s,{exec:tt,log:g=>this.log(g),keep:c.dir}).then(g=>{g.length&&this.log(`[worktrees] removed ${g.length} unused worktree(s): ${g.join(", ")}`)}).catch(g=>this.log(`[worktrees] prune failed: ${g?.message||g}`)));let l=Yc(c);return{fresh:!c.reused,def:{...e,persistentProcess:!1},task:{...t,cwd:c.dir,systemPromptAppend:t.systemPromptAppend?`${t.systemPromptAppend}
174
174
 
175
- ${l}`:l}}}specTestSettings(){return{...Oc,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new Pn(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 Hc(tt,t.repo,t.number,t.cwd),o=Bc({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 Uc({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:tt,runAgent:Fc,store:this.specTestStore(),noteOnIssue:o=>Wc(tt,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=We(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=gd(e.message,o);if(ld(o)&&!e.preSpawnRetry&&!e.timeLimitContinuation){let c=this.notices.take(e.agentId);c&&(e={...e,message:c+e.message})}if(vs(this.config.jobState,o)&&!e.jobStateAsk&&(e={...e,message:Qa+e.message}),!i)return this.runWithRecovery(e,t,s,r);let a=await this.workLanes.enter(e.agentId,i,dt()?.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&&$e(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=Wa({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??Is});if(u.action==="continue"){let l=this.config.resume?.timeLimit??Is,g=e.taskId,m=[];try{m=g&&this.traceToolCalls?this.traceToolCalls(g):[]}catch{}let h=Ga(u.minutes,m,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${g??"-"}: 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}
176
- ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:g??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:qa(i.error,u.reason)}),e.jobStateAsk||(i=await this.checkJobState(e,i)),e.intentRef)try{let l=i.error?$e(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Bo().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 checkJobState(e,t){let s=e.context?.channel,r=e.runningTaskId;if(!vs(this.config.jobState,s)||t.error||t.viaMesh||t.midTurnDelivered)return r&&this.jobStates.delete(r),t;let o=`${e.agentId} ${s??"-"} ${e.taskId??"-"}`,i=Ja(s),a=w=>{if(!i){let R=wt(t.content)?As(t.content??""):t.content;return{...t,content:R,jobState:w}}if(wt(t.content))return{...t,jobState:w};let v=`[Job state] ${bt(w)}`;return{...t,content:t.content?`${t.content}
175
+ ${l}`:l}}}specTestSettings(){return{...Oc,...this.config.quality?.specTests??{}}}specTestStore(){return this.specTests||(this.specTests=new On(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 Hc(tt,t.repo,t.number,t.cwd),o=Bc({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 jc({settings:this.specTestSettings(),input:t,codeAgent:e,checkout:s,exec:tt,runAgent:Fc,store:this.specTestStore(),noteOnIssue:o=>Wc(tt,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=We(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=gd(e.message,o);if(ld(o)&&!e.preSpawnRetry&&!e.timeLimitContinuation){let c=this.notices.take(e.agentId);c&&(e={...e,message:c+e.message})}if(As(this.config.jobState,o)&&!e.jobStateAsk&&(e={...e,message:Qa+e.message}),!i)return this.runWithRecovery(e,t,s,r);let a=await this.workLanes.enter(e.agentId,i,dt()?.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&&$e(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=Wa({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??vs});if(u.action==="continue"){let l=this.config.resume?.timeLimit??vs,g=e.taskId,m=[];try{m=g&&this.traceToolCalls?this.traceToolCalls(g):[]}catch{}let h=Ga(u.minutes,m,u.continuation>=l.maxContinuations);this.log(`[resume] ${e.agentId} ${e.context?.channel??"-"} ${g??"-"}: 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}
176
+ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt:e.timeLimitStartedAt??o,...u.timeoutMinutes?{timeoutMinutes:u.timeoutMinutes}:{},resumedFrom:g??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:qa(i.error,u.reason)}),e.jobStateAsk||(i=await this.checkJobState(e,i)),e.intentRef)try{let l=i.error?$e(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Bo().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 checkJobState(e,t){let s=e.context?.channel,r=e.runningTaskId;if(!As(this.config.jobState,s)||t.error||t.viaMesh||t.midTurnDelivered)return r&&this.jobStates.delete(r),t;let o=`${e.agentId} ${s??"-"} ${e.taskId??"-"}`,i=Ja(s),a=w=>{if(!i){let R=wt(t.content)?$s(t.content??""):t.content;return{...t,content:R,jobState:w}}if(wt(t.content))return{...t,jobState:w};let v=`[Job state] ${bt(w)}`;return{...t,content:t.content?`${t.content}
177
177
 
178
- ${v}`:v,jobState:w}},d=[e.taskId,r],c=As(t.content??"");if(Do(No(c))){let w=this.takeJobState(e,t)??{state:"done",proof:"nothing to report"};return this.log(`[job-state] ${o}: ${bt(w)} (quiet answer)`),this.tellJobState(d,{kind:"stated",state:w}),{...t,content:c,jobState:w}}let u=this.takeJobState(e,t);if(u)return this.log(`[job-state] ${o}: ${bt(u)}`),this.tellJobState(d,{kind:"stated",state:u}),a(u);this.log(`[job-state] ${o}: ended with no state; asking once`),this.tellJobState(d,{kind:"asked"});let{intentRef:l,timeLimitRequest:g,timeLimitContinuation:m,timeLimitStartedAt:h,...y}=e,S={...y,message:Xa,jobStateAsk:!0,runningTaskId:void 0,freshSession:!1,resumedFrom:e.taskId??e.resumedFrom},x;try{x=await this.runWithRecovery(S)}catch(w){x={content:"",error:w?.message??String(w)}}let C=x.error?null:this.takeJobState(S,x);if(S.runningTaskId&&this.jobStates.delete(S.runningTaskId),C)return this.log(`[job-state] ${o}: ${bt(C)} (when asked)`),this.tellJobState([...d,S.taskId,S.runningTaskId],{kind:"stated",state:C}),a(C);if(this.log(`[job-state] ${o}: no state when asked${x.error?` (${x.error.slice(0,120)})`:""}; stalled`),this.tellJobState([...d,S.taskId,S.runningTaskId],{kind:"stalled",reason:"run ended with no state, and gave none when asked"}),Kt({kind:"job_stalled",agentId:e.agentId,ref:e.taskId??r??"-",detail:`${s??"-"}: run ended with no job state, none when asked`}),!i)return{...t,jobState:{state:"stalled"}};let N=Ya(e.agentId);return{...t,content:t.content?`${t.content}
178
+ ${v}`:v,jobState:w}},d=[e.taskId,r],c=$s(t.content??"");if(Do(No(c))){let w=this.takeJobState(e,t)??{state:"done",proof:"nothing to report"};return this.log(`[job-state] ${o}: ${bt(w)} (quiet answer)`),this.tellJobState(d,{kind:"stated",state:w}),{...t,content:c,jobState:w}}let u=this.takeJobState(e,t);if(u)return this.log(`[job-state] ${o}: ${bt(u)}`),this.tellJobState(d,{kind:"stated",state:u}),a(u);this.log(`[job-state] ${o}: ended with no state; asking once`),this.tellJobState(d,{kind:"asked"});let{intentRef:l,timeLimitRequest:g,timeLimitContinuation:m,timeLimitStartedAt:h,...y}=e,S={...y,message:Xa,jobStateAsk:!0,runningTaskId:void 0,freshSession:!1,resumedFrom:e.taskId??e.resumedFrom},x;try{x=await this.runWithRecovery(S)}catch(w){x={content:"",error:w?.message??String(w)}}let C=x.error?null:this.takeJobState(S,x);if(S.runningTaskId&&this.jobStates.delete(S.runningTaskId),C)return this.log(`[job-state] ${o}: ${bt(C)} (when asked)`),this.tellJobState([...d,S.taskId,S.runningTaskId],{kind:"stated",state:C}),a(C);if(this.log(`[job-state] ${o}: no state when asked${x.error?` (${x.error.slice(0,120)})`:""}; stalled`),this.tellJobState([...d,S.taskId,S.runningTaskId],{kind:"stalled",reason:"run ended with no state, and gave none when asked"}),Jt({kind:"job_stalled",agentId:e.agentId,ref:e.taskId??r??"-",detail:`${s??"-"}: run ended with no job state, none when asked`}),!i)return{...t,jobState:{state:"stalled"}};let N=Ya(e.agentId);return{...t,content:t.content?`${t.content}
179
179
 
180
- ${N}`:N,jobState:{state:"stalled"}}}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=we(e.autonomy),a=Zr(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:yd().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 p=await d;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let 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 p=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(I=>I.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:p.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=ht(e.context),g,m=u==="app"&&e.context?.via==="voice",h=Zo(Vo(),e.agentId);if(h)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:h,errorKind:"agent_held"};if(!i){let p=e.context?.channel,f=e.context?.chatId,I=Xt(e.agentId,void 0,Qt(e.agentId,f));if(I&&p&&f&&!Tt(e.context)&&rs()?.getChannel(p)){let $=this.budgetHolds.hold(e.agentId,{text:e.message,channel:p,chatId:String(f),context:e.context,heldAt:e.queuedAt??Date.now()});if($!=="full"){this.armBudgetRelease();let F=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${F} waiting) chat=${p}:${f}`),$==="held"?{content:"",error:es("budget",F)}:{content:"",error:`${I.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(this.offerMidTurn(e,c,u,l),u==="app"){let p=await this.waitForChat(e.agentId,u,l,e);if(typeof p!="string")return p;g=p}let y=()=>{g&&this.voiceClaims.delete(g)};if(c.activeTasks>=c.def.maxConcurrent)if(u==="api"||u==="app"&&!m||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i||Tt(e.context)){let p=Date.now(),f=e.slotWaitMs??fh,I=500,$=f<6e4?`${Math.max(1,Math.ceil(f/1e3))}s`:`${Math.round(f/6e4)}m`;for(c.activeTasks>=c.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${$}) behind=${c.runningTasks.map(F=>F.id).join(",")||"-"} chat=${u}:${l}`);c.activeTasks>=c.def.maxConcurrent;){if(e.callerSignal?.aborted)return y(),this.callerGone(e,"slot wait");if(Date.now()-p>f)return y(),this.log(`[${e.agentId}] slot wait timed out after ${$} chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${$}`,errorKind:"agent_busy"};await new Promise(F=>setTimeout(F,I))}Date.now()-p>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-p)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"||m){if(!g){let p=await this.waitForChat(e.agentId,u,l);if(typeof p!="string")return p;g=p}}else{let p=c.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,l,{...e.midTurnId?{midTurnId:e.midTurnId}:{},text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let I=this.messageQueue.pendingCount(e.agentId,u,l);return Z().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Vn(e.context),humanRoot:Ke(e.context),person:Jt(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${I}) behind=${c.runningTasks.map($=>$.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:es(f,I)}}}let S=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,f)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!S.ok)return y(),this.log(`[${e.agentId}] ${S.reason}`),{content:"",error:S.reason};if(e.callerSignal?.aborted)return y(),this.callerGone(e,"rate-limit wait");if(this.midTurn.isTaken(e.midTurnId))return y(),this.log(`[${e.agentId}] message ${e.midTurnId} was read by the running turn; not run again chat=${u}:${l}`),{content:u==="voice"||m?xi:bi,midTurnDelivered:!0};let x=this.admissionSettings();if(x.tiers.includes(c.def.tier)){let p=Jt(this.config.people,e.context),f=u==="voice"?`${e.agentId}\0${l}`:null,I=await this.admission.admit({agentId:e.agentId,channel:u,chatId:l,person:p?.id??null,owner:p?.role==="owner",...rr(e.context?.admissionPriority)?{atLeast:"critical"}:{},delegated:Jr(e.context)&&!e.context?.delegation,keepOnClose:e.origin?.kind==="router",...e.onHeld&&(x.waitNotice?.afterSeconds??0)>0?{longWait:{afterMs:x.waitNotice.afterSeconds*1e3,notify:e.onHeld}}:{},canStart:()=>c.activeTasks<c.def.maxConcurrent&&!(f&&f!==g&&(this.voiceClaims.has(f)||this.messageQueue.isBusy(e.agentId,u,l))),onStart:()=>{c.activeTasks++,f&&!g&&(g=f,this.voiceClaims.add(f))},signal:e.callerSignal});if(y(),!I.ok)return I.reason==="caller-gone"?this.callerGone(e,"node queue"):I.reason==="closed"?{content:"",error:`Agent "${e.agentId}" not started: the daemon is restarting`,errorKind:"interrupted"}:{content:"",error:ou(I.blockedBy),errorKind:"no_room"};this.admissionTickets.set(e,I.ticket)}else y(),c.activeTasks++;if(e.queuedAt!==void 0){let p=Za(e.queuedAt);p&&(e.message=`${p}
180
+ ${N}`:N,jobState:{state:"stalled"}}}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=we(e.autonomy),a=Zr(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:yd().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 p=await d;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let 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 p=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(I=>I.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:p.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=ht(e.context),g,m=u==="app"&&e.context?.via==="voice",h=Zo(Vo(),e.agentId);if(h)return this.log(`[${e.agentId}] refused \u2014 on hold`),{content:"",error:h,errorKind:"agent_held"};if(!i){let p=e.context?.channel,f=e.context?.chatId,I=Yt(e.agentId,void 0,Xt(e.agentId,f));if(I&&p&&f&&!It(e.context)&&os()?.getChannel(p)){let $=this.budgetHolds.hold(e.agentId,{text:e.message,channel:p,chatId:String(f),context:e.context,heldAt:e.queuedAt??Date.now()});if($!=="full"){this.armBudgetRelease();let F=this.budgetHolds.count(e.agentId);return this.log(`[${e.agentId}] over budget \u2014 message held (${F} waiting) chat=${p}:${f}`),$==="held"?{content:"",error:ts("budget",F)}:{content:"",error:`${I.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(this.offerMidTurn(e,c,u,l),u==="app"){let p=await this.waitForChat(e.agentId,u,l,e);if(typeof p!="string")return p;g=p}let y=()=>{g&&this.voiceClaims.delete(g)};if(c.activeTasks>=c.def.maxConcurrent)if(u==="api"||u==="app"&&!m||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||u==="sprint"||i||It(e.context)){let p=Date.now(),f=e.slotWaitMs??fh,I=500,$=f<6e4?`${Math.max(1,Math.ceil(f/1e3))}s`:`${Math.round(f/6e4)}m`;for(c.activeTasks>=c.def.maxConcurrent&&this.log(`[${e.agentId}] busy, waiting for a slot (up to ${$}) behind=${c.runningTasks.map(F=>F.id).join(",")||"-"} chat=${u}:${l}`);c.activeTasks>=c.def.maxConcurrent;){if(e.callerSignal?.aborted)return y(),this.callerGone(e,"slot wait");if(Date.now()-p>f)return y(),this.log(`[${e.agentId}] slot wait timed out after ${$} chat=${u}:${l} \u2014 message not run`),{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${$}`,errorKind:"agent_busy"};await new Promise(F=>setTimeout(F,I))}Date.now()-p>=6e4&&this.log(`[${e.agentId}] slot free after ${Math.round((Date.now()-p)/6e4)}m wait chat=${u}:${l}`)}else if(u==="voice"||m){if(!g){let p=await this.waitForChat(e.agentId,u,l);if(typeof p!="string")return p;g=p}}else{let p=c.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,l,{...e.midTurnId?{midTurnId:e.midTurnId}:{},text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let I=this.messageQueue.pendingCount(e.agentId,u,l);return Z().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Zn(e.context),humanRoot:Ke(e.context),person:zt(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${I}) behind=${c.runningTasks.map($=>$.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:ts(f,I)}}}let S=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,f)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!S.ok)return y(),this.log(`[${e.agentId}] ${S.reason}`),{content:"",error:S.reason};if(e.callerSignal?.aborted)return y(),this.callerGone(e,"rate-limit wait");if(this.midTurn.isTaken(e.midTurnId))return y(),this.log(`[${e.agentId}] message ${e.midTurnId} was read by the running turn; not run again chat=${u}:${l}`),{content:u==="voice"||m?xi:bi,midTurnDelivered:!0};let x=this.admissionSettings();if(x.tiers.includes(c.def.tier)){let p=zt(this.config.people,e.context),f=u==="voice"?`${e.agentId}\0${l}`:null,I=await this.admission.admit({agentId:e.agentId,channel:u,chatId:l,person:p?.id??null,owner:p?.role==="owner",...rr(e.context?.admissionPriority)?{atLeast:"critical"}:{},delegated:Jr(e.context)&&!e.context?.delegation,keepOnClose:e.origin?.kind==="router",...e.onHeld&&(x.waitNotice?.afterSeconds??0)>0?{longWait:{afterMs:x.waitNotice.afterSeconds*1e3,notify:e.onHeld}}:{},canStart:()=>c.activeTasks<c.def.maxConcurrent&&!(f&&f!==g&&(this.voiceClaims.has(f)||this.messageQueue.isBusy(e.agentId,u,l))),onStart:()=>{c.activeTasks++,f&&!g&&(g=f,this.voiceClaims.add(f))},signal:e.callerSignal});if(y(),!I.ok)return I.reason==="caller-gone"?this.callerGone(e,"node queue"):I.reason==="closed"?{content:"",error:`Agent "${e.agentId}" not started: the daemon is restarting`,errorKind:"interrupted"}:{content:"",error:ou(I.blockedBy),errorKind:"no_room"};this.admissionTickets.set(e,I.ticket)}else y(),c.activeTasks++;if(e.queuedAt!==void 0){let p=Za(e.queuedAt);p&&(e.message=`${p}
181
181
  ${e.message}`),e.queuedAt=void 0}let C=sd({message:e.message,home:e.context?.home}),N=nd(c.runningTasks,C,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});N&&(this.log(`[${e.agentId}] ${N.slice(0,160)}`),e.message=`${N}
182
- ${e.message}`),c.totalTasks++,c.lastActive=new Date;let w={...C.length?{homes:C}:{},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(w),e.runningTaskId=w.id;let v=Jt(this.config.people,e.context);if(e.context&&(v?e.context.person=v.id:delete e.context.person),this.runningContexts.set(w.id,e.context??{}),e.onStart)try{e.onStart(w.id)}catch{}let R=new AbortController;this.taskAborts.set(w.id,{agentId:e.agentId,channel:w.channel,chatId:typeof w.chatId=="string"?w.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:dt()?.rootId,workflowRunId:e.workflowRunId??(typeof w.chatId=="string"&&w.chatId.startsWith("workflow:")&&w.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let _={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(w.id,_);let L=p=>{if(p){_.buffer+=p,_.buffer.length>cu&&(_.buffer=_.buffer.slice(_.buffer.length-cu));for(let f of _.subscribers)try{f(p)}catch{}}},B=Ge();e.taskId=B,w.traceId=B;let H=this.taskAborts.get(w.id);H&&(H.traceId=B);let q=new Map,J=(p,f,I)=>{try{Z().emit("task:step",{taskId:B,agentId:e.agentId,name:"pipeline",action:p,status:I,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},M=0,A=!1,k=()=>{A||(A=!0,M&&J("first-event",M,"ok"))},U;if(t){let p=Th();U=f=>{k();let I=p(f);if(I&&L(I),gu(B,e.agentId,f),lu(q,f),Ns(f,void 0,e.model||c.def.model),Ds(f,void 0,e.agentId),r)try{r(f)}catch{}}}else U=p=>{if(k(),gu(B,e.agentId,p),lu(q,p),Ns(p,void 0,e.model||c.def.model),Ds(p,void 0,e.agentId),r)try{r(p)}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??mh)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${w.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`,ne;R.signal.addEventListener("abort",()=>{let p=We(R.signal).message;/^timed out/.test(p)&&(ne=w.step??"start"),this.log(`[${e.agentId}] task ${w.id} aborted in step "${w.step??"start"}" \u2014 ${p} ${D()}`)},{once:!0});let ee=p=>{w.step=p,this.log(`[${e.agentId}] step ${p} ${D()}`)},le=(p,f,I=0)=>{if(R.signal.aborted)return Promise.reject(We(R.signal));ee(p),(p==="agent"||p==="workflow-auto-run")&&(oe(),M=Date.now());let $=Date.now(),F=kc(f(),ah[p]??0,p);return Sc(F,R.signal,I).then(K=>(J(p,$,"ok"),K),K=>{throw J(p,$,"error"),K instanceof et&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},_t=async(p,f,I,$=0)=>{try{return await le(p,f,$)}catch(F){if(F instanceof et)return I();throw F}},ir=!1,Nn=!1,ar=p=>{if(!(!ir||Nn)){Nn=!0;try{Z().emit("task:completed",{taskId:B,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-w.startedAt.getTime(),error:p?.error||(R.signal.aborted?We(R.signal).message:"run ended before completion"),errorKind:p?.errorKind,interrupted:this.interruptedRuns.has(w.id)?!0:void 0,stopped:!this.interruptedRuns.has(w.id)&&(this.stoppedRuns.has(w.id)||p?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},dr=!1,cr=p=>{if(dr)return;dr=!0,ar(p),this.runReleases.delete(w.id),P&&clearTimeout(P),oe(),c.activeTasks--,this.admissionTickets.get(e)?.release();let f=c.runningTasks.findIndex($=>$.id===w.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(w.id),this.taskAborts.delete(w.id);let I=this.runEndWaiters.get(w.id);this.runEndWaiters.delete(w.id);for(let $ of I??[])try{$()}catch{}_.done=!0,_.endedAt=new Date;for(let $ of _.subscribers)try{$(`
182
+ ${e.message}`),c.totalTasks++,c.lastActive=new Date;let w={...C.length?{homes:C}:{},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(w),e.runningTaskId=w.id;let v=zt(this.config.people,e.context);if(e.context&&(v?e.context.person=v.id:delete e.context.person),this.runningContexts.set(w.id,e.context??{}),e.onStart)try{e.onStart(w.id)}catch{}let R=new AbortController;this.taskAborts.set(w.id,{agentId:e.agentId,channel:w.channel,chatId:typeof w.chatId=="string"?w.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:dt()?.rootId,workflowRunId:e.workflowRunId??(typeof w.chatId=="string"&&w.chatId.startsWith("workflow:")&&w.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let _={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(w.id,_);let L=p=>{if(p){_.buffer+=p,_.buffer.length>cu&&(_.buffer=_.buffer.slice(_.buffer.length-cu));for(let f of _.subscribers)try{f(p)}catch{}}},B=Ge();e.taskId=B,w.traceId=B;let H=this.taskAborts.get(w.id);H&&(H.traceId=B);let q=new Map,J=(p,f,I)=>{try{Z().emit("task:step",{taskId:B,agentId:e.agentId,name:"pipeline",action:p,status:I,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},M=0,A=!1,k=()=>{A||(A=!0,M&&J("first-event",M,"ok"))},j;if(t){let p=Th();j=f=>{k();let I=p(f);if(I&&L(I),gu(B,e.agentId,f),lu(q,f),Ls(f,void 0,e.model||c.def.model),Ns(f,void 0,e.agentId),r)try{r(f)}catch{}}}else j=p=>{if(k(),gu(B,e.agentId,p),lu(q,p),Ls(p,void 0,e.model||c.def.model),Ns(p,void 0,e.agentId),r)try{r(p)}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??mh)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${w.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`,ne;R.signal.addEventListener("abort",()=>{let p=We(R.signal).message;/^timed out/.test(p)&&(ne=w.step??"start"),this.log(`[${e.agentId}] task ${w.id} aborted in step "${w.step??"start"}" \u2014 ${p} ${D()}`)},{once:!0});let ee=p=>{w.step=p,this.log(`[${e.agentId}] step ${p} ${D()}`)},le=(p,f,I=0)=>{if(R.signal.aborted)return Promise.reject(We(R.signal));ee(p),(p==="agent"||p==="workflow-auto-run")&&(oe(),M=Date.now());let $=Date.now(),F=kc(f(),ah[p]??0,p);return Sc(F,R.signal,I).then(K=>(J(p,$,"ok"),K),K=>{throw J(p,$,"error"),K instanceof et&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},Et=async(p,f,I,$=0)=>{try{return await le(p,f,$)}catch(F){if(F instanceof et)return I();throw F}},ir=!1,Ln=!1,ar=p=>{if(!(!ir||Ln)){Ln=!0;try{Z().emit("task:completed",{taskId:B,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-w.startedAt.getTime(),error:p?.error||(R.signal.aborted?We(R.signal).message:"run ended before completion"),errorKind:p?.errorKind,interrupted:this.interruptedRuns.has(w.id)?!0:void 0,stopped:!this.interruptedRuns.has(w.id)&&(this.stoppedRuns.has(w.id)||p?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},dr=!1,cr=p=>{if(dr)return;dr=!0,ar(p),this.runReleases.delete(w.id),P&&clearTimeout(P),oe(),c.activeTasks--,this.admissionTickets.get(e)?.release();let f=c.runningTasks.findIndex($=>$.id===w.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(w.id),this.taskAborts.delete(w.id);let I=this.runEndWaiters.get(w.id);this.runEndWaiters.delete(w.id);for(let $ of I??[])try{$()}catch{}_.done=!0,_.endedAt=new Date;for(let $ of _.subscribers)try{$(`
183
183
  [task finished]
184
- `)}catch{}_.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(w.id),gh).unref?.();try{let $=_.endedAt,F={id:w.id,agentId:e.agentId,channel:w.channel,chatId:w.chatId,sender:w.sender,message:e.message||"",startedAt:w.startedAt.toISOString(),endedAt:$.toISOString(),durationMs:$.getTime()-w.startedAt.getTime(),ok:!p?.error,error:p?.error,...this.stoppedRuns.has(w.id)||p?.errorKind==="stopped"?{status:"stopped"}:ne?{status:"timeout",step:ne}:{},responseText:p?.content||"",transcript:_.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:$,ok:F.ok})}}catch($){this.log(`[${e.agentId}] task history persist failed: ${$?.message}`)}this.midTurn.endChat(en(e.agentId,u,l)),this.messageQueue.markDone(e.agentId,u,l).then($=>{if($.length===0)return;this.log(`[${e.agentId}] flushing ${$.length} queued message(s) after task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:$.length,at:new Date().toISOString()});let K=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of $){let Oe=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Oe,queuedAt:X.queuedAt??X.timestamp}).then(Ie=>($e(Ie.error)||K(),this.postQueuedResponseToChannel(e.agentId,Oe,Ie)),Ie=>{throw K(),Ie}).catch(Ie=>{this.log(`[${e.agentId}] queued message failed: ${Ie.message}`)})}}).catch($=>{Z().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: ${$.message}`)})};this.runReleases.set(w.id,cr),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${D()}`);let b=e.context?.channel||"api",{evaluateRequest:fu,selectRequestContext:hu}=await import("./request-planner-QQ7QRGUO.js"),ur=_t("request-gate",()=>fu(e.message,e.agentId,b),()=>({active:!1,preprocess:!1})),Ln=!1;ur.then(()=>{Ln=!0},()=>{Ln=!0});let T=l,Bn=e.context?.sender||"User",de=c.def.tier==="codex-cli",st=qd(this.config.session,b,c.def.tier),Et=Gd(this.config.session),ge=e.isolated===!0,rt=!ge&&st==="lean"&&Et.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,b,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${b}:${T}`),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}));let Pt=this.sessions.sessionIdleMs(e.agentId,b,T);e.freshSession||await _t("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,b,T,e.seedHistory),()=>{});let yu=[...this.sessions.getSession(e.agentId,b,T).messages].reverse().find(p=>p.role==="agent")?.content;yc({agent:e.agentId,channel:b,chatId:T,message:e.message,previousReply:yu,taskId:B}),this.sessions.addUserMessage(e.agentId,b,T,Bn,e.message);let lr=Date.now(),gr={agentId:e.agentId,channel:b,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(lr).toISOString(),taskId:B,resumeOrigin:Ha(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,...e.jobStateAsk?{jobStateAsk:!0}:{},sender:Vn(e.context),...v?{person:v}:{},humanRoot:Ke(e.context),pickup:Qr(e.context),operator:Xr(e.context),dueAt:xc(e.context),taskType:Rn(e.context),...typeof e.context?.home=="string"?{home:e.context.home.slice(0,500)}:{},...Tt(e.context)?{jobId:Tt(e.context)}:{}};Z().emit("task:started",gr),ir=!0;let te,Un,pr=this.classifier;if(pr&&b!=="a2a"&&!de){ee("classify");let p=Date.now();Un=pr.classify({text:e.message,channel:b,sender:e.context?.sender,chatId:T,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(w.intentPath=te.path.slice()),J("classify",p,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),J("classify",p,"error")})}let mr=async p=>{if(!Un)return;let f;await Promise.race([Un,new Promise(I=>{f=setTimeout(I,p),f.unref?.()})]),f&&clearTimeout(f)};await mr(th);let _e=this.config.workflows?.matching,Te,fr,hr=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&hr?.enabled&&(hr.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let p=new Yt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Vt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list());f&&f.confidence>=(_e?.suggestThreshold??.65)&&(fr=ni(f.workflow))}catch(p){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${p?.message||p}`)}if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let p=new Yt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Vt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list());f&&f.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${_e.mode} reasons=${f.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&f.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?Te={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let Ee=si(this.config.workflows,e.agentId)&&ri(e)?this.workflowRuns:void 0;if(Ee&&!Te&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let p=new Yt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Vt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list()),I=_e?.autoRunThreshold??.85;f&&f.confidence>=I&&(Te={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(p){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${p?.message||p}`)}let ce=Ee?ih():void 0,wu=ce?oi(ce):void 0,jn=this.wikiHub.getAgentWiki(e.agentId),yr=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),wr=this.memoryStore.buildContext(yr),br=this.memoryStore.contextFacts(yr),bu=this.patternStore.findRelevant(e.message,e.agentId,5),xu=this.patternStore.buildContext(bu),xr="";if(!de)try{let{loadLocalSkills:p,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),I=await le("skills",()=>p(c.def.workspace)),$=e.personLimits?.skills??[],F=$.length?I.filter(K=>!$.some(X=>it(X,K.frontmatter.name))):I;xr=f(F,e.message)}catch{}let j=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,b,T):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,b,T):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,b,T):void 0;if(j&&this.sessions.isSessionStale(e.agentId,b,T,Pt)&&(this.log(`[${e.agentId}] session stale for ${b}:${T}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,j,b,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,b,T)){let p=this.sessions.getLastTurnContextTokens(e.agentId,b,T);this.log(`[${e.agentId}] tier-2 rotation for ${b}:${T} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(b)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,j,b,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,b,T)){let p=this.sessions.getTurnCount(e.agentId,b,T);this.log(`[${e.agentId}] max-turns rotation for ${b}:${T} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,j,b,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&c.def.tier==="claude-code"){let p=this.config.session?.resumeGate;if(p&&p.mode!=="off"){let f=qi({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,b,T),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,b,T),idleMs:Pt??0},p);if(f.rotate&&p.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${b}:${T}: ${us(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,j,b,T,"cost");let I=this.sessions.getLastTurnInputTokens(e.agentId,b,T);this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"cost",lastTurnInputTokens:I,at:new Date().toISOString()}),j=void 0}else p.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${b}:${T}: would ${us(f)}`)}}if(j&&c.def.tier==="claude-code"){let p=j;await _t("rotate",()=>this.maybeRotateForContinuity(e,c,b,T,p),()=>!1)&&(j=void 0)}try{let p=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,b,T,this.memoryStore));if(p.compacted){let f=p.qualityScore??"?",I=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${b}:${T} (quality: ${f}%, ${I} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let $=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${$.overallScore} (lexicon=${$.lexiconDecay}, tools=${$.toolShift}, semantic=${$.semanticDrift})`),$.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${$.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let Su=process.env.AGENTX_CONTEXT_SURGERY==="1",ku=de?{maxMessages:8,maxChars:2400}:Su&&du(b,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Tu=!j&&!de?xh(jn,e.agentId,{notesInbox:bh(this.config)}):void 0,Sr;if(!j&&!de)try{let p=this.config.wiki?.decisionApprovals?.required===!0,f=Jo(zo(jn,e.agentId),jn.baseDir,p);Sr=Ko(f,Date.now())||void 0}catch{}let Ot=!j&&!rt?this.sessions.buildHistoryContext(e.agentId,b,T,ku):void 0,Iu=j?void 0:this.sessions.getRotationMemo(e.agentId,b,T)??void 0,kr,Tr=[];if(this.config.procedures?.injection?.enabled&&!j&&!de)try{let p=new kt({baseDir:G(process.cwd(),this.config.procedures.dir)}),f=Fs(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){kr=Hs(f),Tr=f.map(I=>({id:I.procedure.meta.id,title:I.procedure.meta.title}));for(let I of f)this.log(`[${e.agentId}] procedure match ${I.procedure.meta.id} score=${I.score.toFixed(2)} (${I.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(Ne&&Ne.cat)try{let f=this.sessions.getSession(e.agentId,b,T).messages,I=f[0],$=f[f.length-1],F=Ot===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ot.length}c/${Ot.split(`
185
- `).length}L`,K=`[${e.agentId}] ${b}:${T} ${F} | session.messages=${f.length}`+(f.length>0?` first=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")}) last=${$.timestamp.slice(11,19)}(${$.role}:${($.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ne.cat("context",K)}catch(p){Ne.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let Ir;if(c.def.contextReferences&&!j)try{let p=c.def.workspace,f=this.referencesCache.get(p);if(!f){let[$,F]=await le("references",()=>Promise.all([ts(c.def.workspace),ns(c.def.workspace)]));if($.byId.size===0&&F.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([ts(process.cwd()),ns(process.cwd())]));f={refs:K,recipes:X}}else f={refs:$,recipes:F};this.referencesCache.set(p,f)}let I=Uo({agentId:e.agentId,intentTags:te?.path,message:e.message},f.recipes,f.refs);I.cards.length>0&&(Ir=Lo(I.cards,500*4)),I.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${I.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let vr=ge||rt?"":this.sessions.getCrossSessionSummary(e.agentId,b,T,e.message),Ar,Dt=ge?null:_a(e.message);if(Dt)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:b,chatId:T,lookbackDays:Dt.lookbackDays,limit:12});if(p.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Dt.lookbackDays}d on this chat (cue-triggered)]`],I=[...p.turns].sort(($,F)=>$.ts.localeCompare(F.ts));for(let $ of I){let F=$.ts.slice(11,16)+" "+$.day,K=$.role==="user"?$.senderName||"User":$.senderName||"Agent";f.push(`${F} ${K}: ${$.content}`)}p.hasMore&&f.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Ar=f.join(`
186
- `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Dt.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let vu=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",$r,Mr,Cr=!1;Ln||ee("request-gate");let fe=await ur;if(fe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),vu==="planner"&&!ge&&!fe.active&&!rt&&b!=="voice"&&b!=="desktop"){try{let{planContext:p}=await import("./context-planner-CVCRW5TV.js"),f=await le("plan-context",()=>p({agentId:e.agentId,channel:b,chatId:T,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Cr=!0,$r=f.sessionHistory,wr=f.memoryContext,br=f.memoryFacts,vr=f.crossChatContext,Mr=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Cr&&j&&(this.sessions.clearClaudeSessionId(e.agentId,b,T),j=void 0)}let Fn=`${e.agentId}:${b}:${T}`,Nt=mo(e.message);Nt&&(Nt==="default"?(this.activeSouls.delete(Fn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Fn,Nt),this.log(`[${e.agentId}] Soul switched to: ${Nt}`)));let Au=this.activeSouls.get(Fn),$u=go(c.def.workspace,Au),Mu=po($u),Cu=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ru=uh(c.def.tier),_u=Ih(c.def.richMessages,e.context?.via==="voice"?"voice":b),Eu=c.def.tier==="claude-code"&&(ge||st!=="lean"||Kd(Et)),Rr="";if(c.def.workspace&&!Eu){let p=G(c.def.workspace,"CLAUDE.md");if(ae(p))try{let f=Ct(p,"utf-8");Rr=`[Project CLAUDE.md]
184
+ `)}catch{}_.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(w.id),gh).unref?.();try{let $=_.endedAt,F={id:w.id,agentId:e.agentId,channel:w.channel,chatId:w.chatId,sender:w.sender,message:e.message||"",startedAt:w.startedAt.toISOString(),endedAt:$.toISOString(),durationMs:$.getTime()-w.startedAt.getTime(),ok:!p?.error,error:p?.error,...this.stoppedRuns.has(w.id)||p?.errorKind==="stopped"?{status:"stopped"}:ne?{status:"timeout",step:ne}:{},responseText:p?.content||"",transcript:_.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:$,ok:F.ok})}}catch($){this.log(`[${e.agentId}] task history persist failed: ${$?.message}`)}this.midTurn.endChat(tn(e.agentId,u,l)),this.messageQueue.markDone(e.agentId,u,l).then($=>{if($.length===0)return;this.log(`[${e.agentId}] flushing ${$.length} queued message(s) after task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:$.length,at:new Date().toISOString()});let K=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of $){let Oe=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Oe,queuedAt:X.queuedAt??X.timestamp}).then(Ie=>($e(Ie.error)||K(),this.postQueuedResponseToChannel(e.agentId,Oe,Ie)),Ie=>{throw K(),Ie}).catch(Ie=>{this.log(`[${e.agentId}] queued message failed: ${Ie.message}`)})}}).catch($=>{Z().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: ${$.message}`)})};this.runReleases.set(w.id,cr),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${D()}`);let b=e.context?.channel||"api",{evaluateRequest:fu,selectRequestContext:hu}=await import("./request-planner-HF7ZY7HX.js"),ur=Et("request-gate",()=>fu(e.message,e.agentId,b),()=>({active:!1,preprocess:!1})),Bn=!1;ur.then(()=>{Bn=!0},()=>{Bn=!0});let T=l,jn=e.context?.sender||"User",de=c.def.tier==="codex-cli",st=qd(this.config.session,b,c.def.tier),Pt=Gd(this.config.session),ge=e.isolated===!0,rt=!ge&&st==="lean"&&Pt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,b,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${b}:${T}`),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}));let Ot=this.sessions.sessionIdleMs(e.agentId,b,T);e.freshSession||await Et("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,b,T,e.seedHistory),()=>{});let yu=[...this.sessions.getSession(e.agentId,b,T).messages].reverse().find(p=>p.role==="agent")?.content;yc({agent:e.agentId,channel:b,chatId:T,message:e.message,previousReply:yu,taskId:B}),this.sessions.addUserMessage(e.agentId,b,T,jn,e.message);let lr=Date.now(),gr={agentId:e.agentId,channel:b,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(lr).toISOString(),taskId:B,resumeOrigin:Ha(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,...e.jobStateAsk?{jobStateAsk:!0}:{},sender:Zn(e.context),...v?{person:v}:{},humanRoot:Ke(e.context),pickup:Qr(e.context),operator:Xr(e.context),dueAt:xc(e.context),taskType:_n(e.context),...typeof e.context?.home=="string"?{home:e.context.home.slice(0,500)}:{},...It(e.context)?{jobId:It(e.context)}:{}};Z().emit("task:started",gr),ir=!0;let te,Un,pr=this.classifier;if(pr&&b!=="a2a"&&!de){ee("classify");let p=Date.now();Un=pr.classify({text:e.message,channel:b,sender:e.context?.sender,chatId:T,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(w.intentPath=te.path.slice()),J("classify",p,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),J("classify",p,"error")})}let mr=async p=>{if(!Un)return;let f;await Promise.race([Un,new Promise(I=>{f=setTimeout(I,p),f.unref?.()})]),f&&clearTimeout(f)};await mr(th);let _e=this.config.workflows?.matching,Te,fr,hr=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&hr?.enabled&&(hr.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let p=new Vt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Zt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list());f&&f.confidence>=(_e?.suggestThreshold??.65)&&(fr=ni(f.workflow))}catch(p){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${p?.message||p}`)}if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let p=new Vt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Zt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list());f&&f.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${_e.mode} reasons=${f.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&f.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?Te={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let Ee=si(this.config.workflows,e.agentId)&&ri(e)?this.workflowRuns:void 0;if(Ee&&!Te&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let p=new Vt({baseDir:G(process.cwd(),this.config.workflows.dir)}),f=Zt({agentId:e.agentId,channel:b,message:e.message,intentPath:te?.path},p.list()),I=_e?.autoRunThreshold??.85;f&&f.confidence>=I&&(Te={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(p){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${p?.message||p}`)}let ce=Ee?ih():void 0,wu=ce?oi(ce):void 0,Fn=this.wikiHub.getAgentWiki(e.agentId),yr=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),wr=this.memoryStore.buildContext(yr),br=this.memoryStore.contextFacts(yr),bu=this.patternStore.findRelevant(e.message,e.agentId,5),xu=this.patternStore.buildContext(bu),xr="";if(!de)try{let{loadLocalSkills:p,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),I=await le("skills",()=>p(c.def.workspace)),$=e.personLimits?.skills??[],F=$.length?I.filter(K=>!$.some(X=>it(X,K.frontmatter.name))):I;xr=f(F,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,b,T):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,b,T):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,b,T):void 0;if(U&&this.sessions.isSessionStale(e.agentId,b,T,Ot)&&(this.log(`[${e.agentId}] session stale for ${b}:${T}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,b,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,b,T)){let p=this.sessions.getLastTurnContextTokens(e.agentId,b,T);this.log(`[${e.agentId}] tier-2 rotation for ${b}:${T} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(b)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,b,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,b,T)){let p=this.sessions.getTurnCount(e.agentId,b,T);this.log(`[${e.agentId}] max-turns rotation for ${b}:${T} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,b,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let p=this.config.session?.resumeGate;if(p&&p.mode!=="off"){let f=qi({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,b,T),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,b,T),idleMs:Ot??0},p);if(f.rotate&&p.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${b}:${T}: ${ls(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,U,b,T,"cost");let I=this.sessions.getLastTurnInputTokens(e.agentId,b,T);this.sessions.clearClaudeSessionId(e.agentId,b,T),Z().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"cost",lastTurnInputTokens:I,at:new Date().toISOString()}),U=void 0}else p.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${b}:${T}: would ${ls(f)}`)}}if(U&&c.def.tier==="claude-code"){let p=U;await Et("rotate",()=>this.maybeRotateForContinuity(e,c,b,T,p),()=>!1)&&(U=void 0)}try{let p=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,b,T,this.memoryStore));if(p.compacted){let f=p.qualityScore??"?",I=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${b}:${T} (quality: ${f}%, ${I} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let $=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${$.overallScore} (lexicon=${$.lexiconDecay}, tools=${$.toolShift}, semantic=${$.semanticDrift})`),$.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${$.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let Su=process.env.AGENTX_CONTEXT_SURGERY==="1",ku=de?{maxMessages:8,maxChars:2400}:Su&&du(b,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Tu=!U&&!de?xh(Fn,e.agentId,{notesInbox:bh(this.config)}):void 0,Sr;if(!U&&!de)try{let p=this.config.wiki?.decisionApprovals?.required===!0,f=Jo(zo(Fn,e.agentId),Fn.baseDir,p);Sr=Ko(f,Date.now())||void 0}catch{}let Dt=!U&&!rt?this.sessions.buildHistoryContext(e.agentId,b,T,ku):void 0,Iu=U?void 0:this.sessions.getRotationMemo(e.agentId,b,T)??void 0,kr,Tr=[];if(this.config.procedures?.injection?.enabled&&!U&&!de)try{let p=new kt({baseDir:G(process.cwd(),this.config.procedures.dir)}),f=Hs(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){kr=Ws(f),Tr=f.map(I=>({id:I.procedure.meta.id,title:I.procedure.meta.title}));for(let I of f)this.log(`[${e.agentId}] procedure match ${I.procedure.meta.id} score=${I.score.toFixed(2)} (${I.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(Ne&&Ne.cat)try{let f=this.sessions.getSession(e.agentId,b,T).messages,I=f[0],$=f[f.length-1],F=Dt===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Dt.length}c/${Dt.split(`
185
+ `).length}L`,K=`[${e.agentId}] ${b}:${T} ${F} | session.messages=${f.length}`+(f.length>0?` first=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")}) last=${$.timestamp.slice(11,19)}(${$.role}:${($.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ne.cat("context",K)}catch(p){Ne.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let Ir;if(c.def.contextReferences&&!U)try{let p=c.def.workspace,f=this.referencesCache.get(p);if(!f){let[$,F]=await le("references",()=>Promise.all([ns(c.def.workspace),ss(c.def.workspace)]));if($.byId.size===0&&F.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([ns(process.cwd()),ss(process.cwd())]));f={refs:K,recipes:X}}else f={refs:$,recipes:F};this.referencesCache.set(p,f)}let I=jo({agentId:e.agentId,intentTags:te?.path,message:e.message},f.recipes,f.refs);I.cards.length>0&&(Ir=Lo(I.cards,500*4)),I.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${I.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let vr=ge||rt?"":this.sessions.getCrossSessionSummary(e.agentId,b,T,e.message),Ar,Nt=ge?null:_a(e.message);if(Nt)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:b,chatId:T,lookbackDays:Nt.lookbackDays,limit:12});if(p.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Nt.lookbackDays}d on this chat (cue-triggered)]`],I=[...p.turns].sort(($,F)=>$.ts.localeCompare(F.ts));for(let $ of I){let F=$.ts.slice(11,16)+" "+$.day,K=$.role==="user"?$.senderName||"User":$.senderName||"Agent";f.push(`${F} ${K}: ${$.content}`)}p.hasMore&&f.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Ar=f.join(`
186
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Nt.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let vu=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",$r,Mr,Cr=!1;Bn||ee("request-gate");let fe=await ur;if(fe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),vu==="planner"&&!ge&&!fe.active&&!rt&&b!=="voice"&&b!=="desktop"){try{let{planContext:p}=await import("./context-planner-CVCRW5TV.js"),f=await le("plan-context",()=>p({agentId:e.agentId,channel:b,chatId:T,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Cr=!0,$r=f.sessionHistory,wr=f.memoryContext,br=f.memoryFacts,vr=f.crossChatContext,Mr=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Cr&&U&&(this.sessions.clearClaudeSessionId(e.agentId,b,T),U=void 0)}let Hn=`${e.agentId}:${b}:${T}`,Lt=mo(e.message);Lt&&(Lt==="default"?(this.activeSouls.delete(Hn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Hn,Lt),this.log(`[${e.agentId}] Soul switched to: ${Lt}`)));let Au=this.activeSouls.get(Hn),$u=go(c.def.workspace,Au),Mu=po($u),Cu=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ru=uh(c.def.tier),_u=Ih(c.def.richMessages,e.context?.via==="voice"?"voice":b),Eu=c.def.tier==="claude-code"&&(ge||st!=="lean"||Kd(Pt)),Rr="";if(c.def.workspace&&!Eu){let p=G(c.def.workspace,"CLAUDE.md");if(ae(p))try{let f=Rt(p,"utf-8");Rr=`[Project CLAUDE.md]
187
187
  ${f.length>4e3?f.slice(0,4e3)+`
188
188
 
189
- [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Lt=e.context?.runbookPath,Hn=[];if(Lt&&ae(Lt)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,I=4e3,$=16e3;for(let F of p){if(f>=$)break;let K=G(Lt,F);if(ae(K))try{let X=Ct(K,"utf-8"),Oe=X.length>I?X.slice(0,I)+`
189
+ [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Bt=e.context?.runbookPath,Wn=[];if(Bt&&ae(Bt)){let p=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,I=4e3,$=16e3;for(let F of p){if(f>=$)break;let K=G(Bt,F);if(ae(K))try{let X=Rt(K,"utf-8"),Oe=X.length>I?X.slice(0,I)+`
190
190
 
191
- [${F} truncated to ${I} bytes]`:X;Hn.push(`[Project Runbook \u2014 ${F} from ${Lt}]
192
- ${Oe}`),f+=Oe.length}catch{}}}let Pu=Hn.length>0?Hn.join(`
191
+ [${F} truncated to ${I} bytes]`:X;Wn.push(`[Project Runbook \u2014 ${F} from ${Bt}]
192
+ ${Oe}`),f+=Oe.length}catch{}}}let Pu=Wn.length>0?Wn.join(`
193
193
 
194
- `):"",Wn=[c.def.systemPrompt||"",Ru,_u,Rr,Pu,Mu||"",Cu||""].filter(p=>p.trim().length>0).join(`
194
+ `):"",qn=[c.def.systemPrompt||"",Ru,_u,Rr,Pu,Mu||"",Cu||""].filter(p=>p.trim().length>0).join(`
195
195
 
196
- `)||void 0,Bt={channel:b,chatId:T,channelScope:e.context?.group?"group":b==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,b),systemPrompt:c.def.systemPrompt,sender:Bn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||rt||du(b,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:xu||void 0,procedureContext:[kr,fr].filter(Boolean).join(`
196
+ `)||void 0,jt={channel:b,chatId:T,channelScope:e.context?.group?"group":b==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,b),systemPrompt:c.def.systemPrompt,sender:jn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||rt||du(b,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:xu||void 0,procedureContext:[kr,fr].filter(Boolean).join(`
197
197
 
198
- `)||void 0,workflowRunContext:wu,references:Ir,skillInjection:xr||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:$r??Ot,memoryContext:wr||void 0,crossChatContext:vr||void 0,longMemoryRecall:Ar||void 0,contextOnDemand:rt&&!j?Vd(b,T):void 0,wikiContext:Tu,handoverNote:this.buildHandoverNote(e.agentId,b,T),watcherNote:(()=>{try{return this.runNote?.(gr)}catch{return}})(),rotationMemo:Iu,ownerDecisions:Sr,eventDigest:j?void 0:wh(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let p=yi(b,!j,c.def.richMessages);return p?Sh(c.def.workspace,p):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ge&&Object.assign(Bt,{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 ot=e.model?void 0:io({tier:c.def.tier,channel:b,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!j,sessionIdleMs:j?Pt:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let _r=oo(c.def.tier,this.config.decisions.routing),Er=ot?.downgraded?Promise.resolve(ot.model):!e.model&&_r&&(!fe.active||fe.preprocess)?(async()=>{try{let{routeTaskModel:p}=await import("./routing-4YTBWI2S.js"),f=await le("route-model",()=>p({message:e.message,agent:e.agentId,channel:b,isFollowUp:!!j,sessionIdleMs:j?Pt:null,cheapModel:_r}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Pr=!1;Er.then(()=>{Pr=!0});let Or=!e.model&&!ot?.downgraded&&!ge&&(c.def.tier==="claude-code"||c.def.tier==="codex-cli")&&Mi()&&(!fe.active||fe.preprocess)?(async()=>{try{return await le("route-edge",()=>Ri({message:e.message,agent:e.agentId,channel:b,tier:c.def.tier,isFollowUp:!!j,agentPrompt:c.def.systemPrompt??null,edgeModel:Ci(c.def.tier,this.config.decisions.routing),currentModel:c.def.model??null,impliedWork:Ke(e.context)?this.config.decisions.routing.impliedWork:"off"}))}catch{return}})():Promise.resolve(void 0),Dr=!1;Or.then(()=>{Dr=!0});let Ut=fe.active&&fe.preprocess?await _t("select-context",()=>hu(Bt),()=>({input:Bt,excluded:[]})):{input:Bt,excluded:[]};Ut.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ut.excluded.join(", ")}`);let jt=Fa(Ut.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),Ou=Ro(jt,{memory:br,procedures:Tr,wikiContext:Ut.input.wikiContext}),qn=(jt?.length??0)+(Wn?.length??0)+(e.message?.length??0),Ft={history:jt?.length??0,sysPrompt:Wn?.length??0,message:e.message?.length??0},Nr=Nd(e.agentId,b,T);Ld(Nr,qn,Ft);let Lr=Bd(Nr);Lr&&this.log(`[${e.agentId}] ${Lr}`),qn>16e3&&this.log(`[${e.agentId}] large context for ${b}:${T}: ${qn} bytes (history=${Ft.history}, sysPrompt=${Ft.sysPrompt}, message=${Ft.message})`),Pr||ee("route-model");let Ht=await Er,Gn=c.def.tier!=="claude-code"?void 0:ge?Qd():st==="lean"?zd(c.def.workspace,Et,void 0,b):Yd(c.def.workspace);st==="lean"&&!ge&&!j&&this.log(`[${e.agentId}] session profile for ${b}: ${Zd(st,Et,b)}`);let Br=c.def.tier==="claude-code"&&!j?Hi({message:e.message??"",agent:e.agentId,channel:b,agentPrompt:c.def.systemPrompt??null,taskId:B},p=>this.log(p)):void 0;Dr||ee("route-edge");let Pe=await Or,Wt=Ei(Pe,{tier:c.def.tier,claudeArgs:Gn}),Kn=_i(Pe,Ht),Ur=!!Ht&&Kn!==Ht;Pe&&(Pe.upgraded||Pe.subagents||Ur||(Pe.impliedP??0)>=ds)&&this.log(`[${e.agentId}] ${Pe.reason}${Ur?` \u2014 downgrade to ${Ht} dropped`:""}`);let Du={...e,systemPromptAppend:Wn,...Gn?{claudeArgs:Gn}:{},...Kn?{model:Kn}:{},...Wt.subagentModel?{subagentModel:Wt.subagentModel}:{},...Wt.turnNote?{turnNote:Wt.turnNote}:{}},se,jr=mc({agent:e.agentId,request:e.message,taskId:B,budgetMinutes:c.def.maxExecutionMinutes??20}),Nu=U,Fr=!1,Jn=!0;U=p=>{if(jr.observe(p),ce&&Jn)for(let f of ai(p))ii(f.name,f.input)||(Jn=!1);Nu?.(p)};try{let p=this.workflowAutoRunner;if(Te&&p){let O=Te;try{let z=await le("workflow-auto-run",()=>p({workflowId:O.workflowId,agentId:e.agentId,channel:b,chatId:T,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:b,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Te.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:Te.workflowId,workflowRunId:z.runId,workflowMatchConfidence:Te.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ee)try{let O=ci(Ee,e.resumedFrom);di(Ee,{runId:ce,agentId:e.agentId,channel:b,chatId:T,message:e.message,taskId:B,...O?{continues:O}:{}}),Fr=!0,w.workflow={runId:ce,workflowId:ti}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${O?.message||O}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ee("dispatch-gate");let O=c.def.persistentProcess?ut():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:b,chatId:T}),he=!!j||z,ye=[wd(he),Od(he,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(ye){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ye.reason}`);let De={content:"",error:ye.message,errorKind:"dispatch_hold",..."retryAt"in ye&&typeof ye.retryAt=="number"?{retryAt:ye.retryAt}:{},duration:0};if(!t){_.buffer=`[error] ${ye.message}`;for(let Uu of _.subscribers)try{Uu(_.buffer)}catch{}}return De}Ad();let ue=Dd();return ue&&this.log(`[${e.agentId}] ${ue}`),null},I=Xt(e.agentId,void 0,Qt(e.agentId,e.context?.chatId));if(I){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${I.reason}`),!t){_.buffer=`[error] ${I.message}`;for(let O of _.subscribers)try{O(_.buffer)}catch{}}return c.errors++,se={content:"",error:I.message,errorKind:"budget_cap",duration:0},se}let $=this.planCloudSession(c.def,e);if($.route==="local"){let O=f();if(O)return c.errors++,se=O,O}let F=c.def.tier==="claude-code",K=F?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,Oe=F?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},Ie=()=>{X&&(L(`
199
- `),X=!1)},Lu=F?K:K?(O,z)=>{Ie(),K(O,z)}:void 0,E=await le("agent",async()=>{if($.route!=="local"){let z=await this.runCloudSession(c.def,e,$,B);if(z)return z;let he=f();if(he)return he}let O=await this.inTaskWorktree(c.def,Du);return Ma(O.def,O.task,this.providers,Lu,jt,O.fresh?void 0:j,U,R.signal,Oe)},ph);if(!E.error){let O=kh(c.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([he,qe])=>`${he}=${qe}`).join(", ")||"none";E.error=`tool_required_not_called: ${O} (invoked: ${z})`,E.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}Br&&Wi(Br,{toolUses:q,eventsSeen:A,error:E.error,agentId:e.agentId},O=>this.log(O));let qt=this.interruptedRuns.get(w.id);qt&&(E.content="",E.error=qt,E.errorKind="interrupted");let zn=qt?void 0:this.stoppedRuns.get(w.id);zn&&(E.content="",E.error=zn,E.errorKind="stopped"),se=E;let ve=E.usage?Mo(E.usage):void 0,Bu=E.billedModel||e.model||c.def.model||void 0,Gt=E.costUsd??(E.usage?this.tokenTracker.runCost(E.usage,Bu,c.def.tier):void 0);if(Nn=!0,Z().emit("task:completed",{taskId:B,agentId:e.agentId,channel:b,chatId:T,durationMs:Date.now()-lr,error:E.error||void 0,errorKind:E.error?E.errorKind:void 0,interrupted:qt?!0:void 0,stopped:zn?!0:void 0,inputTokens:ve?.inputTokens,outputTokens:ve?.outputTokens,cacheReadTokens:ve?.cacheReadTokens,cacheCreateTokens:ve?.cacheCreateTokens,tier2InputTokens:ve?.tier2InputTokens,tier2OutputTokens:ve?.tier2OutputTokens,tier2CacheReadTokens:ve?.tier2CacheReadTokens,tier2CacheCreateTokens:ve?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:fe.arm,numTurns:E.numTurns,costUsd:Gt!==void 0&&Number.isFinite(Gt)&&Gt>0?Gt:void 0,injectedContext:Ou,finalResponse:E.content||void 0,billedModel:E.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(E.content||E.error)){let O=E.error?`[error] ${E.error}`:E.content;_.buffer=O;for(let z of _.subscribers)try{z(O)}catch{}}if(E.error)c.errors++,this.log(`[${e.agentId}] error: ${E.error}`);else{if(this.sessions.addAgentMessage(e.agentId,b,T,E.content),hc({agent:e.agentId,channel:b,chatId:T,request:e.message,reply:E.content,taskId:B}),E.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,b,T,E.claudeSessionId),E.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,b,T,E.codexSessionId),E.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,b,T,E.opencodeSessionId),(E.claudeSessionId||E.codexSessionId||E.opencodeSessionId)&&E.usage&&this.sessions.recordTurnUsage(e.agentId,b,T,E.usage,E.contextTokens),E.usage){let ue=E.contextTokens,De=(E.usage.inputTokens||0)+(E.usage.cacheReadTokens||0)+(E.usage.cacheCreateTokens||0);(ue??De)>=this.sessions.getTierTwoThresholdTokens(b)&&this.log(`[${e.agentId}] TIER-2 HIT on ${b}:${T}: context=${ue??"n/a"} tokens (cumulative turn total=${De}) \u2014 next turn will rotate`)}let O=xo({channel:b,content:`User: ${e.message}`,responseLength:E.content.length}),z=G(this.wikiHub.getBaseDir(),Oa);O.capture||Da(z,e.agentId,O,ue=>this.log(ue)),O.capture&&(await mr(nh),Na(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:b,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
198
+ `)||void 0,workflowRunContext:wu,references:Ir,skillInjection:xr||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:$r??Dt,memoryContext:wr||void 0,crossChatContext:vr||void 0,longMemoryRecall:Ar||void 0,contextOnDemand:rt&&!U?Vd(b,T):void 0,wikiContext:Tu,handoverNote:this.buildHandoverNote(e.agentId,b,T),watcherNote:(()=>{try{return this.runNote?.(gr)}catch{return}})(),rotationMemo:Iu,ownerDecisions:Sr,eventDigest:U?void 0:wh(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let p=yi(b,!U,c.def.richMessages);return p?Sh(c.def.workspace,p):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ge&&Object.assign(jt,{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 ot=e.model?void 0:io({tier:c.def.tier,channel:b,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!U,sessionIdleMs:U?Ot:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let _r=oo(c.def.tier,this.config.decisions.routing),Er=ot?.downgraded?Promise.resolve(ot.model):!e.model&&_r&&(!fe.active||fe.preprocess)?(async()=>{try{let{routeTaskModel:p}=await import("./routing-CVVEL76N.js"),f=await le("route-model",()=>p({message:e.message,agent:e.agentId,channel:b,isFollowUp:!!U,sessionIdleMs:U?Ot:null,cheapModel:_r}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Pr=!1;Er.then(()=>{Pr=!0});let Or=!e.model&&!ot?.downgraded&&!ge&&(c.def.tier==="claude-code"||c.def.tier==="codex-cli")&&Mi()&&(!fe.active||fe.preprocess)?(async()=>{try{return await le("route-edge",()=>Ri({message:e.message,agent:e.agentId,channel:b,tier:c.def.tier,isFollowUp:!!U,agentPrompt:c.def.systemPrompt??null,edgeModel:Ci(c.def.tier,this.config.decisions.routing),currentModel:c.def.model??null,impliedWork:Ke(e.context)?this.config.decisions.routing.impliedWork:"off"}))}catch{return}})():Promise.resolve(void 0),Dr=!1;Or.then(()=>{Dr=!0});let Ut=fe.active&&fe.preprocess?await Et("select-context",()=>hu(jt),()=>({input:jt,excluded:[]})):{input:jt,excluded:[]};Ut.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ut.excluded.join(", ")}`);let Ft=Fa(Ut.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),Ou=Ro(Ft,{memory:br,procedures:Tr,wikiContext:Ut.input.wikiContext}),Gn=(Ft?.length??0)+(qn?.length??0)+(e.message?.length??0),Ht={history:Ft?.length??0,sysPrompt:qn?.length??0,message:e.message?.length??0},Nr=Nd(e.agentId,b,T);Ld(Nr,Gn,Ht);let Lr=Bd(Nr);Lr&&this.log(`[${e.agentId}] ${Lr}`),Gn>16e3&&this.log(`[${e.agentId}] large context for ${b}:${T}: ${Gn} bytes (history=${Ht.history}, sysPrompt=${Ht.sysPrompt}, message=${Ht.message})`),Pr||ee("route-model");let Wt=await Er,Kn=c.def.tier!=="claude-code"?void 0:ge?Qd():st==="lean"?zd(c.def.workspace,Pt,void 0,b):Yd(c.def.workspace);st==="lean"&&!ge&&!U&&this.log(`[${e.agentId}] session profile for ${b}: ${Zd(st,Pt,b)}`);let Br=c.def.tier==="claude-code"&&!U?Hi({message:e.message??"",agent:e.agentId,channel:b,agentPrompt:c.def.systemPrompt??null,taskId:B},p=>this.log(p)):void 0;Dr||ee("route-edge");let Pe=await Or,qt=Ei(Pe,{tier:c.def.tier,claudeArgs:Kn}),Jn=_i(Pe,Wt),jr=!!Wt&&Jn!==Wt;Pe&&(Pe.upgraded||Pe.subagents||jr||(Pe.impliedP??0)>=cs)&&this.log(`[${e.agentId}] ${Pe.reason}${jr?` \u2014 downgrade to ${Wt} dropped`:""}`);let Du={...e,systemPromptAppend:qn,...Kn?{claudeArgs:Kn}:{},...Jn?{model:Jn}:{},...qt.subagentModel?{subagentModel:qt.subagentModel}:{},...qt.turnNote?{turnNote:qt.turnNote}:{}},se,Ur=mc({agent:e.agentId,request:e.message,taskId:B,budgetMinutes:c.def.maxExecutionMinutes??20}),Nu=j,Fr=!1,zn=!0;j=p=>{if(Ur.observe(p),ce&&zn)for(let f of ai(p))ii(f.name,f.input)||(zn=!1);Nu?.(p)};try{let p=this.workflowAutoRunner;if(Te&&p){let O=Te;try{let z=await le("workflow-auto-run",()=>p({workflowId:O.workflowId,agentId:e.agentId,channel:b,chatId:T,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:b,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Te.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:Te.workflowId,workflowRunId:z.runId,workflowMatchConfidence:Te.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ee)try{let O=ci(Ee,e.resumedFrom);di(Ee,{runId:ce,agentId:e.agentId,channel:b,chatId:T,message:e.message,taskId:B,...O?{continues:O}:{}}),Fr=!0,w.workflow={runId:ce,workflowId:ti}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${O?.message||O}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ee("dispatch-gate");let O=c.def.persistentProcess?ut():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:b,chatId:T}),he=!!U||z,ye=[wd(he),Od(he,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(ye){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ye.reason}`);let De={content:"",error:ye.message,errorKind:"dispatch_hold",..."retryAt"in ye&&typeof ye.retryAt=="number"?{retryAt:ye.retryAt}:{},duration:0};if(!t){_.buffer=`[error] ${ye.message}`;for(let ju of _.subscribers)try{ju(_.buffer)}catch{}}return De}Ad();let ue=Dd();return ue&&this.log(`[${e.agentId}] ${ue}`),null},I=Yt(e.agentId,void 0,Xt(e.agentId,e.context?.chatId));if(I){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${I.reason}`),!t){_.buffer=`[error] ${I.message}`;for(let O of _.subscribers)try{O(_.buffer)}catch{}}return c.errors++,se={content:"",error:I.message,errorKind:"budget_cap",duration:0},se}let $=this.planCloudSession(c.def,e);if($.route==="local"){let O=f();if(O)return c.errors++,se=O,O}let F=c.def.tier==="claude-code",K=F?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,Oe=F?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},Ie=()=>{X&&(L(`
199
+ `),X=!1)},Lu=F?K:K?(O,z)=>{Ie(),K(O,z)}:void 0,E=await le("agent",async()=>{if($.route!=="local"){let z=await this.runCloudSession(c.def,e,$,B);if(z)return z;let he=f();if(he)return he}let O=await this.inTaskWorktree(c.def,Du);return Ma(O.def,O.task,this.providers,Lu,Ft,O.fresh?void 0:U,j,R.signal,Oe)},ph);if(!E.error){let O=kh(c.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([he,qe])=>`${he}=${qe}`).join(", ")||"none";E.error=`tool_required_not_called: ${O} (invoked: ${z})`,E.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}Br&&Wi(Br,{toolUses:q,eventsSeen:A,error:E.error,agentId:e.agentId},O=>this.log(O));let Gt=this.interruptedRuns.get(w.id);Gt&&(E.content="",E.error=Gt,E.errorKind="interrupted");let Qn=Gt?void 0:this.stoppedRuns.get(w.id);Qn&&(E.content="",E.error=Qn,E.errorKind="stopped"),se=E;let ve=E.usage?Mo(E.usage):void 0,Bu=E.billedModel||e.model||c.def.model||void 0,Kt=E.costUsd??(E.usage?this.tokenTracker.runCost(E.usage,Bu,c.def.tier):void 0);if(Ln=!0,Z().emit("task:completed",{taskId:B,agentId:e.agentId,channel:b,chatId:T,durationMs:Date.now()-lr,error:E.error||void 0,errorKind:E.error?E.errorKind:void 0,interrupted:Gt?!0:void 0,stopped:Qn?!0:void 0,inputTokens:ve?.inputTokens,outputTokens:ve?.outputTokens,cacheReadTokens:ve?.cacheReadTokens,cacheCreateTokens:ve?.cacheCreateTokens,tier2InputTokens:ve?.tier2InputTokens,tier2OutputTokens:ve?.tier2OutputTokens,tier2CacheReadTokens:ve?.tier2CacheReadTokens,tier2CacheCreateTokens:ve?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:fe.arm,numTurns:E.numTurns,costUsd:Kt!==void 0&&Number.isFinite(Kt)&&Kt>0?Kt:void 0,injectedContext:Ou,finalResponse:E.content||void 0,billedModel:E.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(E.content||E.error)){let O=E.error?`[error] ${E.error}`:E.content;_.buffer=O;for(let z of _.subscribers)try{z(O)}catch{}}if(E.error)c.errors++,this.log(`[${e.agentId}] error: ${E.error}`);else{if(this.sessions.addAgentMessage(e.agentId,b,T,E.content),hc({agent:e.agentId,channel:b,chatId:T,request:e.message,reply:E.content,taskId:B}),E.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,b,T,E.claudeSessionId),E.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,b,T,E.codexSessionId),E.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,b,T,E.opencodeSessionId),(E.claudeSessionId||E.codexSessionId||E.opencodeSessionId)&&E.usage&&this.sessions.recordTurnUsage(e.agentId,b,T,E.usage,E.contextTokens),E.usage){let ue=E.contextTokens,De=(E.usage.inputTokens||0)+(E.usage.cacheReadTokens||0)+(E.usage.cacheCreateTokens||0);(ue??De)>=this.sessions.getTierTwoThresholdTokens(b)&&this.log(`[${e.agentId}] TIER-2 HIT on ${b}:${T}: context=${ue??"n/a"} tokens (cumulative turn total=${De}) \u2014 next turn will rotate`)}let O=xo({channel:b,content:`User: ${e.message}`,responseLength:E.content.length}),z=G(this.wikiHub.getBaseDir(),Oa);O.capture||Da(z,e.agentId,O,ue=>this.log(ue)),O.capture&&(await mr(nh),Na(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:b,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
200
200
 
201
- Agent: ${E.content}`,meta:yh(te,e.context)})},ue=>this.log(ue)),To(e.agentId,e.message,E.content,{channel:b,chatId:T,sender:Bn},this.memoryStore).catch(()=>{}),ad(e.agentId,e.message,E.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let he=E.billedModel||e.model||c.def.model,qe=e.context?.channel,ye=qe&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${qe}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,E.duration||0,E.usage,e.message.length,E.content.length,!1,he,qe,ye),this.log(`[${e.agentId}] completed in ${E.duration}ms`+(E.tokensUsed?` (${E.tokensUsed} tokens)`:"")+` ${D()}`)}return E}catch(p){c.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=rn(p.message);return se={content:"",error:on(f),errorKind:f.kind},se}finally{if(jr.stop(),Fr&&ce&&Ee)try{let p=se?.usage,f=ui(Ee,ce,{error:se?se.error||void 0:R.signal.aborted?We(R.signal).message:"run ended before completion",canceled:li(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...p?{inputTokens:p.inputTokens,outputTokens:p.outputTokens}:{},readOnly:Jn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(p){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${p?.message||p}`)}ar(se),cr(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?lh(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:gi(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),nt,this.safe(e.agentId),t);ae(s)||sh(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);oh(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(),nt,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 g=G(a,l);if(ae(g))try{for(let m of ke(g)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let S=Math.floor((s-y)/36e5),x=t-1-S;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),nt);if(!ae(e))return 0;let t=0;for(let s of ke(e)){let r=G(e,s),o;try{o=ke(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=ke(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(Ct(G(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hh){let t=G(process.cwd(),nt);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ke(t)){let i=G(t,o),a;try{a=ke(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{rh(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),nt,this.safe(e));if(!ae(s))return[];let r=ke(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=ke(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(Ct(G(a,c),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),nt,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ke(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(Ct(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=>!Xt(t,void 0,Qt(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=rs();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||$e(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){dh.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=ht(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let 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}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!Si(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(d=>d.channel===s&&d.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(en(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(en(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}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 g=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:g,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);Z().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(g).toISOString(),sender:{name:s},humanRoot:!1,person:Yr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:g});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=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=g=>{u||(u=!0,c(g))};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:g=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:g,queued:!1})}).then(g=>{$e(g.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):g.error?l({ok:!1,status:500,error:g.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>l({ok:!1,status:500,error:g?.message??String(g)}))})}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 Ih(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(`
202
- `)}export{vh as a,$i as b,Qi as c,Gh as d,Kh as e,Jh as f,Yi as g,ny as h,ml as i,Zi as j,dn as k,yy as l,Sy as m,ky as n,$y as o,ht as p,Ul as q,va as r,ql as s,Gl as t,Kl as u,Ma as v,fn as w,Oa as x,ow as y,hn as z,hg as A,uw as B,lw as C,pw as D,vs as E,hw as F,yw as G,bt as H,Ya as I,wn as J,Cg as K,xw as L,Cs as M,Z as N,pd as O,zg as P,Vg as Q,hd as R,Uw as S,yd as T,Id as U,Zw as V,eb as W,Rd as X,tb as Y,_d as Z,In as _,ub as $,lb as aa,kt as ba,cm as ca,um as da,lm as ea,gm as fa,pm as ga,Fs as ha,qb as ia,Gb as ja,Im as ka,wc as la,Rn as ma,Jb as na,En as oa,_n as pa,$c as qa,vt as ra,Mc as sa,ex as ta,tx as ua,nx as va,sx as wa,rx as xa,ox as ya,ix as za,Xm as Aa,jc as Ba,tt as Ca,eu as Da,rr as Ea,xx as Fa,kx as Ga,Tx as Ha,ch as Ia,uh as Ja,a0 as Ka,d0 as La,lh as Ma,fh as Na,yh as Oa,wh as Pa,xh as Qa,or as Ra,uu as Sa,lu as Ta,kh as Ua,gu as Va,pu as Wa,Ih as Xa};
203
- //# sourceMappingURL=chunk-IWEIHEYQ.js.map
201
+ Agent: ${E.content}`,meta:yh(te,e.context)})},ue=>this.log(ue)),To(e.agentId,e.message,E.content,{channel:b,chatId:T,sender:jn},this.memoryStore).catch(()=>{}),ad(e.agentId,e.message,E.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let he=E.billedModel||e.model||c.def.model,qe=e.context?.channel,ye=qe&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${qe}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,E.duration||0,E.usage,e.message.length,E.content.length,!1,he,qe,ye),this.log(`[${e.agentId}] completed in ${E.duration}ms`+(E.tokensUsed?` (${E.tokensUsed} tokens)`:"")+` ${D()}`)}return E}catch(p){c.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=on(p.message);return se={content:"",error:an(f),errorKind:f.kind},se}finally{if(Ur.stop(),Fr&&ce&&Ee)try{let p=se?.usage,f=ui(Ee,ce,{error:se?se.error||void 0:R.signal.aborted?We(R.signal).message:"run ended before completion",canceled:li(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...p?{inputTokens:p.inputTokens,outputTokens:p.outputTokens}:{},readOnly:zn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(p){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${p?.message||p}`)}ar(se),cr(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?lh(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:gi(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),nt,this.safe(e.agentId),t);ae(s)||sh(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);oh(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(),nt,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 g=G(a,l);if(ae(g))try{for(let m of ke(g)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let S=Math.floor((s-y)/36e5),x=t-1-S;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),nt);if(!ae(e))return 0;let t=0;for(let s of ke(e)){let r=G(e,s),o;try{o=ke(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=ke(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(Rt(G(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hh){let t=G(process.cwd(),nt);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ke(t)){let i=G(t,o),a;try{a=ke(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{rh(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),nt,this.safe(e));if(!ae(s))return[];let r=ke(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=ke(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(Rt(G(a,c),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),nt,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ke(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(Rt(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=>!Yt(t,void 0,Xt(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=os();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||$e(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){dh.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=ht(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let 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}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!Si(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(d=>d.channel===s&&d.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(tn(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(tn(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}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 g=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:g,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);Z().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(g).toISOString(),sender:{name:s},humanRoot:!1,person:Yr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:g});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=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=g=>{u||(u=!0,c(g))};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:g=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:g,queued:!1})}).then(g=>{$e(g.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):g.error?l({ok:!1,status:500,error:g.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>l({ok:!1,status:500,error:g?.message??String(g)}))})}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 Ih(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(`
202
+ `)}export{vh as a,$i as b,Qi as c,Gh as d,Kh as e,Jh as f,Yi as g,ny as h,ml as i,Zi as j,cn as k,yy as l,Sy as m,ky as n,$y as o,ht as p,jl as q,va as r,ql as s,Gl as t,Kl as u,Ma as v,hn as w,Oa as x,ow as y,yn as z,hg as A,uw as B,lw as C,pw as D,As as E,hw as F,yw as G,bt as H,Ya as I,bn as J,Cg as K,xw as L,Rs as M,Z as N,pd as O,zg as P,Vg as Q,hd as R,jw as S,yd as T,Id as U,Zw as V,eb as W,Rd as X,tb as Y,_d as Z,vn as _,ub as $,lb as aa,kt as ba,cm as ca,um as da,lm as ea,gm as fa,pm as ga,Hs as ha,qb as ia,Gb as ja,Im as ka,wc as la,_n as ma,Jb as na,Pn as oa,En as pa,$c as qa,At as ra,Mc as sa,ex as ta,tx as ua,nx as va,sx as wa,rx as xa,ox as ya,ix as za,Xm as Aa,Uc as Ba,tt as Ca,eu as Da,rr as Ea,xx as Fa,kx as Ga,Tx as Ha,ch as Ia,uh as Ja,a0 as Ka,d0 as La,lh as Ma,fh as Na,yh as Oa,wh as Pa,xh as Qa,or as Ra,uu as Sa,lu as Ta,kh as Ua,gu as Va,pu as Wa,Ih as Xa};
203
+ //# sourceMappingURL=chunk-4GUFZT5S.js.map