agentix-cli 0.164.0 → 0.165.1

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 (134) hide show
  1. package/dist/{App-4PQX4N6S.js → App-NV2JJMHN.js} +2 -2
  2. package/dist/{ChatApp-NHB5VPUE.js → ChatApp-CIGDPS3A.js} +2 -2
  3. package/dist/{absorb-eval-PWLEKRFA.js → absorb-eval-VPAASHZG.js} +2 -2
  4. package/dist/{agent-USWAFKWO.js → agent-UFMIPTQZ.js} +2 -2
  5. package/dist/{board-dashboard-F2TCMJCZ.js → board-dashboard-NUEVGTM7.js} +551 -385
  6. package/dist/board-dashboard-NUEVGTM7.js.map +1 -0
  7. package/dist/{chunk-K7ZUE7SG.js → chunk-4SJ2VFVI.js} +2 -2
  8. package/dist/{chunk-EGCWS56X.js → chunk-6Y53LLIX.js} +2 -2
  9. package/dist/{chunk-H4DQGVUG.js → chunk-73SESASJ.js} +2 -2
  10. package/dist/{chunk-AM2DYH7Y.js → chunk-A3GDFLFB.js} +2 -2
  11. package/dist/{chunk-MYEEWFXP.js → chunk-AXDNFXYU.js} +2 -2
  12. package/dist/{chunk-EJFJBYDJ.js → chunk-BC7VOHNH.js} +2 -2
  13. package/dist/{chunk-3S2BNZHX.js → chunk-CDPQQAK6.js} +2 -2
  14. package/dist/{chunk-QLN4W2KV.js → chunk-CGE5EAWC.js} +2 -2
  15. package/dist/{chunk-C65BZPUE.js → chunk-CRUNUMVO.js} +2 -2
  16. package/dist/{chunk-CLHIE4UW.js → chunk-DAWJHJKD.js} +10 -10
  17. package/dist/{chunk-CLHIE4UW.js.map → chunk-DAWJHJKD.js.map} +1 -1
  18. package/dist/{chunk-KDDCIOS7.js → chunk-EXJGRK2N.js} +2 -2
  19. package/dist/{chunk-IMERQYQ6.js → chunk-FK2TJZNJ.js} +2 -2
  20. package/dist/{chunk-JCOLQ6MO.js → chunk-GJ4SQRAE.js} +2 -2
  21. package/dist/{chunk-6JFGNRC3.js → chunk-ILHTAVZZ.js} +6 -6
  22. package/dist/{chunk-6JFGNRC3.js.map → chunk-ILHTAVZZ.js.map} +1 -1
  23. package/dist/{chunk-KKOULF3I.js → chunk-IVTO54EM.js} +2 -2
  24. package/dist/{chunk-GJMXUROS.js → chunk-KTJ6234K.js} +268 -268
  25. package/dist/chunk-KTJ6234K.js.map +1 -0
  26. package/dist/{chunk-TW2PBGYA.js → chunk-KVSHZKAL.js} +2 -2
  27. package/dist/{chunk-CR55SCRE.js → chunk-NCEYJFF5.js} +2 -2
  28. package/dist/{chunk-UD3WIY2B.js → chunk-ON7Y3JSP.js} +3 -3
  29. package/dist/{chunk-HGQKZKXL.js → chunk-PSTEWKR3.js} +2 -2
  30. package/dist/{chunk-I53O35TO.js → chunk-QT63Q6C5.js} +2 -2
  31. package/dist/{chunk-Z5JVYKVH.js → chunk-RUB4HZEG.js} +2 -2
  32. package/dist/{chunk-UY64KKNE.js → chunk-S6ZZKRDB.js} +2 -2
  33. package/dist/{chunk-BRNAE6ET.js → chunk-T5IGXFSW.js} +2 -2
  34. package/dist/{chunk-OO7T7E4O.js → chunk-TADIDWYZ.js} +2 -2
  35. package/dist/{chunk-XG5FRD7G.js → chunk-UEEB3UTU.js} +9 -8
  36. package/dist/{chunk-XG5FRD7G.js.map → chunk-UEEB3UTU.js.map} +1 -1
  37. package/dist/{chunk-MK3H5LQT.js → chunk-V7R5AJVN.js} +2 -2
  38. package/dist/{chunk-DLTJCOEN.js → chunk-Y6JSB5II.js} +2 -2
  39. package/dist/{chunk-343WTR6F.js → chunk-YUGYKMY6.js} +2 -2
  40. package/dist/cli.js +1 -1
  41. package/dist/{client-3JLER5ZO.js → client-D3CYQPUD.js} +2 -2
  42. package/dist/{config-HHNGJKVW.js → config-OTO56OCX.js} +2 -2
  43. package/dist/config-mutate-5KKGQHC6.js +2 -0
  44. package/dist/config-mutator-XBUGJZER.js +2 -0
  45. package/dist/{contributions-6M3TIP57.js → contributions-SMSYSHPU.js} +2 -2
  46. package/dist/{doctor-TOLXE6QQ.js → doctor-5PFLKGNU.js} +2 -2
  47. package/dist/{follow-up-tool-Q44GNGWF.js → follow-up-tool-ME4DV7HT.js} +2 -2
  48. package/dist/hub-WGUNZ2D5.js +2 -0
  49. package/dist/index.d.ts +17 -0
  50. package/dist/index.js +1 -1
  51. package/dist/{program-PMD6BM3U.js → program-GBPLSXFF.js} +23 -23
  52. package/dist/{promote-JLFDSQFH.js → promote-TQ3OZ7EC.js} +2 -2
  53. package/dist/{query-KNZ3EMHA.js → query-M4VWXBHF.js} +2 -2
  54. package/dist/{query-settings-XRNZOOWV.js → query-settings-Y4PWFLYK.js} +2 -2
  55. package/dist/{registry-EHLXMVUV.js → registry-GLNCV3KP.js} +2 -2
  56. package/dist/{request-planner-T5GKPGQT.js → request-planner-FE3C2QFQ.js} +2 -2
  57. package/dist/{review-candidates-HSKH2UGT.js → review-candidates-R7QKVGMQ.js} +2 -2
  58. package/dist/routing-6J4OHUJS.js +2 -0
  59. package/dist/schedule-tool-FE3TWOGS.js +2 -0
  60. package/dist/scheduler-XDLJAWGC.js +2 -0
  61. package/dist/{seat-OSYVYKBK.js → seat-35AZG54F.js} +2 -2
  62. package/dist/{select-I5JLTJKJ.js → select-6PC26YUI.js} +2 -2
  63. package/dist/{set-enabled-Q5EPYA33.js → set-enabled-UJOLDPZV.js} +2 -2
  64. package/dist/{surface-usage-W33HGXMP.js → surface-usage-Y7D5W52I.js} +2 -2
  65. package/dist/{tool-SM3FPKK6.js → tool-LAMDUPTX.js} +2 -2
  66. package/dist/{tool-ZDGA6CTA.js → tool-QLIJQQ7W.js} +2 -2
  67. package/dist/wiki-W7L5EJTZ.js +2 -0
  68. package/dist/wiki-enrich-3ZCL5TEC.js +2 -0
  69. package/package.json +1 -1
  70. package/dist/board-dashboard-F2TCMJCZ.js.map +0 -1
  71. package/dist/chunk-GJMXUROS.js.map +0 -1
  72. package/dist/config-mutate-CP2TIY2J.js +0 -2
  73. package/dist/config-mutator-ZSW4PTO5.js +0 -2
  74. package/dist/hub-H4AW5H7E.js +0 -2
  75. package/dist/routing-C66W2E3P.js +0 -2
  76. package/dist/schedule-tool-3Z45TBN6.js +0 -2
  77. package/dist/scheduler-TZJJGRAE.js +0 -2
  78. package/dist/wiki-NAE25PMF.js +0 -2
  79. package/dist/wiki-enrich-3XXN4XCV.js +0 -2
  80. /package/dist/{App-4PQX4N6S.js.map → App-NV2JJMHN.js.map} +0 -0
  81. /package/dist/{ChatApp-NHB5VPUE.js.map → ChatApp-CIGDPS3A.js.map} +0 -0
  82. /package/dist/{absorb-eval-PWLEKRFA.js.map → absorb-eval-VPAASHZG.js.map} +0 -0
  83. /package/dist/{agent-USWAFKWO.js.map → agent-UFMIPTQZ.js.map} +0 -0
  84. /package/dist/{chunk-K7ZUE7SG.js.map → chunk-4SJ2VFVI.js.map} +0 -0
  85. /package/dist/{chunk-EGCWS56X.js.map → chunk-6Y53LLIX.js.map} +0 -0
  86. /package/dist/{chunk-H4DQGVUG.js.map → chunk-73SESASJ.js.map} +0 -0
  87. /package/dist/{chunk-AM2DYH7Y.js.map → chunk-A3GDFLFB.js.map} +0 -0
  88. /package/dist/{chunk-MYEEWFXP.js.map → chunk-AXDNFXYU.js.map} +0 -0
  89. /package/dist/{chunk-EJFJBYDJ.js.map → chunk-BC7VOHNH.js.map} +0 -0
  90. /package/dist/{chunk-3S2BNZHX.js.map → chunk-CDPQQAK6.js.map} +0 -0
  91. /package/dist/{chunk-QLN4W2KV.js.map → chunk-CGE5EAWC.js.map} +0 -0
  92. /package/dist/{chunk-C65BZPUE.js.map → chunk-CRUNUMVO.js.map} +0 -0
  93. /package/dist/{chunk-KDDCIOS7.js.map → chunk-EXJGRK2N.js.map} +0 -0
  94. /package/dist/{chunk-IMERQYQ6.js.map → chunk-FK2TJZNJ.js.map} +0 -0
  95. /package/dist/{chunk-JCOLQ6MO.js.map → chunk-GJ4SQRAE.js.map} +0 -0
  96. /package/dist/{chunk-KKOULF3I.js.map → chunk-IVTO54EM.js.map} +0 -0
  97. /package/dist/{chunk-TW2PBGYA.js.map → chunk-KVSHZKAL.js.map} +0 -0
  98. /package/dist/{chunk-CR55SCRE.js.map → chunk-NCEYJFF5.js.map} +0 -0
  99. /package/dist/{chunk-UD3WIY2B.js.map → chunk-ON7Y3JSP.js.map} +0 -0
  100. /package/dist/{chunk-HGQKZKXL.js.map → chunk-PSTEWKR3.js.map} +0 -0
  101. /package/dist/{chunk-I53O35TO.js.map → chunk-QT63Q6C5.js.map} +0 -0
  102. /package/dist/{chunk-Z5JVYKVH.js.map → chunk-RUB4HZEG.js.map} +0 -0
  103. /package/dist/{chunk-UY64KKNE.js.map → chunk-S6ZZKRDB.js.map} +0 -0
  104. /package/dist/{chunk-BRNAE6ET.js.map → chunk-T5IGXFSW.js.map} +0 -0
  105. /package/dist/{chunk-OO7T7E4O.js.map → chunk-TADIDWYZ.js.map} +0 -0
  106. /package/dist/{chunk-MK3H5LQT.js.map → chunk-V7R5AJVN.js.map} +0 -0
  107. /package/dist/{chunk-DLTJCOEN.js.map → chunk-Y6JSB5II.js.map} +0 -0
  108. /package/dist/{chunk-343WTR6F.js.map → chunk-YUGYKMY6.js.map} +0 -0
  109. /package/dist/{client-3JLER5ZO.js.map → client-D3CYQPUD.js.map} +0 -0
  110. /package/dist/{config-HHNGJKVW.js.map → config-OTO56OCX.js.map} +0 -0
  111. /package/dist/{config-mutate-CP2TIY2J.js.map → config-mutate-5KKGQHC6.js.map} +0 -0
  112. /package/dist/{config-mutator-ZSW4PTO5.js.map → config-mutator-XBUGJZER.js.map} +0 -0
  113. /package/dist/{contributions-6M3TIP57.js.map → contributions-SMSYSHPU.js.map} +0 -0
  114. /package/dist/{doctor-TOLXE6QQ.js.map → doctor-5PFLKGNU.js.map} +0 -0
  115. /package/dist/{follow-up-tool-Q44GNGWF.js.map → follow-up-tool-ME4DV7HT.js.map} +0 -0
  116. /package/dist/{hub-H4AW5H7E.js.map → hub-WGUNZ2D5.js.map} +0 -0
  117. /package/dist/{program-PMD6BM3U.js.map → program-GBPLSXFF.js.map} +0 -0
  118. /package/dist/{promote-JLFDSQFH.js.map → promote-TQ3OZ7EC.js.map} +0 -0
  119. /package/dist/{query-KNZ3EMHA.js.map → query-M4VWXBHF.js.map} +0 -0
  120. /package/dist/{query-settings-XRNZOOWV.js.map → query-settings-Y4PWFLYK.js.map} +0 -0
  121. /package/dist/{registry-EHLXMVUV.js.map → registry-GLNCV3KP.js.map} +0 -0
  122. /package/dist/{request-planner-T5GKPGQT.js.map → request-planner-FE3C2QFQ.js.map} +0 -0
  123. /package/dist/{review-candidates-HSKH2UGT.js.map → review-candidates-R7QKVGMQ.js.map} +0 -0
  124. /package/dist/{routing-C66W2E3P.js.map → routing-6J4OHUJS.js.map} +0 -0
  125. /package/dist/{schedule-tool-3Z45TBN6.js.map → schedule-tool-FE3TWOGS.js.map} +0 -0
  126. /package/dist/{scheduler-TZJJGRAE.js.map → scheduler-XDLJAWGC.js.map} +0 -0
  127. /package/dist/{seat-OSYVYKBK.js.map → seat-35AZG54F.js.map} +0 -0
  128. /package/dist/{select-I5JLTJKJ.js.map → select-6PC26YUI.js.map} +0 -0
  129. /package/dist/{set-enabled-Q5EPYA33.js.map → set-enabled-UJOLDPZV.js.map} +0 -0
  130. /package/dist/{surface-usage-W33HGXMP.js.map → surface-usage-Y7D5W52I.js.map} +0 -0
  131. /package/dist/{tool-SM3FPKK6.js.map → tool-LAMDUPTX.js.map} +0 -0
  132. /package/dist/{tool-ZDGA6CTA.js.map → tool-QLIJQQ7W.js.map} +0 -0
  133. /package/dist/{wiki-NAE25PMF.js.map → wiki-W7L5EJTZ.js.map} +0 -0
  134. /package/dist/{wiki-enrich-3XXN4XCV.js.map → wiki-enrich-3ZCL5TEC.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-BRNAE6ET.js";import{a as w}from"./chunk-VUEQ4SL5.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-H4DQGVUG.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-3S2BNZHX.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{b as Ae,da as Xt,fa as oe,ga as Ie,ia as Te}from"./chunk-MYEEWFXP.js";import{q as zt}from"./chunk-HGQKZKXL.js";import{a as Bt,b as Ht}from"./chunk-C65BZPUE.js";import{ab as Ee,ba as Mt,ca as Ut,ea as Ft,fa as Wt,jb as qt,kb as jt,p as se,q as Ot,r as Pt,s as Ns,tb as Vt}from"./chunk-KKOULF3I.js";import{a as Re,h as Ls}from"./chunk-BRK6M6LA.js";import{i as _e,q as Os}from"./chunk-XG5FRD7G.js";import{existsSync as Ps,readdirSync as Ms,readFileSync as Us,statSync as Fs}from"fs";import{resolve as Ws}from"path";function hn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function rc(t,e=1e3){if(!Ps(t))return[];let n=Ms(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Ws(t,o);return{path:i,mtime:Fs(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=qs(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function qs(t,e){try{let n=Us(t,"utf-8").split(`
1
+ import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-T5IGXFSW.js";import{a as w}from"./chunk-VUEQ4SL5.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-73SESASJ.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-CDPQQAK6.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{b as Ae,da as Xt,fa as oe,ga as Ie,ia as Te}from"./chunk-AXDNFXYU.js";import{q as zt}from"./chunk-PSTEWKR3.js";import{a as Bt,b as Ht}from"./chunk-CRUNUMVO.js";import{ab as Ee,ba as Mt,ca as Ut,ea as Ft,fa as Wt,jb as qt,kb as jt,p as se,q as Ot,r as Pt,s as Ns,tb as Vt}from"./chunk-IVTO54EM.js";import{a as Re,h as Ls}from"./chunk-BRK6M6LA.js";import{j as _e,r as Os}from"./chunk-UEEB3UTU.js";import{existsSync as Ps,readdirSync as Ms,readFileSync as Us,statSync as Fs}from"fs";import{resolve as Ws}from"path";function hn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function rc(t,e=1e3){if(!Ps(t))return[];let n=Ms(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Ws(t,o);return{path:i,mtime:Fs(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=qs(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function qs(t,e){try{let n=Us(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var js={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Vs=(t,e,n)=>{try{return zt(t,e,n)}catch{return null}},bn=864e5;function ac(t){let e=t.now??Date.now(),n={...js,...t.thresholds},r=t.nextFire??Vs,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],d=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:E(a.id,k.text),trigger:{schedule:E(a.schedule,k.text),timezone:d},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Le(a.nextRun)??Le(r(a.schedule,new Date(e),d)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Gs(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:yn(c),sampledRuns:l.length,flags:[],attention:null};p.flags=wn(p,c,a.schedule,d,null,e,n,r),s.push(kn(p))}let o=new Map(hn(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(T=>T.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let d=l.config??{},c=a.state||"active",u=c==="active",p=(i.get(a.id)??[]).slice().sort((T,$e)=>$e.at-T.at),g=p.map(T=>({at:T.at,status:zs(T.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof d.spec=="string"?d.spec:"",x=typeof d.timezone=="string"?d.timezone:"UTC",F={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:E(a.title||a.id,k.text),trigger:m?{schedule:E(b,k.text),timezone:x}:{event:E(typeof d.event=="string"?d.event:"",k.text),filters:Ks(d.filter,a)},agent:Xs(a),enabled:u,state:c,nextRunAt:m&&u&&b?Le(r(b,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let T=g.find($e=>$e.status==="success");return T?new Date(T.at).toISOString():null})(),consecutiveFailures:yn(g),sampledRuns:p.length,flags:[],attention:null},re=Date.parse(a.updated||a.created||"");F.flags=m?wn(F,g,b,x,Number.isFinite(re)?re:null,e,n,r):Bs(F,o.get(a.id)?.state==="dormant",Number.isFinite(re)?re:null,e,n),s.push(kn(F))}return s.sort(Hs).slice(0,k.routines)}function yn(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function wn(t,e,n,r,s,o,i,a){let l=[],d=e.length?e[0].at:null;if(!t.enabled){let p=xn(d,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),d===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(d),u=null;for(let p=0;p<i.missedFires&&(u=a(n,c,r),!!u);p++)c=u;return u&&o>u.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(d).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Bs(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=xn(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function xn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*bn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/bn)} days`:"Disabled and never ran"}}function kn(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Sn={critical:0,warning:1,info:2};function Hs(t,e){let n=t.attention?Sn[t.attention]:3,r=e.attention?Sn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function zs(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Xs(t){if(t.ownerAgent)return E(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?E(String(e.config.agentId),k.text):null}function Ks(t,e){let n=[],r=e?.project;if(r&&n.push(E(`project=${r}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(E(`${s}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function E(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Gs(t,e){return t===void 0?void 0:E(t,e)}import{mkdirSync as Js,readFileSync as Ys,renameSync as Zs,writeFileSync as Qs}from"fs";import{resolve as eo}from"path";function vn(t){return eo(Ce(t),"_state.json")}function v(t){try{let e=JSON.parse(Ys(vn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function K(t,e){Js(Ce(t),{recursive:!0});let n=vn(t),r=`${n}.${process.pid}.tmp`;Qs(r,JSON.stringify(e,null,2)+`
3
3
  `),Zs(r,n)}function $n(t,e,n,r=Date.now()){let s=v(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),K(t,{...s,snoozed:o})}function pc(t,e){K(t,{...v(t),lastDigest:e})}function Oe(t,e,n,r=Date.now()){let s=v(t),o=new Set(n),i={};for(let[l,d]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=d);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));K(t,{...s,popped:i,wanted:a})}function Rn(t,e){let n=v(t);K(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function gc(t,e=Date.now()){K(t,{...v(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as to,readFileSync as no}from"fs";Vt();Ls();function _n(t){let e=Bt(t),n={};if(to(e))try{n=qt(JSON.parse(no(e,"utf-8")))}catch{n={}}let r=Ee.safeParse(n?.requests);return r.success?r.data:Ee.parse(void 0)}async function wc(t,e={}){let n=(t.channels??[]).filter(r=>!Re.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Re].join(", ")}`}:Ht(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as G,readdirSync as bo,readFileSync as yo}from"fs";import{resolve as A}from"path";import{randomBytes as In}from"crypto";import{existsSync as so,mkdirSync as oo,readdirSync as io,readFileSync as ao,renameSync as Tn,unlinkSync as lo,writeFileSync as co}from"fs";import{resolve as Dn}from"path";function En(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ro=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function An(t,e,n,r=Ne){let s=await r(t.bin,[...En(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ro(s.stderr||s.stdout)}`}}async function xc(t,e,n,r,s=Ne){return(await s(t.bin,[...En(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var uo=2e3,po=t=>An(t.wacli,t.to,t.text);function Pe(t){return Dn(t,".agentx","whatsapp-triage","drafts")}var go=t=>/^[a-z0-9-]{8,64}$/.test(t),ae=(t,e)=>Dn(Pe(t),`${e}.json`);function Cn(t,e){oo(Pe(t),{recursive:!0});let n=ae(t,e.id),r=`${n}.${process.pid}.tmp`;co(r,JSON.stringify(e,null,2)+`
@@ -575,4 +575,4 @@ Document the arguments, commands, or files the skill expects. Example:
575
575
  claude-code ${Lt(t)} --arg value
576
576
  \`\`\`
577
577
  `}Vt();var Is={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Ts(t){return{...Is,...t??{},regions:{...t?.regions??{}},buffer:{...Is.buffer,...t?.buffer??{}}}}function pg(t){try{return Ts(jt(t).screen)}catch{return Ts(void 0)}}var ec=/^[a-z][\w-]*$/,Ds=["window","screen","menubar","notifications"];function ne(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var ve=(t,e)=>ne(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Cs(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function gg(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ve(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ve(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ve(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ne(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ne(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!ec.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Cs(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=ne(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=ne(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=ve(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!Ds.includes(r)&&!n.regions?.[r])try{Cs(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ds,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{hn as a,rc as b,pt as c,Xi as d,Ki as e,tu as f,nu as g,ru as h,iu as i,au as j,lu as k,Ir as l,Tr as m,cu as n,Dr as o,uu as p,gu as q,N as r,Cr as s,k as t,ac as u,Or as v,wu as w,xu as x,Mr as y,vu as z,Ur as A,$u as B,Z as C,Sa as D,Ru as E,_u as F,Wr as G,xc as H,po as I,Ac as J,Ln as K,v as L,pc as M,gc as N,Dc as O,ce as P,Cc as Q,_n as R,wc as S,P as T,Kc as U,jn as V,Vn as W,Co as X,No as Y,Yc as Z,Zc as _,Wo as $,nd as aa,jr as ba,Iu as ca,od as da,id as ea,Rr as fa,rt as ga,Wi as ha,ts as ia,op as ja,ip as ka,il as la,dp as ma,as as na,up as oa,pp as pa,yp as qa,bl as ra,wp as sa,ld as ta,cd as ua,dd as va,ud as wa,pd as xa,gd as ya,md as za,hd as Aa,Rd as Ba,Ke as Ca,_d as Da,Ed as Ea,J as Fa,Y as Ga,vl as Ha,Ap as Ia,Ip as Ja,Tp as Ka,Dp as La,xt as Ma,Cp as Na,Ye as Oa,Ze as Pa,he as Qa,pi as Ra,fi as Sa,Cd as Ta,et as Ua,tt as Va,mi as Wa,hi as Xa,fr as Ya,yr as Za,Nd as _a,wi as $a,Ld as ab,Ei as bb,Ti as cb,nt as db,Ci as eb,wr as fb,L as gb,ys as hb,ws as ib,ks as jb,$t as kb,Up as lb,Cl as mb,xs as nb,vs as ob,Gp as pb,Jp as qb,Kl as rb,Yp as sb,Rs as tb,be as ub,zd as vb,dt as wb,Qd as xb,tg as yb,ng as zb,rg as Ab,sg as Bb,og as Cb,ig as Db,ag as Eb,lg as Fb,cg as Gb,Is as Hb,Ts as Ib,pg as Jb,Ds as Kb,gg as Lb};
578
- //# sourceMappingURL=chunk-KDDCIOS7.js.map
578
+ //# sourceMappingURL=chunk-EXJGRK2N.js.map
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-JCOLQ6MO.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
1
+ import{d as h}from"./chunk-GJ4SQRAE.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
2
  `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
4
  `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
5
  `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
- //# sourceMappingURL=chunk-IMERQYQ6.js.map
6
+ //# sourceMappingURL=chunk-FK2TJZNJ.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-UD3WIY2B.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
1
+ import{e as g}from"./chunk-ON7Y3JSP.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
2
2
  `)}).join(`
3
3
 
4
4
  ---
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
14
14
 
15
15
  ${i}
16
16
  `}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
17
- //# sourceMappingURL=chunk-JCOLQ6MO.js.map
17
+ //# sourceMappingURL=chunk-GJ4SQRAE.js.map
@@ -1,4 +1,4 @@
1
- import{B as Rt,D as Dr,P as Nr,Q as Lr,R as Ur,T as Fr,U as Hr,V as Br,W as jr,Z as Wr,_ as qr,a as xr,b as Sr,ba as Gr,ca as Kr,d as Sn,f as Xe,ha as Jr,i as Pr,ja as zr,l as Ct,n as Er,t as Mt,u as Or}from"./chunk-MYEEWFXP.js";import{b as Ir}from"./chunk-MEFPXHQJ.js";import{a as vn}from"./chunk-W4YR2RO2.js";import{a as br}from"./chunk-VL74KOR7.js";import{b as kr,c as kn,d as $r,e as At,h as Ar}from"./chunk-HGQKZKXL.js";import{e as hr,f as yr,g as wr}from"./chunk-XIRM45DH.js";import{a as In,b as Tr}from"./chunk-J3SOEFRE.js";import{a as Tn,b as vr}from"./chunk-SIU6STB2.js";import{e as Cr,i as Mr,j as Rr,k as _r}from"./chunk-X5C5W3E4.js";import{a as mr}from"./chunk-CR55SCRE.js";import{g as pr,h as fr}from"./chunk-EJFJBYDJ.js";import{c as tr,f as nr}from"./chunk-MK3H5LQT.js";import{s as Vs,v as $t,w as er,y as we,z as xn}from"./chunk-I53O35TO.js";import{a as Qe,b as Oe,f as vt}from"./chunk-72SZI2UW.js";import{a as Ee,b as mn}from"./chunk-FCPTN6NF.js";import{a as sr,c as rr}from"./chunk-MYVHVJWZ.js";import{e as De,h as or,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as ir,b as ar,c as dr,d as cr,l as ur}from"./chunk-AV7T3SYT.js";import{a as lr,b as gr}from"./chunk-TM2TPQKH.js";import{c as Bs,d as js}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Aa as Js,Ea as bd,Ka as zs,La as bn,Ma as Qs,Na as ze,Oa as Xs,Pa as Ys,Va as Zs,sa as Ks,tb as xd,va as wn,xa as wd}from"./chunk-KKOULF3I.js";import{g as Je,h as hd}from"./chunk-BRK6M6LA.js";import{i as yn,q as yd}from"./chunk-XG5FRD7G.js";import{a as Ws,b as pe,c as qs,d as Gs,e as hn}from"./chunk-2QNT5JDS.js";xn();vt();var _t="tool-set",Qr=["answer","code","full"],Xr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Sd=.1;function Zr(n){return{task:Yr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Yr(n.agentPrompt,600)}:{}}}var Vr={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function eo(n,e=Sd){let s=n?.bundle?.probabilities;if(!s)return"full";let r=$n(s.answer),o=$n(s.code),i=$n(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function to(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Xr.answer.includes(t))?"answer":e.every(t=>Xr.code.includes(t))?"code":"full"}function no(n,e){return Qr.indexOf(n)<Qr.indexOf(e)}function $n(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Yr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var so=!1;function ro(n,e){let t=$t(_t);if(t!=="off")return t==="active"&&!so&&(so=!0,e(`[decisions] seat "${_t}" is set to active, but only shadow is built: it records and changes nothing`)),we(_t,Zr(n),Vr,{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=eo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function oo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=to(r);er(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}`+(no(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Id(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function io(n,e){let t=Id(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 An(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)`}xn();vt();var ao="session-continuity",co={continues:Qe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Qe("Does the new request refer to something stated earlier in the conversation?")};function uo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Cn(n.message,1200),previousRequest:n.previousMessage?Cn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Cn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function lo(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 Cn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ht}from"execa";import{spawn as Td}from"node:child_process";import{createHash as kd}from"node:crypto";import{createInterface as vd}from"node:readline";var be=class extends Error{},$d=n=>Td("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),Mn=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(),vd({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{B as Rt,D as Dr,P as Nr,Q as Lr,R as Ur,T as Fr,U as Hr,V as Br,W as jr,Z as Wr,_ as qr,a as xr,b as Sr,ba as Gr,ca as Kr,d as Sn,f as Xe,ha as Jr,i as Pr,ja as zr,l as Ct,n as Er,t as Mt,u as Or}from"./chunk-AXDNFXYU.js";import{b as Ir}from"./chunk-MEFPXHQJ.js";import{a as vn}from"./chunk-W4YR2RO2.js";import{a as br}from"./chunk-VL74KOR7.js";import{b as kr,c as kn,d as $r,e as At,h as Ar}from"./chunk-PSTEWKR3.js";import{e as hr,f as yr,g as wr}from"./chunk-XIRM45DH.js";import{a as In,b as Tr}from"./chunk-J3SOEFRE.js";import{a as Tn,b as vr}from"./chunk-SIU6STB2.js";import{e as Cr,i as Mr,j as Rr,k as _r}from"./chunk-X5C5W3E4.js";import{a as mr}from"./chunk-NCEYJFF5.js";import{g as pr,h as fr}from"./chunk-BC7VOHNH.js";import{c as tr,f as nr}from"./chunk-V7R5AJVN.js";import{s as Vs,v as $t,w as er,y as we,z as xn}from"./chunk-QT63Q6C5.js";import{a as Qe,b as Oe,f as vt}from"./chunk-72SZI2UW.js";import{a as Ee,b as mn}from"./chunk-FCPTN6NF.js";import{a as sr,c as rr}from"./chunk-MYVHVJWZ.js";import{e as De,h as or,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as ir,b as ar,c as dr,d as cr,l as ur}from"./chunk-AV7T3SYT.js";import{a as lr,b as gr}from"./chunk-TM2TPQKH.js";import{c as Bs,d as js}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Aa as Js,Ea as bd,Ka as zs,La as bn,Ma as Qs,Na as ze,Oa as Xs,Pa as Ys,Va as Zs,sa as Ks,tb as xd,va as wn,xa as wd}from"./chunk-IVTO54EM.js";import{g as Je,h as hd}from"./chunk-BRK6M6LA.js";import{j as yn,r as yd}from"./chunk-UEEB3UTU.js";import{a as Ws,b as pe,c as qs,d as Gs,e as hn}from"./chunk-2QNT5JDS.js";xn();vt();var _t="tool-set",Qr=["answer","code","full"],Xr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Sd=.1;function Zr(n){return{task:Yr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Yr(n.agentPrompt,600)}:{}}}var Vr={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function eo(n,e=Sd){let s=n?.bundle?.probabilities;if(!s)return"full";let r=$n(s.answer),o=$n(s.code),i=$n(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function to(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Xr.answer.includes(t))?"answer":e.every(t=>Xr.code.includes(t))?"code":"full"}function no(n,e){return Qr.indexOf(n)<Qr.indexOf(e)}function $n(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Yr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var so=!1;function ro(n,e){let t=$t(_t);if(t!=="off")return t==="active"&&!so&&(so=!0,e(`[decisions] seat "${_t}" is set to active, but only shadow is built: it records and changes nothing`)),we(_t,Zr(n),Vr,{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=eo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function oo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=to(r);er(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}`+(no(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Id(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function io(n,e){let t=Id(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 An(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)`}xn();vt();var ao="session-continuity",co={continues:Qe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Qe("Does the new request refer to something stated earlier in the conversation?")};function uo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Cn(n.message,1200),previousRequest:n.previousMessage?Cn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Cn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function lo(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 Cn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ht}from"execa";import{spawn as Td}from"node:child_process";import{createHash as kd}from"node:crypto";import{createInterface as vd}from"node:readline";var be=class extends Error{},$d=n=>Td("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),Mn=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(),vd({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Rn=class{constructor(e=$d,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=kd("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[A])=>x.localeCompare(A))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new be("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,A])=>!A.connection.busy);if(!x)throw new be("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new Mn(e,this.launchProcess)}}catch{throw new be("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,m=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),y=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(y),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let R=new Promise((O,$)=>{i.failTurn=$,i.notify=(L,N)=>{if(N?.threadId!==u)return;let D=N.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:L.replace("/","."),...D?{item:{...D,type:W[D.type]||D.type}}:{}}),L==="item/completed"&&D?.type==="agentMessage"&&D.phase==="final_answer"&&(d=D.text),L==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=N.delta,e.onDelta?.(N.delta,c)),L==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}L==="turn/completed"&&(N.turn.status==="completed"?O():$(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return R.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await R,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new be(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(y),clearTimeout(b),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},go=new Rn;import{execFile as Jd}from"child_process";import{StringDecoder as tt}from"string_decoder";import{mkdtempSync as Ro,readFileSync as _o,rmSync as Po}from"fs";import{join as Ut}from"path";import{tmpdir as Eo}from"os";function Pt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Et(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Ot(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var po=null;function Dt(){return po}function Jg(n){po=n}function Ye(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Ad(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Ne=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},fo=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Ye(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Ad(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Ne(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Ne(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ye(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Ye(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Cd}from"child_process";import{randomUUID as Md}from"crypto";import{existsSync as Rd,readFileSync as _d}from"fs";import{resolve as Pd}from"path";function Ed(n){let e=Pd(n,"CLAUDE.md");if(!Rd(e))return null;try{let t=_d(e,"utf8");return ur(t)}catch{return null}}var Od=20*60*1e3,Dd=5e3,Ze=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Nd(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var mo=class{constructor(e={}){this.opts=e}spawn(e,t){return new _n(e,t,this.opts)}},_n=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Cd(r,o,{cwd:t.workspace,env:Ce(Nd({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Ed(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(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=Md(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??Od,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ze(c)),l=!1,p=null;try{for(;;){let m=d-Date.now();if(m<=0)throw u();let h=await this.nextEvent(m);if(h===null&&this.killReason)throw new Ve(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let b=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Dd);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
4
  `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};hn();yd();mn();import{resolve as ho,join as yo}from"path";var Ld=4e3;function Nt(n){try{let e=yo(ho(n.root),".agentx","db.sqlite"),t=yn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,Ld):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function Qd(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,l)}};O.stdout?.on("data",T=>{D+=F.write(T);let S=D.split(`
32
32
  `);D=S.pop()||"";for(let U of S)z(U)}),O.stderr?.on("data",T=>{W+=q.write(T)});let C=await O;if(i&&i.removeEventListener("abort",N),D+=F.end(),D.trim()&&z(D),W+=q.end(),$)return{content:"",error:L||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(C.exitCode!==0||h){let T=C,S;return T.timedOut?S=`OpenCode timed out after ${Math.round(A/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?S=Ao():S=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(S),duration:Date.now()-c,usage:p,opencodeSessionId:m}}return y=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch(A){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let R=/ENOENT|spawn opencode/i.test(A?.message||"")?Ao():A?.message;return{content:l,...V(R||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:m}}finally{x?.(),b?.release(y)}}async function ic(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function ac(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let b=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let y=n.provider||"claude-code",x=s?`${s}
33
33
 
34
- ${e.message}`:e.message,A=e.context?.sender,R=typeof A=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(A),O=e.context?.channel==="web-chat"&&R?{userId:A,agentId:e.agentId||"acme-public"}:void 0,$=cr(n),L=Object.keys($).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:L?$:void 0};if(r){let{generateStream:z}=await import("./agent-USWAFKWO.js"),C="",T,S,U,B;for await(let _ of z(N)){if(c)try{c(_)}catch{}if(_.type==="text_delta")C+=_.text,r(_.text,C);else if(_.type==="thinking_delta")_.text&&i&&i(_.text);else if(_.type==="generate_result"){if(_.result.content&&_.result.content!==C){let Q=_.result.content.slice(C.length);Q?(C=_.result.content,r(Q,C)):C=_.result.content}T=_.result.tokensUsed,_.result.inputTokens!=null&&(S=_.result.inputTokens),_.result.outputTokens!=null&&(U=_.result.outputTokens)}else if(_.type==="done"){if(_.result.content&&_.result.content!==C){let Q=_.result.content.slice(C.length);Q?(C=_.result.content,r(Q,C)):C=_.result.content}_.result.tokensUsed!=null&&(T=_.result.tokensUsed)}else _.type==="error"&&(B=_.error)}return B&&!C?p?b():B==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:C||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:D}=await import("./agent-USWAFKWO.js"),W=await D(N),F=W.inputTokens,q=W.outputTokens;if((F===void 0||q===void 0)&&W.tokensUsed){let z=W.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var En=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}},dc=1e3;async function cc(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"}),dc),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 uc(n,e,t,s,r,o,i){let a=Dt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=jt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let C=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>C}catch(C){return C instanceof Ne,null}m&&Ln(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,A,R,O,$,L,N="",D="",W=C=>{if(!i||!C)return;let T;if(D&&C.startsWith(D)?T=C.slice(D.length):T=N&&!N.endsWith(`
34
+ ${e.message}`:e.message,A=e.context?.sender,R=typeof A=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(A),O=e.context?.channel==="web-chat"&&R?{userId:A,agentId:e.agentId||"acme-public"}:void 0,$=cr(n),L=Object.keys($).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:L?$:void 0};if(r){let{generateStream:z}=await import("./agent-UFMIPTQZ.js"),C="",T,S,U,B;for await(let _ of z(N)){if(c)try{c(_)}catch{}if(_.type==="text_delta")C+=_.text,r(_.text,C);else if(_.type==="thinking_delta")_.text&&i&&i(_.text);else if(_.type==="generate_result"){if(_.result.content&&_.result.content!==C){let Q=_.result.content.slice(C.length);Q?(C=_.result.content,r(Q,C)):C=_.result.content}T=_.result.tokensUsed,_.result.inputTokens!=null&&(S=_.result.inputTokens),_.result.outputTokens!=null&&(U=_.result.outputTokens)}else if(_.type==="done"){if(_.result.content&&_.result.content!==C){let Q=_.result.content.slice(C.length);Q?(C=_.result.content,r(Q,C)):C=_.result.content}_.result.tokensUsed!=null&&(T=_.result.tokensUsed)}else _.type==="error"&&(B=_.error)}return B&&!C?p?b():B==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:C||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:D}=await import("./agent-UFMIPTQZ.js"),W=await D(N),F=W.inputTokens,q=W.outputTokens;if((F===void 0||q===void 0)&&W.tokensUsed){let z=W.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var En=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}},dc=1e3;async function cc(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"}),dc),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 uc(n,e,t,s,r,o,i){let a=Dt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=jt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let C=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>C}catch(C){return C instanceof Ne,null}m&&Ln(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,A,R,O,$,L,N="",D="",W=C=>{if(!i||!C)return;let T;if(D&&C.startsWith(D)?T=C.slice(D.length):T=N&&!N.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${C}`:C,D=C,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let z=!1;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:C})){if(z=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let S=T.raw.message?.content??[];for(let B of S)B.type==="text"&&typeof B.text=="string"?(b=B.text,W(B.text)):B.type==="tool_use"&&(D="");let U=T.raw.message?.usage;if(U){let B=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);B>0&&(R=B)}}if(T.type==="result"){let S=T.raw;if(S.is_error){let U=V(typeof S.result=="string"?S.result:"claude error");y=U.error,x=U.errorKind}else typeof S.result=="string"&&S.result.length>0&&(b=S.result,N||W(S.result));typeof S.session_id=="string"&&(L=S.session_id),S.usage&&(A={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(O=S.num_turns),typeof S.message?.model=="string"?$=S.message.model:typeof S.model=="string"?$=S.model:$=Ot(S.modelUsage)||$}}}catch(C){if(F)y="task cancelled by operator",x="cancelled";else if(z)if(C instanceof Ve)y=`Claude Code was stopped mid-turn (${C.reason}), before its time limit`,x="interrupted";else if(C instanceof Ze){let T=V(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);y=T.error,x=T.errorKind}else{let T=V(`persistent claude process error: ${C?.message||String(C)}`);y=T.error,x=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!y&&(y="task cancelled by operator",x="cancelled"),{content:F?"":b,error:y,errorKind:x,duration:Date.now()-c,usage:A,contextTokens:R,numTurns:O,billedModel:$,claudeSessionId:L}}function Wo(n){let e=pe(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?xo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:vo(t.args,n.taskId,n.agentId)}function lc(n){return pe(n.autonomy)||!!n.personLimits}async function gc(n,e,t,s,r,o,i){let a=pe(e.autonomy)?e.autonomy:void 0,c=a&&So(a,n.tier)||e.personLimits&&$o(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${Gs(a)}
@@ -55,7 +55,7 @@ ${h.join(`
55
55
  `),tags:["intent",...n.intent.path]})}else{let i=Cc(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
56
56
  `),tags:["artifacts",...n.mediaType?["media"]:[]]}),n.skillInjection&&s.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:n.skillInjection,tags:["skills","auto-inject"]}),n.patternContext&&s.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:n.patternContext,tags:["patterns","behavioral","self-improving"]}),n.procedureContext&&s.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:n.procedureContext,tags:["procedures","sop"]}),n.workflowRunContext&&s.push({name:"workflow-run",priority:6.55,maxTokens:t("workflow-run",200),content:n.workflowRunContext,tags:["workflow","plan"]}),n.memoryContext&&s.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:n.memoryContext,tags:["memory","persistent"]});let o=n.groupHistory||n.sessionHistory;if(o&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"],keep:"tail"}),n.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:n.crossChatContext,tags:["history","cross-chat"]}),n.contextOnDemand&&s.push({name:"on-demand",priority:7,maxTokens:t("on-demand",150),content:n.contextOnDemand,tags:["history","on-demand","lean"]}),n.longMemoryRecall&&s.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:n.longMemoryRecall,tags:["history","long-memory"]}),n.handoverNote){let i=[`[Handover] You are taking over this conversation from ${n.handoverNote.fromAgent}.`];n.handoverNote.summary&&i.push(`Operator summary: ${n.handoverNote.summary}`),i.push(`Handover time: ${n.handoverNote.at}`),s.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
57
57
  `),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner:]`,n.rotationMemo.memo].join(`
58
- `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function $c(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
58
+ `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.watcherNote&&s.push({name:"watcher",priority:2.6,maxTokens:t("watcher",400),content:n.watcherNote,tags:["watcher","done"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function $c(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(`
59
59
  `),tags:r,rules:s}}function Ac(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
60
60
  `),tags:s}}function Cc(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 Mc="resumeDelivery";function qp(n){if(!n||n.kind!=="direct"||!n.context||n.context[Mc]||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 Rc=32e3;function ti(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Rc?e:null}catch{return null}}function Gp(n){if(!n)return null;try{let e=JSON.parse(n);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}function ni(n){return new Date(n).toISOString().slice(11,16)}function si(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${ni(n)} UTC, running at ${ni(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 Kt=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
61
61
  `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};var _c=String.raw`(?=[\w.-]*[A-Za-z])[\w.-]+`,Pc=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.-]+`,ri=/\bhttps?:\/\/[^\s/<>()"']+\/([^\s<>()"'#?]+?)\/(?:-\/)?(issues|pull|merge_requests)\/(\d+)/gi,oi=new RegExp(String.raw`(?<![\w/.-])((?:${_c}\/)+${Pc})([#!])(\d+)\b`,"g");function Jt(n){if(typeof n!="string")return;let e=n.trim();if(!e||e.length>300||/\s/.test(e))return;let t=new RegExp(ri.source,"i").exec(e);if(t)return`${t[1].toLowerCase()}${t[2].toLowerCase()==="merge_requests"?"!":"#"}${t[3]}`;let s=new RegExp(`^${oi.source}$`).exec(e);return s?`${s[1].toLowerCase()}${s[2]}${s[3]}`:e.replace(/\/+$/,"").toLowerCase()}function Ec(n){if(!n)return[];let e=new Set;for(let t of n.matchAll(ri)){let s=Jt(t[0]);s&&e.add(s)}for(let t of n.matchAll(oi))e.add(`${t[1].toLowerCase()}${t[2]}${t[3]}`);return[...e]}function zp(n){let e=n.context&&typeof n.context=="object"?n.context:null;return Jt(n.home)??Jt(e?.home)}var Oc="[agentx:same-home]";function ii(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`${Oc} 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 ai(n){let e=Jt(n.home),t=Ec(n.message);return e?[e,...t.filter(s=>s!==e)]:t}import{readFileSync as Dc,writeFileSync as di,appendFileSync as Nc,mkdirSync as Lc,existsSync as ci}from"fs";import{resolve as Hn}from"path";var ui=50,Uc="claude-haiku-4-5-20251001",Fc=`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.
@@ -159,7 +159,7 @@ ${Ra(d.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.c
159
159
  ${e.message}`),e.queuedAt=void 0}let h=ai({message:e.message,home:e.context?.home}),b=ii(d.runningTasks,h,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});b&&(this.log(`[${e.agentId}] ${b.slice(0,160)}`),e.message=`${b}
160
160
  ${e.message}`),d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let y={...h.length?{homes:h}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(y),e.runningTaskId=y.id;let x=bn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(y.id,e.context??{}),e.onStart)try{e.onStart(y.id)}catch{}let A=new AbortController;this.taskAborts.set(y.id,{agentId:e.agentId,channel:y.channel,chatId:typeof y.chatId=="string"?y.chatId:"",originalMessage:e.message||"",controller:A,sender:e.context?.sender,rootId:At()?.rootId,workflowRunId:e.workflowRunId??(typeof y.chatId=="string"&&y.chatId.startsWith("workflow:")&&y.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let R={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(y.id,R);let O=g=>{if(g){R.buffer+=g,R.buffer.length>Fa&&(R.buffer=R.buffer.slice(R.buffer.length-Fa));for(let f of R.subscribers)try{f(g)}catch{}}},$=Ee();e.taskId=$,y.traceId=$;let L=this.taskAborts.get(y.id);L&&(L.traceId=$);let N=new Map,D=(g,f,k)=>{try{ee().emit("task:step",{taskId:$,agentId:e.agentId,name:"pipeline",action:g,status:k,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},W=0,F=!1,q=()=>{F||(F=!0,W&&D("first-event",W,"ok"))},z;if(t){let g=_g();z=f=>{q();let k=g(f);if(k&&O(k),ja($,e.agentId,f),Ba(N,f),Gn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else z=g=>{if(q(),ja($,e.agentId,g),Ba(N,g),Gn(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let C=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,T=C?setTimeout(()=>A.abort(new Error(`timed out after ${Math.round(C/1e3)}s`)),C):void 0;T?.unref?.();let S=(d.def.preSpawnTimeoutSec??Tg)*1e3,U=setTimeout(()=>{A.abort(new Error(`timed out before spawn after ${Math.round(S/1e3)}s in step "${y.step??"start"}"`))},S);U.unref?.();let B=()=>{U&&clearTimeout(U),U=void 0},_=()=>`task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`,Q;A.signal.addEventListener("abort",()=>{let g=Pe(A.signal).message;/^timed out/.test(g)&&(Q=y.step??"start"),this.log(`[${e.agentId}] task ${y.id} aborted in step "${y.step??"start"}" \u2014 ${g} ${_()}`)},{once:!0});let te=g=>{y.step=g,this.log(`[${e.agentId}] step ${g} ${_()}`)},Y=(g,f,k=0)=>{if(A.signal.aborted)return Promise.reject(Pe(A.signal));te(g),(g==="agent"||g==="workflow-auto-run")&&(B(),W=Date.now());let v=Date.now(),j=ha(f(),wg[g]??0,g);return ma(j,A.signal,k).then(G=>(D(g,v,"ok"),G),G=>{throw D(g,v,"error"),G instanceof je&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${_()}`),G})},P=async(g,f,k,v=0)=>{try{return await Y(g,f,v)}catch(j){if(j instanceof je)return k();throw j}},re=!1,ie=!1,as=g=>{if(!(!re||ie)){ie=!0;try{ee().emit("task:completed",{taskId:$,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-y.startedAt.getTime(),error:g?.error||(A.signal.aborted?Pe(A.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(y.id)?!0:void 0,stopped:!this.interruptedRuns.has(y.id)&&(this.stoppedRuns.has(y.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ds=!1,cs=g=>{if(ds)return;ds=!0,as(g),this.runReleases.delete(y.id),T&&clearTimeout(T),B(),d.activeTasks--;let f=d.runningTasks.findIndex(v=>v.id===y.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(y.id),this.taskAborts.delete(y.id);let k=this.runEndWaiters.get(y.id);this.runEndWaiters.delete(y.id);for(let v of k??[])try{v()}catch{}R.done=!0,R.endedAt=new Date;for(let v of R.subscribers)try{v(`
161
161
  [task finished]
162
- `)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),Sg).unref?.();try{let v=R.endedAt,j={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let X=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:v,ok:j.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let j=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:j,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:j,at:new Date().toISOString()});for(let X of v){let $e=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:$e,queuedAt:X.queuedAt??X.timestamp}).then(he=>(Xe(he.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,he)),he=>{throw G(),he}).catch(he=>{this.log(`[${e.agentId}] queued message failed: ${he.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,cs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${_()}`);let w=e.context?.channel||"api",{evaluateRequest:Ga,selectRequestContext:Ka}=await import("./request-planner-T5GKPGQT.js"),us=P("request-gate",()=>Ga(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),on=!1;us.then(()=>{on=!0},()=>{on=!0});let I=l,an=e.context?.sender||"User",ce=d.def.tier==="codex-cli",qe=Hi(this.config.session,w,d.def.tier),ut=Bi(this.config.session),le=e.isolated===!0,Ge=!le&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await P("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ja=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;pa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ja,taskId:$}),this.sessions.addUserMessage(e.agentId,w,I,an,e.message);let ls=Date.now(),gs={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(ls).toISOString(),taskId:$,resumeOrigin:ti(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:wn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Ks(e.context),operator:Js(e.context),dueAt:fa(e.context),taskType:en(e.context)};ee().emit("task:started",gs),re=!0;let ne,dn,ps=this.classifier;if(ps&&w!=="a2a"&&!ce){te("classify");let g=Date.now();dn=ps.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(y.intentPath=ne.path.slice()),D("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",g,"error")})}let fs=async g=>{if(!dn)return;let f;await Promise.race([dn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await fs(gg);let Te=this.config.workflows?.matching,me,ms,hs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&hs?.enabled&&(hs.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(ms=Dr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?me={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Nr(this.config.workflows,e.agentId)&&Lr(e)?this.workflowRuns:void 0;if(ke&&!me&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(me={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?yg():void 0,za=ae?Ur(ae):void 0,Qa=this.wikiHub.getAgentWiki(e.agentId),ys=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),ws=this.memoryStore.buildContext(ys),bs=this.memoryStore.contextFacts(ys),Xa=this.patternStore.findRelevant(e.message,e.agentId,5),Ya=this.patternStore.buildContext(Xa),xs="";if(!ce)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await Y("skills",()=>g(d.def.workspace)),v=e.personLimits?.skills??[],j=v.length?k.filter(G=>!v.some(X=>ze(X,G.frontmatter.name))):k;xs=f(j,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=io({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${An(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${An(f)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await P("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await Y("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Za=process.env.AGENTX_CONTEXT_SURGERY==="1",Va=ce?{maxMessages:8,maxChars:2400}:Za&&Ua(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,ed=!H&&!ce?Cg(Qa,e.agentId,{notesInbox:Ag(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Va):void 0,td=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Ss,Is=[];if(this.config.procedures?.injection?.enabled&&!H&&!ce)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=Qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ss=Xn(f),Is=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,k=f[0],v=f[f.length-1],j=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
162
+ `)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),Sg).unref?.();try{let v=R.endedAt,j={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let X=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:v,ok:j.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let j=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:j,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:j,at:new Date().toISOString()});for(let X of v){let $e=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:$e,queuedAt:X.queuedAt??X.timestamp}).then(he=>(Xe(he.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,he)),he=>{throw G(),he}).catch(he=>{this.log(`[${e.agentId}] queued message failed: ${he.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,cs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${_()}`);let w=e.context?.channel||"api",{evaluateRequest:Ga,selectRequestContext:Ka}=await import("./request-planner-FE3C2QFQ.js"),us=P("request-gate",()=>Ga(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),on=!1;us.then(()=>{on=!0},()=>{on=!0});let I=l,an=e.context?.sender||"User",ce=d.def.tier==="codex-cli",qe=Hi(this.config.session,w,d.def.tier),ut=Bi(this.config.session),le=e.isolated===!0,Ge=!le&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await P("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ja=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;pa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ja,taskId:$}),this.sessions.addUserMessage(e.agentId,w,I,an,e.message);let ls=Date.now(),gs={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(ls).toISOString(),taskId:$,resumeOrigin:ti(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:wn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Ks(e.context),operator:Js(e.context),dueAt:fa(e.context),taskType:en(e.context)};ee().emit("task:started",gs),re=!0;let ne,dn,ps=this.classifier;if(ps&&w!=="a2a"&&!ce){te("classify");let g=Date.now();dn=ps.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(y.intentPath=ne.path.slice()),D("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",g,"error")})}let fs=async g=>{if(!dn)return;let f;await Promise.race([dn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await fs(gg);let Te=this.config.workflows?.matching,me,ms,hs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&hs?.enabled&&(hs.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(ms=Dr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?me={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Nr(this.config.workflows,e.agentId)&&Lr(e)?this.workflowRuns:void 0;if(ke&&!me&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new Mt({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Rt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(me={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?yg():void 0,za=ae?Ur(ae):void 0,Qa=this.wikiHub.getAgentWiki(e.agentId),ys=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),ws=this.memoryStore.buildContext(ys),bs=this.memoryStore.contextFacts(ys),Xa=this.patternStore.findRelevant(e.message,e.agentId,5),Ya=this.patternStore.buildContext(Xa),xs="";if(!ce)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await Y("skills",()=>g(d.def.workspace)),v=e.personLimits?.skills??[],j=v.length?k.filter(G=>!v.some(X=>ze(X,G.frontmatter.name))):k;xs=f(j,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=io({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${An(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${An(f)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await P("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await Y("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Za=process.env.AGENTX_CONTEXT_SURGERY==="1",Va=ce?{maxMessages:8,maxChars:2400}:Za&&Ua(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,ed=!H&&!ce?Cg(Qa,e.agentId,{notesInbox:Ag(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Va):void 0,td=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Ss,Is=[];if(this.config.procedures?.injection?.enabled&&!H&&!ce)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=Qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ss=Xn(f),Is=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,k=f[0],v=f[f.length-1],j=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
163
163
  `).length}L`,G=`[${e.agentId}] ${w}:${I} ${j} | session.messages=${f.length}`+(f.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Ts;if(d.def.contextReferences&&!H)try{let g=d.def.workspace,f=this.referencesCache.get(g);if(!f){let[v,j]=await Y("references",()=>Promise.all([In(d.def.workspace),Tn(d.def.workspace)]));if(v.byId.size===0&&j.recipes.length===0){let[G,X]=await Y("references",()=>Promise.all([In(process.cwd()),Tn(process.cwd())]));f={refs:G,recipes:X}}else f={refs:v,recipes:j};this.referencesCache.set(g,f)}let k=vr({agentId:e.agentId,intentTags:ne?.path,message:e.message},f.recipes,f.refs);k.cards.length>0&&(Ts=Tr(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let ks=le||Ge?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),vs,pt=le?null:Jo(e.message);if(pt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:pt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${pt.lookbackDays}d on this chat (cue-triggered)]`],k=[...g.turns].sort((v,j)=>v.ts.localeCompare(j.ts));for(let v of k){let j=v.ts.slice(11,16)+" "+v.day,G=v.role==="user"?v.senderName||"User":v.senderName||"Agent";f.push(`${j} ${G}: ${v.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),vs=f.join(`
164
164
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${pt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let nd=ce?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",$s,As,Cs=!1;on||te("request-gate");let ve=await us;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),nd==="planner"&&!le&&!ve.active&&!Ge&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-2XBAPQ3S.js"),f=await Y("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Cs=!0,$s=f.sessionHistory,ws=f.memoryContext,bs=f.memoryFacts,ks=f.crossChatContext,As=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Cs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let cn=`${e.agentId}:${w}:${I}`,ft=dr(e.message);ft&&(ft==="default"?(this.activeSouls.delete(cn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(cn,ft),this.log(`[${e.agentId}] Soul switched to: ${ft}`)));let sd=this.activeSouls.get(cn),rd=ir(d.def.workspace,sd),od=ar(rd),id=le?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),ad=xg(d.def.tier),dd=Pg(d.def.richMessages,w),cd=d.def.tier==="claude-code"&&(le||qe!=="lean"||ji(ut)),Ms="";if(d.def.workspace&&!cd){let g=K(d.def.workspace,"CLAUDE.md");if(de(g))try{let f=dt(g,"utf-8");Ms=`[Project CLAUDE.md]
165
165
  ${f.length>4e3?f.slice(0,4e3)+`
@@ -173,9 +173,9 @@ ${$e}`),f+=$e.length}catch{}}}let ud=un.length>0?un.join(`
173
173
 
174
174
  `)||void 0,ht={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:an,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ce||Ge||Ua(w,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ce?void 0:Ya||void 0,procedureContext:[Ss,ms].filter(Boolean).join(`
175
175
 
176
- `)||void 0,workflowRunContext:za,references:Ts,skillInjection:xs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:$s??gt,memoryContext:ws||void 0,crossChatContext:ks||void 0,longMemoryRecall:vs||void 0,contextOnDemand:Ge&&!H?zi(w,I):void 0,wikiContext:ed,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(gs)}catch{return}})(),rotationMemo:td,eventDigest:H?void 0:$g(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Jr(w,!H,d.def.richMessages);return g?Mg(d.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:nr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let Rs=tr(d.def.tier,this.config.decisions.routing),_s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&Rs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-C66W2E3P.js"),f=await Y("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:Rs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Ps=!1;_s.then(()=>{Ps=!0});let wt=ve.active&&ve.preprocess?await P("select-context",()=>Ka(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=ei(wt.input,ce?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),ld=br(bt,{memory:bs,procedures:Is,wikiContext:wt.input.wikiContext}),gn=(bt?.length??0)+(ln?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:ln?.length??0,message:e.message?.length??0},Es=Pi(e.agentId,w,I);Ei(Es,gn,xt);let Os=Oi(Es);Os&&this.log(`[${e.agentId}] ${Os}`),gn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${gn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),Ps||te("route-model");let Ds=await _s,Ns=d.def.tier!=="claude-code"?void 0:le?Gi():qe==="lean"?qi(d.def.workspace,ut,void 0,w):Ji(d.def.workspace);qe==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Qi(qe,ut,w)}`);let Ls=d.def.tier==="claude-code"&&!H?ro({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:$},g=>this.log(g)):void 0,gd={...e,systemPromptAppend:ln,...Ns?{claudeArgs:Ns}:{},...Ds?{model:Ds}:{}},se,Us=ua({agent:e.agentId,request:e.message,taskId:$,budgetMinutes:d.def.maxExecutionMinutes??20}),pd=z,Fs=!1,pn=!0;z=g=>{if(Us.observe(g),ae&&pn)for(let f of Hr(g))Fr(f.name,f.input)||(pn=!1);pd?.(g)};try{let g=this.workflowAutoRunner;if(me&&g){let E=me;try{let J=await Y("workflow-auto-run",()=>g({workflowId:E.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${me.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:me.workflowId,workflowRunId:J.runId,workflowMatchConfidence:me.confidence}},se}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let E=jr(ke,e.resumedFrom);Br(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:$,...E?{continues:E}:{}}),Fs=!0,y.workflow={runId:ae,workflowId:Or}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;te("dispatch-gate");let E=d.def.persistentProcess?Dt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,ge=[yi(ye),Ri(ye,void 0,e.model||d.def.model)].find(kt=>kt&&kt.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let kt={content:"",error:ge.message,duration:0};if(!t){R.buffer=`[error] ${ge.message}`;for(let md of R.subscribers)try{md(R.buffer)}catch{}}return kt}Ii();let Ke=_i();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},k=Ct(e.agentId);if(k){if(te("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){R.buffer=`[error] ${k.message}`;for(let E of R.subscribers)try{E(R.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,se=E,E}let j=d.def.tier==="claude-code",G=j?t:(E,J)=>{E&&O(E),t&&t(E,J)},X=!1,$e=j?s:E=>{E&&(X?O(E):(O(`\u{1F4AD} ${E}`),X=!0)),s&&s(E)},he=()=>{X&&(O(`
176
+ `)||void 0,workflowRunContext:za,references:Ts,skillInjection:xs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:$s??gt,memoryContext:ws||void 0,crossChatContext:ks||void 0,longMemoryRecall:vs||void 0,contextOnDemand:Ge&&!H?zi(w,I):void 0,wikiContext:ed,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(gs)}catch{return}})(),rotationMemo:td,eventDigest:H?void 0:$g(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Jr(w,!H,d.def.richMessages);return g?Mg(d.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:nr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let Rs=tr(d.def.tier,this.config.decisions.routing),_s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&Rs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-6J4OHUJS.js"),f=await Y("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:Rs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Ps=!1;_s.then(()=>{Ps=!0});let wt=ve.active&&ve.preprocess?await P("select-context",()=>Ka(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=ei(wt.input,ce?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),ld=br(bt,{memory:bs,procedures:Is,wikiContext:wt.input.wikiContext}),gn=(bt?.length??0)+(ln?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:ln?.length??0,message:e.message?.length??0},Es=Pi(e.agentId,w,I);Ei(Es,gn,xt);let Os=Oi(Es);Os&&this.log(`[${e.agentId}] ${Os}`),gn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${gn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),Ps||te("route-model");let Ds=await _s,Ns=d.def.tier!=="claude-code"?void 0:le?Gi():qe==="lean"?qi(d.def.workspace,ut,void 0,w):Ji(d.def.workspace);qe==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Qi(qe,ut,w)}`);let Ls=d.def.tier==="claude-code"&&!H?ro({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:$},g=>this.log(g)):void 0,gd={...e,systemPromptAppend:ln,...Ns?{claudeArgs:Ns}:{},...Ds?{model:Ds}:{}},se,Us=ua({agent:e.agentId,request:e.message,taskId:$,budgetMinutes:d.def.maxExecutionMinutes??20}),pd=z,Fs=!1,pn=!0;z=g=>{if(Us.observe(g),ae&&pn)for(let f of Hr(g))Fr(f.name,f.input)||(pn=!1);pd?.(g)};try{let g=this.workflowAutoRunner;if(me&&g){let E=me;try{let J=await Y("workflow-auto-run",()=>g({workflowId:E.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${me.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:me.workflowId,workflowRunId:J.runId,workflowMatchConfidence:me.confidence}},se}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let E=jr(ke,e.resumedFrom);Br(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:$,...E?{continues:E}:{}}),Fs=!0,y.workflow={runId:ae,workflowId:Or}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;te("dispatch-gate");let E=d.def.persistentProcess?Dt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,ge=[yi(ye),Ri(ye,void 0,e.model||d.def.model)].find(kt=>kt&&kt.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let kt={content:"",error:ge.message,duration:0};if(!t){R.buffer=`[error] ${ge.message}`;for(let md of R.subscribers)try{md(R.buffer)}catch{}}return kt}Ii();let Ke=_i();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},k=Ct(e.agentId);if(k){if(te("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){R.buffer=`[error] ${k.message}`;for(let E of R.subscribers)try{E(R.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,se=E,E}let j=d.def.tier==="claude-code",G=j?t:(E,J)=>{E&&O(E),t&&t(E,J)},X=!1,$e=j?s:E=>{E&&(X?O(E):(O(`\u{1F4AD} ${E}`),X=!0)),s&&s(E)},he=()=>{X&&(O(`
177
177
  `),X=!1)},fd=j?G:G?(E,J)=>{he(),G(E,J)}:void 0,M=await Y("agent",async()=>{if(v.route!=="local"){let E=await this.runCloudSession(d.def,e,v,$);if(E)return E;let J=f();if(J)return J}return qo(d.def,gd,this.providers,fd,bt,H,z,A.signal,$e)},Ig);if(!M.error){let E=Rg(d.def.toolUseRequired,N);if(E){let J=Array.from(N.entries()).map(([ye,Tt])=>`${ye}=${Tt}`).join(", ")||"none";M.error=`tool_required_not_called: ${E} (invoked: ${J})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${E}, observed ${J}`)}}Ls&&oo(Ls,{toolUses:N,eventsSeen:F,error:M.error,agentId:e.agentId},E=>this.log(E));let St=this.interruptedRuns.get(y.id);St&&(M.content="",M.error=St,M.errorKind="interrupted");let fn=St?void 0:this.stoppedRuns.get(y.id);fn&&(M.content="",M.error=fn,M.errorKind="stopped"),se=M;let ue=M.usage?yr(M.usage):void 0,Hs=M.billedModel||e.model||d.def.model||void 0,It=M.costUsd??(ue&&hr(Hs,d.def.tier)?this.tokenTracker.cost({tasks:1,totalDuration:0,errors:0,...ue},Hs):void 0);if(ie=!0,ee().emit("task:completed",{taskId:$,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-ls,error:M.error||void 0,errorKind:M.error?M.errorKind:void 0,interrupted:St?!0:void 0,stopped:fn?!0:void 0,inputTokens:ue?.inputTokens,outputTokens:ue?.outputTokens,cacheReadTokens:ue?.cacheReadTokens,cacheCreateTokens:ue?.cacheCreateTokens,tier2InputTokens:ue?.tier2InputTokens,tier2OutputTokens:ue?.tier2OutputTokens,tier2CacheReadTokens:ue?.tier2CacheReadTokens,tier2CacheCreateTokens:ue?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:M.numTurns,costUsd:It!==void 0&&Number.isFinite(It)&&It>0?It:void 0,injectedContext:ld,finalResponse:M.content||void 0,billedModel:M.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let E=M.error?`[error] ${M.error}`:M.content;R.buffer=E;for(let J of R.subscribers)try{J(E)}catch{}}if(M.error)d.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,M.content),ga({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:M.content,taskId:$}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,M.usage,M.contextTokens),M.usage){let ge=M.contextTokens,Ke=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(ge??Ke)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ge??"n/a"} tokens (cumulative turn total=${Ke}) \u2014 next turn will rotate`)}if(lr({channel:w,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await fs(pg);try{let ge=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ge,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
178
178
 
179
179
  Agent: ${M.content}`,meta:vg(ne,e.context)})}catch{}gr(e.agentId,e.message,M.content,{channel:w,chatId:I,sender:an},this.memoryStore).catch(()=>{}),li(e.agentId,e.message,M.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=M.billedModel||e.model||d.def.model,ye=e.context?.channel,Tt=ye&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ye}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,M.duration||0,M.usage,e.message.length,M.content.length,!1,J,ye,Tt),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${_()}`)}return M}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Pt(g.message);return se={content:"",error:Et(f),errorKind:f.kind},se}finally{if(Us.stop(),Fs&&ae&&ke)try{let g=se?.usage,f=Wr(ke,ae,{error:se?se.error||void 0:A.signal.aborted?Pe(A.signal).message:"run ended before completion",canceled:qr(se?.errorKind)||this.stoppedRuns.has(y.id)||this.interruptedRuns.has(y.id)||!se&&A.signal.aborted,durationMs:Date.now()-y.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:pn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}as(se),cs(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.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Gr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),We,this.safe(e.agentId),t);de(s)||fg(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);hg(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),We,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=K(a,l);if(de(p))try{for(let m of fe(p)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],b=parseInt(h,10);if(!Number.isFinite(b)||b<i||b>s)continue;let y=Math.floor((s-b)/36e5),x=t-1-y;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),We);if(!de(e))return 0;let t=0;for(let s of fe(e)){let r=K(e,s),o;try{o=fe(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=fe(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(dt(K(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=kg){let t=K(process.cwd(),We);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of fe(t)){let i=K(t,o),a;try{a=fe(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{mg(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),We,this.safe(e));if(!de(s))return[];let r=fe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),c;try{c=fe(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(dt(K(a,d),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),We,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=fe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(de(a))try{return JSON.parse(dt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){if(Ct(t))continue;let s=this.budgetHolds.take(t);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=vn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Xe(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=jt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let m=this.messageQueue.pendingCount(i,a,c);ee().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:zs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,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,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{Xe(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Pg(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
180
180
  `)}export{go as a,Jg as b,fo as c,Ed as d,mo as e,Nt as f,ip as g,up as h,lp as i,hp as j,jt as k,ec as l,Bo as m,oc as n,ic as o,ac as p,qo as q,qt as r,Gt as s,Mc as t,qp as u,Gp as v,Jt as w,zp as x,jn as y,ee as z,gi as A,Wc as B,Jc as C,mi as D,lf as E,hi as F,xi as G,$i as H,vf as I,Ai as J,Xt as K,_f as L,Pf as M,it as N,Zu as O,Vu as P,el as Q,tl as R,nl as S,Qn as T,en as U,dm as V,Sa as W,at as X,Ia as Y,mm as Z,hm as _,ym as $,wm as aa,bm as ba,xm as ca,Sm as da,El as ea,bg as fa,xg as ga,jh as ha,Wh as ia,vg as ja,$g as ka,Cg as la,is as ma,Ha as na,Ba as oa,Rg as pa,ja as qa,Wa as ra,Pg as sa};
181
- //# sourceMappingURL=chunk-6JFGNRC3.js.map
181
+ //# sourceMappingURL=chunk-ILHTAVZZ.js.map