agentix-cli 0.198.0 → 0.199.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +7 -2
  2. package/apps/mac-voice/Sources/AgentXVoice/AnswerView.swift +19 -8
  3. package/apps/mac-voice/Sources/AgentXVoice/Artifacts.swift +54 -0
  4. package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +3 -0
  5. package/apps/mac-voice/Sources/AgentXVoice/PanelAnswer.swift +3 -2
  6. package/apps/mac-voice/Sources/AgentXVoice/main.swift +7 -7
  7. package/dist/{App-ODMLQITV.js → App-HGCD735J.js} +2 -2
  8. package/dist/{ChatApp-MJBOQWUM.js → ChatApp-VVBGBDKU.js} +2 -2
  9. package/dist/{absorb-eval-QSUGLOOO.js → absorb-eval-2XT7XBH7.js} +2 -2
  10. package/dist/{adapter-BJLSEQ6M.js → adapter-ZGEMORWD.js} +2 -2
  11. package/dist/{agent-QJPWZDTL.js → agent-4IF72I6E.js} +2 -2
  12. package/dist/{board-dashboard-LZRJJ3DZ.js → board-dashboard-2P77CUM3.js} +345 -324
  13. package/dist/board-dashboard-2P77CUM3.js.map +1 -0
  14. package/dist/{chunk-GB7NAOZ4.js → chunk-3DAHVUJH.js} +2 -2
  15. package/dist/{chunk-GGFL7HVN.js → chunk-3DX7CKKW.js} +2 -2
  16. package/dist/{chunk-GL26HRDW.js → chunk-3SWDVBGA.js} +2 -2
  17. package/dist/{chunk-C5QQW2L7.js → chunk-5NE26NUO.js} +2 -2
  18. package/dist/{chunk-PM4Y6ZBW.js → chunk-5QK3U7R6.js} +2 -2
  19. package/dist/{chunk-HYJWN6L5.js → chunk-5VRN6JP7.js} +2 -2
  20. package/dist/{chunk-MA5ZF4YY.js → chunk-6QU5YWOE.js} +2 -2
  21. package/dist/{chunk-D64VFKUU.js → chunk-7SKUXUIX.js} +5 -5
  22. package/dist/{chunk-IJYCPFLZ.js → chunk-BBXB7X25.js} +2 -2
  23. package/dist/chunk-DECMCWGN.js +3 -0
  24. package/dist/{chunk-BIJ3JIWG.js.map → chunk-DECMCWGN.js.map} +1 -1
  25. package/dist/{chunk-KQ5UJTQR.js → chunk-DUVPXHDO.js} +2 -2
  26. package/dist/{chunk-SUVJA67A.js → chunk-F6UAAQSU.js} +2 -2
  27. package/dist/{chunk-CAYGWXWJ.js → chunk-I4U2ELEX.js} +2 -2
  28. package/dist/{chunk-4FY2NOCD.js → chunk-JAS75QDT.js} +2 -2
  29. package/dist/{chunk-2AP2F6S5.js → chunk-K2JE5XR4.js} +3 -3
  30. package/dist/{chunk-VX3IZAF6.js → chunk-K3QWXVLV.js} +2 -2
  31. package/dist/{chunk-PIY23C2Z.js → chunk-KWU4EOWC.js} +2 -2
  32. package/dist/{chunk-QHICHZFK.js → chunk-L3FCDIJT.js} +2 -2
  33. package/dist/{chunk-C3LKB4N7.js → chunk-OCZVJANH.js} +2 -2
  34. package/dist/{chunk-3KHXOLF5.js → chunk-OWL6JA6W.js} +2 -2
  35. package/dist/{chunk-XRCWM7JA.js → chunk-RE6N3TRQ.js} +2 -2
  36. package/dist/{chunk-QF5B5O7K.js → chunk-SPZXOCN5.js} +304 -304
  37. package/dist/chunk-SPZXOCN5.js.map +1 -0
  38. package/dist/{chunk-SHNGAN3L.js → chunk-T7HWU7O4.js} +2 -2
  39. package/dist/chunk-UPRACUXY.js +118 -0
  40. package/dist/chunk-UPRACUXY.js.map +1 -0
  41. package/dist/{chunk-I5KOLVB6.js → chunk-UU7A5DNY.js} +2 -2
  42. package/dist/{chunk-H3NGVXOL.js → chunk-UY25GSQ3.js} +2 -2
  43. package/dist/{chunk-BZ3AXEZW.js → chunk-XTBFWRM3.js} +2 -2
  44. package/dist/{chunk-LOFMZHJN.js → chunk-XZFBOXFK.js} +2 -2
  45. package/dist/{chunk-V2DCI2JL.js → chunk-YU2JJIQH.js} +3 -3
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-WAPDTJ5B.js → client-PNZ3LL72.js} +2 -2
  48. package/dist/config-HOKADOXX.js +2 -0
  49. package/dist/{config-mutate-ZADHR76X.js → config-mutate-ZR7EM4IB.js} +2 -2
  50. package/dist/{config-mutator-GJFZWC43.js → config-mutator-NWTMXBEY.js} +2 -2
  51. package/dist/{contributions-RROXRQEV.js → contributions-NBKZD7QW.js} +2 -2
  52. package/dist/{doctor-DKUDMNK3.js → doctor-K6SPV3GU.js} +2 -2
  53. package/dist/{follow-up-tool-OKKSNVCJ.js → follow-up-tool-NPC3JLOA.js} +2 -2
  54. package/dist/{hub-5X33WEIO.js → hub-NKGZO574.js} +2 -2
  55. package/dist/index.d.ts +81 -0
  56. package/dist/index.js +1 -1
  57. package/dist/{program-4QVJE2JD.js → program-DYFXKKJE.js} +243 -242
  58. package/dist/program-DYFXKKJE.js.map +1 -0
  59. package/dist/{promote-YETAZYXW.js → promote-HIFKFRC4.js} +2 -2
  60. package/dist/{query-IE5EVVY4.js → query-VXE4AREX.js} +2 -2
  61. package/dist/{query-settings-TF4H7EZS.js → query-settings-NC7FOIRC.js} +2 -2
  62. package/dist/{registry-OBQMRAYY.js → registry-NGRLHM7L.js} +2 -2
  63. package/dist/{request-planner-V6J5EISV.js → request-planner-I65SRAJI.js} +2 -2
  64. package/dist/{review-candidates-MTZEBOP5.js → review-candidates-7KV34XZR.js} +2 -2
  65. package/dist/{routing-KWZ3X6ZV.js → routing-MLOSXPVH.js} +2 -2
  66. package/dist/schedule-tool-7DCB7KJP.js +2 -0
  67. package/dist/{scheduler-ST37UR5V.js → scheduler-WEOQLNIF.js} +2 -2
  68. package/dist/{seat-RFFUE7RT.js → seat-66LQTUIR.js} +2 -2
  69. package/dist/{select-DCG457CP.js → select-JV425OUL.js} +2 -2
  70. package/dist/{set-enabled-TD3MPUDH.js → set-enabled-DWL2MKVS.js} +2 -2
  71. package/dist/{sprint-tool-OQ55FHX3.js → sprint-tool-CDO3HLLT.js} +2 -2
  72. package/dist/{tool-JIRXLLQN.js → tool-7EFJJM2A.js} +2 -2
  73. package/dist/{tool-FQE7ZGBT.js → tool-U3WQCSUN.js} +2 -2
  74. package/dist/{tool-RJJKMW5D.js → tool-W763BDXL.js} +2 -2
  75. package/dist/{wiki-OAWT7LND.js → wiki-MIEXBQ5H.js} +2 -2
  76. package/dist/wiki-enrich-K4HHTRZN.js +2 -0
  77. package/package.json +1 -1
  78. package/dist/board-dashboard-LZRJJ3DZ.js.map +0 -1
  79. package/dist/chunk-BIJ3JIWG.js +0 -3
  80. package/dist/chunk-H7SPRPDG.js +0 -116
  81. package/dist/chunk-H7SPRPDG.js.map +0 -1
  82. package/dist/chunk-QF5B5O7K.js.map +0 -1
  83. package/dist/config-NYFW5P4W.js +0 -2
  84. package/dist/program-4QVJE2JD.js.map +0 -1
  85. package/dist/schedule-tool-ZSQTA3IW.js +0 -2
  86. package/dist/wiki-enrich-QVZMYHVY.js +0 -2
  87. /package/dist/{App-ODMLQITV.js.map → App-HGCD735J.js.map} +0 -0
  88. /package/dist/{ChatApp-MJBOQWUM.js.map → ChatApp-VVBGBDKU.js.map} +0 -0
  89. /package/dist/{absorb-eval-QSUGLOOO.js.map → absorb-eval-2XT7XBH7.js.map} +0 -0
  90. /package/dist/{adapter-BJLSEQ6M.js.map → adapter-ZGEMORWD.js.map} +0 -0
  91. /package/dist/{agent-QJPWZDTL.js.map → agent-4IF72I6E.js.map} +0 -0
  92. /package/dist/{chunk-GB7NAOZ4.js.map → chunk-3DAHVUJH.js.map} +0 -0
  93. /package/dist/{chunk-GGFL7HVN.js.map → chunk-3DX7CKKW.js.map} +0 -0
  94. /package/dist/{chunk-GL26HRDW.js.map → chunk-3SWDVBGA.js.map} +0 -0
  95. /package/dist/{chunk-C5QQW2L7.js.map → chunk-5NE26NUO.js.map} +0 -0
  96. /package/dist/{chunk-PM4Y6ZBW.js.map → chunk-5QK3U7R6.js.map} +0 -0
  97. /package/dist/{chunk-HYJWN6L5.js.map → chunk-5VRN6JP7.js.map} +0 -0
  98. /package/dist/{chunk-MA5ZF4YY.js.map → chunk-6QU5YWOE.js.map} +0 -0
  99. /package/dist/{chunk-D64VFKUU.js.map → chunk-7SKUXUIX.js.map} +0 -0
  100. /package/dist/{chunk-IJYCPFLZ.js.map → chunk-BBXB7X25.js.map} +0 -0
  101. /package/dist/{chunk-KQ5UJTQR.js.map → chunk-DUVPXHDO.js.map} +0 -0
  102. /package/dist/{chunk-SUVJA67A.js.map → chunk-F6UAAQSU.js.map} +0 -0
  103. /package/dist/{chunk-CAYGWXWJ.js.map → chunk-I4U2ELEX.js.map} +0 -0
  104. /package/dist/{chunk-4FY2NOCD.js.map → chunk-JAS75QDT.js.map} +0 -0
  105. /package/dist/{chunk-2AP2F6S5.js.map → chunk-K2JE5XR4.js.map} +0 -0
  106. /package/dist/{chunk-VX3IZAF6.js.map → chunk-K3QWXVLV.js.map} +0 -0
  107. /package/dist/{chunk-PIY23C2Z.js.map → chunk-KWU4EOWC.js.map} +0 -0
  108. /package/dist/{chunk-QHICHZFK.js.map → chunk-L3FCDIJT.js.map} +0 -0
  109. /package/dist/{chunk-C3LKB4N7.js.map → chunk-OCZVJANH.js.map} +0 -0
  110. /package/dist/{chunk-3KHXOLF5.js.map → chunk-OWL6JA6W.js.map} +0 -0
  111. /package/dist/{chunk-XRCWM7JA.js.map → chunk-RE6N3TRQ.js.map} +0 -0
  112. /package/dist/{chunk-SHNGAN3L.js.map → chunk-T7HWU7O4.js.map} +0 -0
  113. /package/dist/{chunk-I5KOLVB6.js.map → chunk-UU7A5DNY.js.map} +0 -0
  114. /package/dist/{chunk-H3NGVXOL.js.map → chunk-UY25GSQ3.js.map} +0 -0
  115. /package/dist/{chunk-BZ3AXEZW.js.map → chunk-XTBFWRM3.js.map} +0 -0
  116. /package/dist/{chunk-LOFMZHJN.js.map → chunk-XZFBOXFK.js.map} +0 -0
  117. /package/dist/{chunk-V2DCI2JL.js.map → chunk-YU2JJIQH.js.map} +0 -0
  118. /package/dist/{client-WAPDTJ5B.js.map → client-PNZ3LL72.js.map} +0 -0
  119. /package/dist/{config-NYFW5P4W.js.map → config-HOKADOXX.js.map} +0 -0
  120. /package/dist/{config-mutate-ZADHR76X.js.map → config-mutate-ZR7EM4IB.js.map} +0 -0
  121. /package/dist/{config-mutator-GJFZWC43.js.map → config-mutator-NWTMXBEY.js.map} +0 -0
  122. /package/dist/{contributions-RROXRQEV.js.map → contributions-NBKZD7QW.js.map} +0 -0
  123. /package/dist/{doctor-DKUDMNK3.js.map → doctor-K6SPV3GU.js.map} +0 -0
  124. /package/dist/{follow-up-tool-OKKSNVCJ.js.map → follow-up-tool-NPC3JLOA.js.map} +0 -0
  125. /package/dist/{hub-5X33WEIO.js.map → hub-NKGZO574.js.map} +0 -0
  126. /package/dist/{promote-YETAZYXW.js.map → promote-HIFKFRC4.js.map} +0 -0
  127. /package/dist/{query-IE5EVVY4.js.map → query-VXE4AREX.js.map} +0 -0
  128. /package/dist/{query-settings-TF4H7EZS.js.map → query-settings-NC7FOIRC.js.map} +0 -0
  129. /package/dist/{registry-OBQMRAYY.js.map → registry-NGRLHM7L.js.map} +0 -0
  130. /package/dist/{request-planner-V6J5EISV.js.map → request-planner-I65SRAJI.js.map} +0 -0
  131. /package/dist/{review-candidates-MTZEBOP5.js.map → review-candidates-7KV34XZR.js.map} +0 -0
  132. /package/dist/{routing-KWZ3X6ZV.js.map → routing-MLOSXPVH.js.map} +0 -0
  133. /package/dist/{schedule-tool-ZSQTA3IW.js.map → schedule-tool-7DCB7KJP.js.map} +0 -0
  134. /package/dist/{scheduler-ST37UR5V.js.map → scheduler-WEOQLNIF.js.map} +0 -0
  135. /package/dist/{seat-RFFUE7RT.js.map → seat-66LQTUIR.js.map} +0 -0
  136. /package/dist/{select-DCG457CP.js.map → select-JV425OUL.js.map} +0 -0
  137. /package/dist/{set-enabled-TD3MPUDH.js.map → set-enabled-DWL2MKVS.js.map} +0 -0
  138. /package/dist/{sprint-tool-OQ55FHX3.js.map → sprint-tool-CDO3HLLT.js.map} +0 -0
  139. /package/dist/{tool-JIRXLLQN.js.map → tool-7EFJJM2A.js.map} +0 -0
  140. /package/dist/{tool-FQE7ZGBT.js.map → tool-U3WQCSUN.js.map} +0 -0
  141. /package/dist/{tool-RJJKMW5D.js.map → tool-W763BDXL.js.map} +0 -0
  142. /package/dist/{wiki-OAWT7LND.js.map → wiki-MIEXBQ5H.js.map} +0 -0
  143. /package/dist/{wiki-enrich-QVZMYHVY.js.map → wiki-enrich-K4HHTRZN.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Db as l,Mb as m}from"./chunk-H7SPRPDG.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Eb as l,Ob as m}from"./chunk-UPRACUXY.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-GB7NAOZ4.js.map
4
+ //# sourceMappingURL=chunk-3DAHVUJH.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-V2DCI2JL.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-YU2JJIQH.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-GGFL7HVN.js.map
17
+ //# sourceMappingURL=chunk-3DX7CKKW.js.map
@@ -1,8 +1,8 @@
1
- import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-MA5ZF4YY.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-KQ5UJTQR.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function j(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
1
+ import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-6QU5YWOE.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-DUVPXHDO.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function j(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
2
2
  `)}async function L(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function ae(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,p;try{p=Y(t.configPath)}catch(a){return`Error: ${a.message}`}let h=p.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(h).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>ee(i,f,d)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!p.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),I=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=_(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!p.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||R;if(!b(g))return`Error: unknown timezone "${g}".`;let u=o||q(i.matched,f);if(!B(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(h[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=j(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let y=s(n.report);if(y&&y!=="always"&&y!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let G={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},H=k({parsed:i,agent:f,prompt:l,timezone:g,notify:$,report:y,enabled:!1,createdBy:e.agentId,approval:G}),N=await I(F=>E(F,`crons.${u}`,H));if(!N.success)return`Error: ${N.error}`;let T=S(w(i.cron,g,d),g),U=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${T}`,`Agent: ${f}`,$?`${y==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
4
4
  `),X=await L(p,t,U);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${T}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=h[o];if(!c)return`Error: schedule "${o}" not found.`;if(!K(p,c,e))return Q(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&m(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await I(i=>E(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(m(c)&&c.approval.requestedBy===e.agentId){let u=await I($=>D($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(m(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await I(u=>{if(!P(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);E(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?S(w(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await L(p,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function ie(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),p=s(r?e.AGENTX_CHAT_ID:n.chatId),h=s(n.accountId);return{agentId:t,channel:d,chatId:p,...h?{accountId:h}:{}}}export{ae as a,ie as b};
8
- //# sourceMappingURL=chunk-GL26HRDW.js.map
8
+ //# sourceMappingURL=chunk-3SWDVBGA.js.map
@@ -1,4 +1,4 @@
1
- import{b as W,c as K}from"./chunk-KQ5UJTQR.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as W,c as K}from"./chunk-DUVPXHDO.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let r=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return r?j(r):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?j(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -142,4 +142,4 @@ ${k(O(ye(c.block,F(o.brief,i.prompt)),i.report),i.expectExitZero)}`,i.maxOutputT
142
142
  `);return t.length<=e?t.join(`
143
143
  `):t.slice(-e).join(`
144
144
  `)}function st(n,e,t){return new Promise((r,i)=>{tt("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(o,s,a)=>{if(o&&o.killed){i(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}r({stdout:String(s??""),stderr:String(a??""),code:o?typeof o.code=="number"?o.code:1:0})})})}export{T as a,te as b,St as c,wt as d,Ye as e,$t as f,Ot as g,w as h,de as i,q as j,pt as k,re as l,se as m,At as n,et as o,it as p,Ie as q,Te as r,Re as s,B as t,U as u};
145
- //# sourceMappingURL=chunk-C5QQW2L7.js.map
145
+ //# sourceMappingURL=chunk-5NE26NUO.js.map
@@ -1,4 +1,4 @@
1
- import{a as pe}from"./chunk-7AB3QUGH.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{c as Ft}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ht,c as Bt}from"./chunk-VJVXEVZ7.js";import{b as jt,f as Mt,g as Et,j as _t,l as Lt,m as Ut,s as Kt}from"./chunk-C5QQW2L7.js";import{b as Ot,d as Nt,e as Dt}from"./chunk-5ONH4ITT.js";import{e as Pt,g as Tt,h as Wt,i as _e}from"./chunk-JRAG37V5.js";import{y as St,z as Ir}from"./chunk-SUVJA67A.js";import{b as $t,f as br}from"./chunk-72SZI2UW.js";import{a as te,b as xt}from"./chunk-A7JSRDJL.js";import{a as At,b as Ee,d as Ce,e as Rt,f as Fe}from"./chunk-BERWTVG2.js";import{c as It,d as vt}from"./chunk-AHWWJ7AF.js";import{ja as Me,ua as kr}from"./chunk-H7SPRPDG.js";import{j as je,r as yr}from"./chunk-UEEB3UTU.js";import{existsSync as vr,mkdirSync as qt,readFileSync as $r,writeFileSync as Sr,renameSync as Ar}from"fs";import{resolve as Jt,dirname as Rr}from"path";var zt=class{filePath;log;constructor(e={}){let t=e.baseDir??Jt(process.cwd(),".agentx");this.filePath=Jt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),qt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!vr(this.filePath))return{version:1,overrides:{}};try{let e=$r(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){qt(Rr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Sr(t,JSON.stringify(e,null,2)),Ar(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Zt,writeFileSync as Ue,appendFileSync as Wr,mkdirSync as Or,existsSync as Xt,statSync as Nr}from"fs";import{resolve as fe}from"path";var Yt="[Agent Memory \u2014 persistent facts from past conversations]",xr=2400;function Gt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Pr(n,e=Date.now()){let t=Nt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Gt(t,Pt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Tr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(te(n.content))return{line:`- [${n.category}] ${xt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Wt(n,e);return{line:`- [${n.category}] ${Gt(o,Tt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Vt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Yt.length,a=!1;for(let i of n){let d=e.length>0?Dt(i.content,e):null,l,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Pr(d,t),c=d.id}else l=Tr(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?_e.length:0;if(s+f+l.line.length>xr)break;r.push({fact:i,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Qt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[_e]:[];return[Yt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
1
+ import{a as pe}from"./chunk-7AB3QUGH.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{c as Ft}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ht,c as Bt}from"./chunk-VJVXEVZ7.js";import{b as jt,f as Mt,g as Et,j as _t,l as Lt,m as Ut,s as Kt}from"./chunk-5NE26NUO.js";import{b as Ot,d as Nt,e as Dt}from"./chunk-5ONH4ITT.js";import{e as Pt,g as Tt,h as Wt,i as _e}from"./chunk-JRAG37V5.js";import{y as St,z as Ir}from"./chunk-F6UAAQSU.js";import{b as $t,f as br}from"./chunk-72SZI2UW.js";import{a as te,b as xt}from"./chunk-A7JSRDJL.js";import{a as At,b as Ee,d as Ce,e as Rt,f as Fe}from"./chunk-BERWTVG2.js";import{c as It,d as vt}from"./chunk-AHWWJ7AF.js";import{ja as Me,ua as kr}from"./chunk-UPRACUXY.js";import{j as je,r as yr}from"./chunk-UEEB3UTU.js";import{existsSync as vr,mkdirSync as qt,readFileSync as $r,writeFileSync as Sr,renameSync as Ar}from"fs";import{resolve as Jt,dirname as Rr}from"path";var zt=class{filePath;log;constructor(e={}){let t=e.baseDir??Jt(process.cwd(),".agentx");this.filePath=Jt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),qt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!vr(this.filePath))return{version:1,overrides:{}};try{let e=$r(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){qt(Rr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Sr(t,JSON.stringify(e,null,2)),Ar(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Zt,writeFileSync as Ue,appendFileSync as Wr,mkdirSync as Or,existsSync as Xt,statSync as Nr}from"fs";import{resolve as fe}from"path";var Yt="[Agent Memory \u2014 persistent facts from past conversations]",xr=2400;function Gt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Pr(n,e=Date.now()){let t=Nt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Gt(t,Pt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Tr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(te(n.content))return{line:`- [${n.category}] ${xt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Wt(n,e);return{line:`- [${n.category}] ${Gt(o,Tt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Vt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Yt.length,a=!1;for(let i of n){let d=e.length>0?Dt(i.content,e):null,l,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Pr(d,t),c=d.id}else l=Tr(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?_e.length:0;if(s+f+l.line.length>xr)break;r.push({fact:i,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Qt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[_e]:[];return[Yt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var en=200,Dr=7,tn=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=fe(e,".agentx/memory"),this.ledger=new Ot(fe(e,".agentx/wiki")),Xt(this.memoryDir)||Or(this.memoryDir,{recursive:!0})}filePath(e){return fe(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ee(t.content)||te(t.content))return!1;let r=t.source.trust??At(t.source.channel),o=t.review??Rt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Wr(this.filePath(e),JSON.stringify(s)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Xt(t))return[];try{let{mtimeMs:r,size:o}=Nr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Zt(t,"utf-8").split(`
4
4
  `).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Fe);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=fe(this.memoryDir,`${t}_bm25_cache.json`),i=vt(s,a),d=It(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Qt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Vt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Ue(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
@@ -39,4 +39,4 @@ ${n.text}`}async function xe(n,e){let t=n.channels[e.channel],r={channel:e.chann
39
39
  `).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(ht(this.file))try{let e=JSON.parse(wt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){er(rr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${sr(4).toString("hex")}.tmp`;nr(t,JSON.stringify(e,null,2)+`
40
40
  `,{encoding:"utf-8",mode:384}),tr(t,this.file)}};import{extname as si}from"path";var ar=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,dr=/<agentx-artifact>[\s\S]*$/i;function _l(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(ar,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,c=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(dr,""):s).trim(),artifacts:r}}function Ll(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(ar,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(dr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ii={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Ul={bytes:20*1024*1024,perMessage:20,pathChars:512};function Hl(n){return ii[si(n).toLowerCase()]??null}var ai=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ![what it shows](https://...)."].join(`
41
41
  `);function Bl(n,e,t){return n==="app"&&e&&t!==!1?ai:void 0}import{lstatSync as kt,mkdirSync as di,readdirSync as li,realpathSync as yt,unlinkSync as ui}from"fs";import{join as Ne,resolve as lr}from"path";var ur=".agentx/outbox",ci=7*24*60*60*1e3;function pi(n,e){try{let t=yt(lr(e,n)),r=Ne(t,ur);return yt(r)===r&&kt(r).isDirectory()?r:null}catch{return null}}function zl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=yt(lr(t,n));kt(Ne(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||di(Ne(o,ur),{recursive:!0})}catch{return 0}let r=pi(n,t);return r?cr(r,(e.now??Date.now())-(e.maxAgeMs??ci)):0}function cr(n,e){let t=0;for(let r of li(n)){let o=Ne(n,r);try{let s=kt(o);s.isDirectory()?t+=cr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(ui(o),t++)}catch{}}return t}export{zt as a,tn as b,nn as c,Wi as d,Er as e,Oi as f,Fr as g,ji as h,Mi as i,Ei as j,Ci as k,Fi as l,_i as m,Li as n,Ur as o,Ui as p,Hi as q,Ji as r,qe as s,Gr as t,zi as u,Yi as v,Vr as w,Gi as x,un as y,Zi as z,Xi as A,pn as B,fn as C,to as D,oa as E,sa as F,da as G,la as H,x as I,ne as J,S as K,ze as L,yo as M,Ve as N,L as O,Xe as P,tt as Q,pt as R,As as S,Os as T,gt as U,Eo as V,qs as W,al as X,dl as Y,ll as Z,ul as _,cl as $,Js as aa,zs as ba,pl as ca,fl as da,gl as ea,ml as fa,yl as ga,kl as ha,bl as ia,Il as ja,vl as ka,$l as la,Sl as ma,Al as na,Rl as oa,xl as pa,Pl as qa,Xs as ra,Tl as sa,Wl as ta,Ol as ua,Nl as va,ir as wa,_l as xa,Ll as ya,Ul as za,Hl as Aa,Bl as Ba,ur as Ca,zl as Da};
42
- //# sourceMappingURL=chunk-PM4Y6ZBW.js.map
42
+ //# sourceMappingURL=chunk-5QK3U7R6.js.map
@@ -1,4 +1,4 @@
1
- import{X as y,Z as v,da as w,ea as C,ga as E,ha as R,ia as I}from"./chunk-H7SPRPDG.js";I();v();var L=1e4,T=["issues","prs","all"],W=/^[\w.-]+(?:\/[\w.-]+)+$/,m=e=>typeof e=="string"?e.trim():"";function f(e){let t=m(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=m(e.project),n=r.split("/");if(!W.test(r)||n.some(o=>o==="."||o==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let s=(m(e.what)||"issues").toLowerCase();if(!T.includes(s))return`count.what must be one of ${T.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:s,max:i}}function S(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=f(t);return typeof r=="string"?null:r}catch{return null}}var _=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function $(e){return`${_(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function Y(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let o=await t(e.provider,e.project,i);if(typeof o!="number")return{verdict:"unverifiable",detail:`${e.project}: ${o.error}`};n+=o}let s=`${n} ${_(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:s,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function B(e,t=fetch){return async(r,n,s)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let d=encodeURIComponent(`repo:${n} is:open is:${s==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${d}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${s==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let o;try{o=await t(i,{headers:y(r,e),signal:AbortSignal.timeout(L)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!o.ok)return{error:o.status===404?"not found (or not visible to the connector)":`HTTP ${o.status}`};if(r==="gitlab"){let a=Number(o.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await o.json().catch(()=>null),l=Number(c?.total_count);return Number.isInteger(l)&&l>=0?l:{error:"no total_count in the answer"}}}var F=["active","done","dropped"],Q=300,A=500;function ee(e,t=w,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let s=f(e);return typeof s=="string"?s:{kind:"count",...s}}let n=C(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply or count":n.replace(/^closeWhen/,"check")}function U(e){if(!e)return null;try{if(JSON.parse(e)?.kind==="count"){let t=S(e);return t?{kind:"count",...t}:null}}catch{return null}return R(e)}function j(e){return e.kind==="count"?$(e):E(e)}function k(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:U(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var N=class{constructor(t){this.db=t;t.exec(`
1
+ import{X as y,Z as v,da as w,ea as C,ga as E,ha as R,ia as I}from"./chunk-UPRACUXY.js";I();v();var L=1e4,T=["issues","prs","all"],W=/^[\w.-]+(?:\/[\w.-]+)+$/,m=e=>typeof e=="string"?e.trim():"";function f(e){let t=m(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=m(e.project),n=r.split("/");if(!W.test(r)||n.some(o=>o==="."||o==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let s=(m(e.what)||"issues").toLowerCase();if(!T.includes(s))return`count.what must be one of ${T.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:s,max:i}}function S(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=f(t);return typeof r=="string"?null:r}catch{return null}}var _=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function $(e){return`${_(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function Y(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let o=await t(e.provider,e.project,i);if(typeof o!="number")return{verdict:"unverifiable",detail:`${e.project}: ${o.error}`};n+=o}let s=`${n} ${_(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:s,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function B(e,t=fetch){return async(r,n,s)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let d=encodeURIComponent(`repo:${n} is:open is:${s==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${d}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${s==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let o;try{o=await t(i,{headers:y(r,e),signal:AbortSignal.timeout(L)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!o.ok)return{error:o.status===404?"not found (or not visible to the connector)":`HTTP ${o.status}`};if(r==="gitlab"){let a=Number(o.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await o.json().catch(()=>null),l=Number(c?.total_count);return Number.isInteger(l)&&l>=0?l:{error:"no total_count in the answer"}}}var F=["active","done","dropped"],Q=300,A=500;function ee(e,t=w,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let s=f(e);return typeof s=="string"?s:{kind:"count",...s}}let n=C(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply or count":n.replace(/^closeWhen/,"check")}function U(e){if(!e)return null;try{if(JSON.parse(e)?.kind==="count"){let t=S(e);return t?{kind:"count",...t}:null}}catch{return null}return R(e)}function j(e){return e.kind==="count"?$(e):E(e)}function k(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:U(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var N=class{constructor(t){this.db=t;t.exec(`
2
2
  CREATE TABLE IF NOT EXISTS goals (
3
3
  id TEXT PRIMARY KEY,
4
4
  title TEXT NOT NULL,
@@ -17,4 +17,4 @@ import{X as y,Z as v,da as w,ea as C,ga as E,ha as R,ia as I}from"./chunk-H7SPRP
17
17
  `)}get(t){let r=this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t);return r?k(r):null}list(t=F,r=200){let n=t.map(()=>"?").join(", ");return this.db.prepare(`SELECT * FROM goals WHERE state IN (${n}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...t,r).map(k)}ensure(t,r,n){return this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING").run(t.id,t.title,r,n,n),this.get(t.id)}upsert(t,r){let n=this.get(t.id);return n?this.db.prepare("UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?").run(t.title||n.title,t.ownerAgent!==void 0?t.ownerAgent:n.ownerAgent,t.doneWhen!==void 0?t.doneWhen:n.doneWhen,t.check!==void 0?t.check?JSON.stringify(t.check):null:n.check?JSON.stringify(n.check):null,r,t.id):this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)").run(t.id,t.title,t.ownerAgent??null,t.doneWhen??null,t.check?JSON.stringify(t.check):null,r,r),this.get(t.id)}close(t,r,n,s){return this.db.prepare("UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'").run(r,n?n.slice(0,A):null,s,s,t).changes>0}markChecked(t,r,n){this.db.prepare("UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?").run(r.slice(0,A),n,t)}dueChecks(t){return this.db.prepare("SELECT * FROM goals WHERE state = 'active' AND check_spec IS NOT NULL AND (last_check_at IS NULL OR last_check_at <= ?) ORDER BY last_check_at ASC LIMIT 50").all(t).map(k)}};async function te(e,t,r,n,s=()=>{}){let i=[];for(let o of e.dueChecks(n-r*6e4)){let c;try{c=await t(o.check)}catch(l){c={verdict:"unverifiable",detail:String(l?.message??l)}}e.markChecked(o.id,c.detail,n),c.verdict==="met"&&e.close(o.id,"done",`check: ${c.detail}`,n)?(i.push(o.id),s(`[goals] ${o.id} done: ${c.detail}`)):c.verdict==="unverifiable"&&s(`[goals] ${o.id}: check failed: ${c.detail}`)}return i}function ne(e,t){let r=[`[Goal] ${e.title} (${e.id}): ${e.state}${e.ownerAgent?`, owner ${e.ownerAgent}`:""}.`];return e.doneWhen&&r.push(`Done when: ${e.doneWhen}`),e.check&&r.push(`Check: ${j(e.check)}${e.lastCheck?`; last seen: ${e.lastCheck}${e.lastCheckAt?` (${new Date(e.lastCheckAt).toISOString().slice(0,16).replace("T"," ")} UTC)`:""}`:""}`),t&&r.push(`Requests under it: ${t.open} open, ${t.done} done.`),r.join(`
18
18
  `)}var g="Africa/Tunis";function b(e,t=g){let r=Object.fromEntries(new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(e)).map(s=>[s.type,s.value])),n=(Number(r.hour)%24*3600+Number(r.minute)*60+Number(r.second))*1e3+e%1e3;return e-n}var M=(e,t)=>new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit"}).format(new Date(e));function q(e,t=10){let r=e.replace(/\s+/g," ").trim().split(" ");return r.slice(0,t).join(" ")+(r.length>t?" \u2026":"")}var H=new Set(["issue","idea","approval","erp","card"]);function oe(e,t={}){let r=e.map(n=>{let s=[],i=(o,c)=>{s.some(l=>l.kind===o&&l.ref===c)||s.push({kind:o,ref:c})};for(let o of n.links??[])H.has(o.kind)&&i(o.kind,o.ref);return n.home&&i(n.home.kind,n.home.link),t.hasPlan?.(n.id)&&i("plan",n.id),n.evidence&&i("evidence",n.evidence),{id:n.id,time:M(n.createdAt,t.zone??g),words:q(n.text),state:n.state,owner:n.agentId,landed:s,noHome:s.length===0&&n.state!=="declined"&&n.state!=="dropped"}});return[...r.filter(n=>n.noHome),...r.filter(n=>!n.noHome)]}var x={timeZone:g,days:7},X=90,D=5,G=120,P=(e,t)=>new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e));function Z(e,t){return{day:P(e,t),start:e,asked:0,done:0,dropped:0,moving:0,waiting:0,stuck:0,rate:null,dropReasons:[],moreReasons:0,resent:0,resentDone:0}}function ie(e,t={}){let r=t.zone??x.timeZone,n=Math.min(Math.max(Math.floor(t.days??x.days),1),X),s=t.now??Date.now(),i=[b(s,r)];for(;i.length<n;)i.unshift(b(i[0]-1,r));let o=i.map(a=>Z(a,r)),c=o.map(()=>new Map),l=0;for(let a of e.flowRows(i[0])){for(;l+1<o.length&&a.createdAt>=o[l+1].start;)l++;let d=o[l];if(d.asked++,a.state==="done")d.done++;else if(a.state==="declined"||a.state==="dropped"){d.dropped++;let p=(a.closeReason??"").replace(/\s+/g," ").trim(),u=p.length>G?`${p.slice(0,G-1)}\u2026`:p||"no reason given";c[l].set(u,(c[l].get(u)??0)+1)}else a.state==="in_progress"||a.state==="waiting_other"?d.moving++:a.state==="waiting_owner"?d.waiting++:a.state==="needs_attention"&&d.stuck++;a.resentAt!==null&&(d.resent++,a.state==="done"&&d.resentDone++)}return o.forEach((a,d)=>{a.rate=a.asked?(a.done+a.dropped)/a.asked:null;let p=[...c[d]].sort((u,h)=>h[1]-u[1]);a.dropReasons=p.slice(0,D).map(([u,h])=>({reason:u,count:h})),a.moreReasons=p.slice(D).reduce((u,[,h])=>u+h,0)}),{zone:r,days:o,today:o[o.length-1]}}var O=e=>e===null?"\u2013":`${Math.round(e*100)}%`;function ce(e){let t=e.today,r=[`Today (${t.day}, ${e.zone}): ${t.asked?`${t.done+t.dropped} of ${t.asked} closed, ${O(t.rate)}`:"nothing asked yet"}.`,` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.`+(t.resent?` ${t.resent} resent once on its own, ${t.resentDone} of them done.`:"")];if(t.dropReasons.length){r.push(" Dropped because:");for(let n of t.dropReasons)r.push(` ${n.count} \xD7 ${n.reason}`);t.moreReasons&&r.push(` ${t.moreReasons} more`)}if(e.days.length>1){r.push("","Day asked done dropped moving waiting stuck rate");for(let n of e.days){let s=[n.asked,n.done,n.dropped,n.moving,n.waiting,n.stuck].map(String);r.push(`${n.day} ${s[0].padStart(5)} ${s[1].padStart(4)} ${s[2].padStart(7)} ${s[3].padStart(6)} ${s[4].padStart(7)} ${s[5].padStart(5)} ${O(n.rate).padStart(4)}`)}}return r.join(`
19
19
  `)}export{f as a,S as b,$ as c,Y as d,B as e,Q as f,A as g,ee as h,j as i,N as j,te as k,ne as l,b as m,oe as n,x as o,X as p,ie as q,ce as r};
20
- //# sourceMappingURL=chunk-HYJWN6L5.js.map
20
+ //# sourceMappingURL=chunk-5VRN6JP7.js.map
@@ -1,2 +1,2 @@
1
- import{s as p}from"./chunk-C5QQW2L7.js";import{b as i,c as u,d as l,e as c}from"./chunk-KQ5UJTQR.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
- //# sourceMappingURL=chunk-MA5ZF4YY.js.map
1
+ import{s as p}from"./chunk-5NE26NUO.js";import{b as i,c as u,d as l,e as c}from"./chunk-DUVPXHDO.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
+ //# sourceMappingURL=chunk-6QU5YWOE.js.map
@@ -1,4 +1,4 @@
1
- import{Ba as ko,Da as vo,G as uo,N as Ft,O as lo,V as Ut,X as go,a as Kr,b as zr,d as On,f as tt,ha as po,i as ro,ia as mo,j as oo,ja as fo,k as Nt,la as ho,ma as yo,n as Bt,na as wo,oa as bo,q as io,r as ao,ra as xo,sa as So,v as co,va as Io,wa as To}from"./chunk-PM4Y6ZBW.js";import{b as Jr}from"./chunk-MEFPXHQJ.js";import{a as Bn}from"./chunk-W4YR2RO2.js";import{a as Gr}from"./chunk-VJVXEVZ7.js";import{b as Xr,d as Nn,e as Zr,f as Lt,i as Vr}from"./chunk-C5QQW2L7.js";import{h as Wr,i as qr}from"./chunk-BE64IJWM.js";import{a as Dn,b as Qr}from"./chunk-J3SOEFRE.js";import{a as Ln,b as Yr}from"./chunk-SIU6STB2.js";import{e as eo,i as to,j as no,k as so}from"./chunk-X5C5W3E4.js";import{d as Fr}from"./chunk-HPRLRD4P.js";import{a as jr}from"./chunk-3KHXOLF5.js";import{g as Ur,h as Hr}from"./chunk-XRCWM7JA.js";import{c as vr,f as Ar}from"./chunk-BZ3AXEZW.js";import{s as Tr,v as Dt,w as kr,y as xe,z as Pn}from"./chunk-SUVJA67A.js";import{a as et,b as Ue,f as Ot}from"./chunk-72SZI2UW.js";import{a as Fe,b as Cn}from"./chunk-FCPTN6NF.js";import{a as $r,c as Cr}from"./chunk-MYVHVJWZ.js";import{e as He,h as Mr,i as Re}from"./chunk-QUFIUXMQ.js";import{a as Rr,b as _r,c as Pr,d as Er,l as Or}from"./chunk-AV7T3SYT.js";import{a as Dr,b as Br}from"./chunk-2HBEZV7L.js";import{a as Nr,b as En}from"./chunk-A7JSRDJL.js";import{c as Lr}from"./chunk-BERWTVG2.js";import{c as ur,d as lr}from"./chunk-AHWWJ7AF.js";import{e as Me}from"./chunk-DSYKYZMT.js";import{$a as wr,Ia as hr,La as _n,Mb as wc,Na as hc,Qa as yr,Va as yc,ab as Et,bb as br,cb as Ve,db as xr,eb as Sr,kb as Ir}from"./chunk-H7SPRPDG.js";import{f as fr,g as Ze,h as mc}from"./chunk-VJ5HC63R.js";import{j as Rn,r as fc}from"./chunk-UEEB3UTU.js";import{a as gr,b as me,c as pr,d as mr,e as Mn}from"./chunk-VQRY4IDI.js";Pn();Ot();var Ht="tool-set",Ao=["answer","code","full"],$o={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},bc=.1;function Mo(n){return{task:Co(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Co(n.agentPrompt,600)}:{}}}var Ro={bundle:Ue({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 _o(n,e=bc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Fn(s.answer),o=Fn(s.code),i=Fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Po(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>$o.answer.includes(t))?"answer":e.every(t=>$o.code.includes(t))?"code":"full"}function Eo(n,e){return Ao.indexOf(n)<Ao.indexOf(e)}function Fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Co(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Oo=!1;function Do(n,e){let t=Dt(Ht);if(t!=="off")return t==="active"&&!Oo&&(Oo=!0,e(`[decisions] seat "${Ht}" is set to active, but only shadow is built: it records and changes nothing`)),xe(Ht,Mo(n),Ro,{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=_o(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Lo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Po(r);kr(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}`+(Eo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function xc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function No(n,e){let t=xc(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 Un(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)`}Pn();Ot();var Bo="session-continuity",Fo={continues:et("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:et("Does the new request refer to something stated earlier in the conversation?")};function Uo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Hn(n.message,1200),previousRequest:n.previousMessage?Hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ho(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 Hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Xt}from"execa";import{spawn as Sc}from"node:child_process";import{createHash as Ic}from"node:crypto";import{createInterface as Tc}from"node:readline";var Se=class extends Error{},kc=n=>Sc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),jn=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(),Tc({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{Ba as ko,Da as vo,G as uo,N as Ft,O as lo,V as Ut,X as go,a as Kr,b as zr,d as On,f as tt,ha as po,i as ro,ia as mo,j as oo,ja as fo,k as Nt,la as ho,ma as yo,n as Bt,na as wo,oa as bo,q as io,r as ao,ra as xo,sa as So,v as co,va as Io,wa as To}from"./chunk-5QK3U7R6.js";import{b as Jr}from"./chunk-MEFPXHQJ.js";import{a as Bn}from"./chunk-W4YR2RO2.js";import{a as Gr}from"./chunk-VJVXEVZ7.js";import{b as Xr,d as Nn,e as Zr,f as Lt,i as Vr}from"./chunk-5NE26NUO.js";import{h as Wr,i as qr}from"./chunk-BE64IJWM.js";import{a as Dn,b as Qr}from"./chunk-J3SOEFRE.js";import{a as Ln,b as Yr}from"./chunk-SIU6STB2.js";import{e as eo,i as to,j as no,k as so}from"./chunk-X5C5W3E4.js";import{d as Fr}from"./chunk-HPRLRD4P.js";import{a as jr}from"./chunk-OWL6JA6W.js";import{g as Ur,h as Hr}from"./chunk-RE6N3TRQ.js";import{c as vr,f as Ar}from"./chunk-XTBFWRM3.js";import{s as Tr,v as Dt,w as kr,y as xe,z as Pn}from"./chunk-F6UAAQSU.js";import{a as et,b as Ue,f as Ot}from"./chunk-72SZI2UW.js";import{a as Fe,b as Cn}from"./chunk-FCPTN6NF.js";import{a as $r,c as Cr}from"./chunk-MYVHVJWZ.js";import{e as He,h as Mr,i as Re}from"./chunk-QUFIUXMQ.js";import{a as Rr,b as _r,c as Pr,d as Er,l as Or}from"./chunk-AV7T3SYT.js";import{a as Dr,b as Br}from"./chunk-2HBEZV7L.js";import{a as Nr,b as En}from"./chunk-A7JSRDJL.js";import{c as Lr}from"./chunk-BERWTVG2.js";import{c as ur,d as lr}from"./chunk-AHWWJ7AF.js";import{e as Me}from"./chunk-DSYKYZMT.js";import{$a as wr,Ia as hr,La as _n,Na as hc,Ob as wc,Qa as yr,Va as yc,ab as Et,bb as br,cb as Ve,db as xr,eb as Sr,kb as Ir}from"./chunk-UPRACUXY.js";import{f as fr,g as Ze,h as mc}from"./chunk-VJ5HC63R.js";import{j as Rn,r as fc}from"./chunk-UEEB3UTU.js";import{a as gr,b as me,c as pr,d as mr,e as Mn}from"./chunk-VQRY4IDI.js";Pn();Ot();var Ht="tool-set",Ao=["answer","code","full"],$o={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},bc=.1;function Mo(n){return{task:Co(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Co(n.agentPrompt,600)}:{}}}var Ro={bundle:Ue({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 _o(n,e=bc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Fn(s.answer),o=Fn(s.code),i=Fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Po(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>$o.answer.includes(t))?"answer":e.every(t=>$o.code.includes(t))?"code":"full"}function Eo(n,e){return Ao.indexOf(n)<Ao.indexOf(e)}function Fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Co(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Oo=!1;function Do(n,e){let t=Dt(Ht);if(t!=="off")return t==="active"&&!Oo&&(Oo=!0,e(`[decisions] seat "${Ht}" is set to active, but only shadow is built: it records and changes nothing`)),xe(Ht,Mo(n),Ro,{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=_o(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Lo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Po(r);kr(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}`+(Eo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function xc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function No(n,e){let t=xc(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 Un(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)`}Pn();Ot();var Bo="session-continuity",Fo={continues:et("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:et("Does the new request refer to something stated earlier in the conversation?")};function Uo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Hn(n.message,1200),previousRequest:n.previousMessage?Hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ho(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 Hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Xt}from"execa";import{spawn as Sc}from"node:child_process";import{createHash as Ic}from"node:crypto";import{createInterface as Tc}from"node:readline";var Se=class extends Error{},kc=n=>Sc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),jn=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(),Tc({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()}},Wn=class{constructor(e=kc,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=Ic("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([S],[E])=>S.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Se("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 S=[...this.entries].find(([,E])=>!E.connection.busy);if(!S)throw new Se("Codex warm process capacity reached");S[1].connection.close(),this.entries.delete(S[0])}try{r={fingerprint:s,connection:new jn(e,this.launchProcess)}}catch{throw new Se("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let S={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",{...S,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return U.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await U,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(S){if(i.close(),!a&&!e.signal?.aborted)throw new Se(S.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:S.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},jo=new Wn;import{execFile as Kc}from"child_process";import{StringDecoder as it}from"string_decoder";import{mkdtempSync as ii,readFileSync as ai,rmSync as di}from"fs";import{join as Jt}from"path";import{tmpdir as ci}from"os";function jt(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 Wt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function qt(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 _e=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var Wo=null;function Gt(){return Wo}function Om(n){Wo=n}function nt(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function vc(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 je=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},qo=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=nt(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=vc(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 je(`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 je(`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=nt(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=nt(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=nt(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();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=nt(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Ac}from"child_process";import{randomUUID as $c}from"crypto";import{existsSync as Cc,readFileSync as Mc}from"fs";import{resolve as Rc}from"path";function _c(n){let e=Rc(n,"CLAUDE.md");if(!Cc(e))return null;try{let t=Mc(e,"utf8");return Or(t)}catch{return null}}var Pc=20*60*1e3,Ec=5e3,st=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},rt=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Oc(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 Go=class{constructor(e={}){this.opts=e}spawn(e,t){return new qn(e,t,this.opts)}},qn=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=Ac(r,o,{cwd:t.workspace,env:Re(Oc({...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:_c(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new _e;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=$c(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??Pc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new st(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new rt(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ec);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.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};Mn();fc();Cn();import{resolve as Ko,join as zo}from"path";var Dc=4e3;function Kt(n){try{let e=zo(Ko(n.root),".agentx","db.sqlite"),t=Rn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Fe(),r=n.input.command?n.input.command.slice(0,Dc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function Jc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,l)}};b.stdout?.on("data",v=>{L+=j.write(v);let x=L.split(`
32
32
  `);L=x.pop()||"";for(let B of x)J(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let C=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if(C.exitCode!==0||h){let v=C,x;return v.timedOut?x=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?x=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?x=si():x=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(E?.message||"")?si():E?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{S?.(),y?.release(A)}}async function ou(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Ie(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function iu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",S=s?`${s}
33
33
 
34
- ${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0};if(r){let{generateStream:J}=await import("./agent-QJPWZDTL.js"),C="",v,x,B,W;for await(let P of J(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")C+=P.text,r(P.text,C);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(x=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!C?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((x===void 0||B===void 0)&&v&&(x=Math.round(v*.7),B=v-x),{content:C||"Done.",tokensUsed:v,usage:x!==void 0||B!==void 0?{inputTokens:x||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-QJPWZDTL.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var au=1e3;async function du(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"}),au),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 cu(n,e,t,s,r,o,i){let a=Gt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Zt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let 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}),f=a.list().length>C}catch(C){return C instanceof je,null}f&&Qn(e.agentId,n,e.model,s,"persistent");let h=Ie(n,e,t),y="",A,S,E,U,b,_,R,M="",L="",N=C=>{if(!i||!C)return;let v;if(L&&C.startsWith(L)?v=C.slice(L.length):v=M&&!M.endsWith(`
34
+ ${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0};if(r){let{generateStream:J}=await import("./agent-4IF72I6E.js"),C="",v,x,B,W;for await(let P of J(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")C+=P.text,r(P.text,C);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(x=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!C?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((x===void 0||B===void 0)&&v&&(x=Math.round(v*.7),B=v-x),{content:C||"Done.",tokensUsed:v,usage:x!==void 0||B!==void 0?{inputTokens:x||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-4IF72I6E.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var au=1e3;async function du(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"}),au),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 cu(n,e,t,s,r,o,i){let a=Gt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Zt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let 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}),f=a.list().length>C}catch(C){return C instanceof je,null}f&&Qn(e.agentId,n,e.model,s,"persistent");let h=Ie(n,e,t),y="",A,S,E,U,b,_,R,M="",L="",N=C=>{if(!i||!C)return;let v;if(L&&C.startsWith(L)?v=C.slice(L.length):v=M&&!M.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${C}`:C,L=C,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:C})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let x=v.raw.message?.content??[];for(let W of x)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let x=v.raw;if(x.is_error){let B=Z(typeof x.result=="string"?x.result:"claude error");A=B.error,S=B.errorKind}else typeof x.result=="string"&&x.result.length>0&&(y=x.result,M||N(x.result));typeof x.session_id=="string"&&(R=x.session_id),x.usage&&(E={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(b=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=qt(x.modelUsage)||_}}}catch(C){if(j)A="task cancelled by operator",S="cancelled";else if(J)if(C instanceof rt)A=`Claude Code was stopped mid-turn (${C.reason}), before its time limit`,S="interrupted";else if(C instanceof st){let v=Z(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,S=v.errorKind}else{let v=Z(`persistent claude process error: ${C?.message||String(C)}`);A=v.error,S=v.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 j&&!A&&(A="task cancelled by operator",S="cancelled"),{content:j?"":y,error:A,errorKind:S,duration:Date.now()-c,usage:E,contextTokens:U,numTurns:b,billedModel:_,claudeSessionId:R}}function bi(n){let e=me(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Xo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ti(t.args,n.taskId,n.agentId)}function uu(n){return me(n.autonomy)||!!n.personLimits}async function lu(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,c=a&&Yo(a,n.tier)||e.personLimits&&ni(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?`${mr(a)}
@@ -167,7 +167,7 @@ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt
167
167
  ${e.message}`),e.queuedAt=void 0}let E=Wi({message:e.message,home:e.context?.home}),U=ji(d.runningTasks,E,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});U&&(this.log(`[${e.agentId}] ${U.slice(0,160)}`),e.message=`${U}
168
168
  ${e.message}`),d.totalTasks++,d.lastActive=new Date;let b={...E.length?{homes:E}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(b),e.runningTaskId=b.id;let _=Et(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(b.id,e.context??{}),e.onStart)try{e.onStart(b.id)}catch{}let R=new AbortController;this.taskAborts.set(b.id,{agentId:e.agentId,channel:b.channel,chatId:typeof b.chatId=="string"?b.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:Lt()?.rootId,workflowRunId:e.workflowRunId??(typeof b.chatId=="string"&&b.chatId.startsWith("workflow:")&&b.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(b.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>Ld&&(M.buffer=M.buffer.slice(M.buffer.length-Ld));for(let m of M.subscribers)try{m(g)}catch{}}},N=Fe();e.taskId=N,b.traceId=N;let j=this.taskAborts.get(b.id);j&&(j.traceId=N);let q=new Map,J=(g,m,T)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:T,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},C=0,v=!1,x=()=>{v||(v=!0,C&&J("first-event",C,"ok"))},B;if(t){let g=ym();B=m=>{x();let T=g(m);if(T&&L(T),Fd(N,e.agentId,m),Bd(q,m),us(m,void 0,e.model||d.def.model),cs(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(x(),Fd(N,e.agentId,g),Bd(q,g),us(g,void 0,e.model||d.def.model),cs(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,P=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;P?.unref?.();let Q=(d.def.preSpawnTimeoutSec??dm)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${b.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Le(R.signal).message;/^timed out/.test(g)&&(te=b.step??"start"),this.log(`[${e.agentId}] task ${b.id} aborted in step "${b.step??"start"}" \u2014 ${g} ${D()}`)},{once:!0});let ne=g=>{b.step=g,this.log(`[${e.agentId}] step ${g} ${D()}`)},le=(g,m,T=0)=>{if(R.signal.aborted)return Promise.reject(Le(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),C=Date.now());let k=Date.now(),F=Za(m(),tm[g]??0,g);return Ya(F,R.signal,T).then(K=>(J(g,k,"ok"),K),K=>{throw J(g,k,"error"),K instanceof ze&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},bt=async(g,m,T,k=0)=>{try{return await le(g,m,k)}catch(F){if(F instanceof ze)return T();throw F}},Rs=!1,wn=!1,_s=g=>{if(!(!Rs||wn)){wn=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-b.startedAt.getTime(),error:g?.error||(R.signal.aborted?Le(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(b.id)?!0:void 0,stopped:!this.interruptedRuns.has(b.id)&&(this.stoppedRuns.has(b.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Ps=!1,Es=g=>{if(Ps)return;Ps=!0,_s(g),this.runReleases.delete(b.id),P&&clearTimeout(P),oe(),d.activeTasks--,this.admissionTickets.get(e)?.release();let m=d.runningTasks.findIndex(k=>k.id===b.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(b.id),this.taskAborts.delete(b.id);let T=this.runEndWaiters.get(b.id);this.runEndWaiters.delete(b.id);for(let k of T??[])try{k()}catch{}M.done=!0,M.endedAt=new Date;for(let k of M.subscribers)try{k(`
169
169
  [task finished]
170
- `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),im).unref?.();try{let k=M.endedAt,F={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:F.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of k){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(we=>(tt(we.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,we)),we=>{throw K(),we}).catch(we=>{this.log(`[${e.agentId}] queued message failed: ${we.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Es),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:jd,selectRequestContext:Wd}=await import("./request-planner-V6J5EISV.js"),Os=bt("request-gate",()=>jd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),bn=!1;Os.then(()=>{bn=!0},()=>{bn=!0});let I=l,xn=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Xe=Ia(this.config.session,w,d.def.tier),xt=Ta(this.config.session),ge=e.isolated===!0,Ye=!ge&&Xe==="lean"&&xt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let St=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await bt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let qd=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;Qa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:qd,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,xn,e.message);let Ds=Date.now(),Ls={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ds).toISOString(),taskId:N,resumeOrigin:Oi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:_n(e.context),..._?{person:_}:{},humanRoot:Ze(e.context),pickup:hr(e.context),operator:yr(e.context),dueAt:Xa(e.context),taskType:gn(e.context)};V().emit("task:started",Ls),Rs=!0;let ee,Sn,Ns=this.classifier;if(Ns&&w!=="a2a"&&!ue){ne("classify");let g=Date.now();Sn=Ns.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let Bs=async g=>{if(!Sn)return;let m;await Promise.race([Sn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await Bs(Qp);let ke=this.config.workflows?.matching,ye,Fs,Us=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Us?.enabled&&(Us.agents[e.agentId]??!0)&&!i&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ke?.suggestThreshold??.65)&&(Fs=go(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ke?.enabled&&!i)try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ke.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ke.mode} reasons=${m.reasons.join(",")||"n/a"}`),ke.mode==="auto"&&m.confidence>=ke.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ve=po(this.config.workflows,e.agentId)&&mo(e)?this.workflowRuns:void 0;if(ve&&!ye&&!i&&this.workflowAutoRunner&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ke?.autoRunThreshold??.85;m&&m.confidence>=T&&(ye={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let de=ve?em():void 0,Gd=de?fo(de):void 0,Kd=this.wikiHub.getAgentWiki(e.agentId),Hs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),js=this.memoryStore.buildContext(Hs),Ws=this.memoryStore.contextFacts(Hs),zd=this.patternStore.findRelevant(e.message,e.agentId,5),Jd=this.patternStore.buildContext(zd),qs="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],F=k.length?T.filter(K=>!k.some(X=>Ve(X,K.frontmatter.name))):T;qs=m(F,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,St)&&(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),V().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),V().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),V().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 m=No({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:St??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${Un(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${Un(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await bt("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Qd=process.env.AGENTX_CONTEXT_SURGERY==="1",Xd=ue?{maxMessages:8,maxChars:2400}:Qd&&Dd(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Yd=!H&&!ue?mm(Kd,e.agentId,{notesInbox:pm(this.config)}):void 0,It=!H&&!Ye?this.sessions.buildHistoryContext(e.agentId,w,I,Xd):void 0,Zd=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Gs,Ks=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new lt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=fs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Gs=hs(m),Ks=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Me&&Me.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],F=It===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${It.length}c/${It.split(`
170
+ `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),im).unref?.();try{let k=M.endedAt,F={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:F.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of k){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(we=>(tt(we.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,we)),we=>{throw K(),we}).catch(we=>{this.log(`[${e.agentId}] queued message failed: ${we.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Es),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:jd,selectRequestContext:Wd}=await import("./request-planner-I65SRAJI.js"),Os=bt("request-gate",()=>jd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),bn=!1;Os.then(()=>{bn=!0},()=>{bn=!0});let I=l,xn=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Xe=Ia(this.config.session,w,d.def.tier),xt=Ta(this.config.session),ge=e.isolated===!0,Ye=!ge&&Xe==="lean"&&xt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let St=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await bt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let qd=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;Qa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:qd,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,xn,e.message);let Ds=Date.now(),Ls={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ds).toISOString(),taskId:N,resumeOrigin:Oi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:_n(e.context),..._?{person:_}:{},humanRoot:Ze(e.context),pickup:hr(e.context),operator:yr(e.context),dueAt:Xa(e.context),taskType:gn(e.context)};V().emit("task:started",Ls),Rs=!0;let ee,Sn,Ns=this.classifier;if(Ns&&w!=="a2a"&&!ue){ne("classify");let g=Date.now();Sn=Ns.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let Bs=async g=>{if(!Sn)return;let m;await Promise.race([Sn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await Bs(Qp);let ke=this.config.workflows?.matching,ye,Fs,Us=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Us?.enabled&&(Us.agents[e.agentId]??!0)&&!i&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ke?.suggestThreshold??.65)&&(Fs=go(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ke?.enabled&&!i)try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ke.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ke.mode} reasons=${m.reasons.join(",")||"n/a"}`),ke.mode==="auto"&&m.confidence>=ke.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ve=po(this.config.workflows,e.agentId)&&mo(e)?this.workflowRuns:void 0;if(ve&&!ye&&!i&&this.workflowAutoRunner&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ke?.autoRunThreshold??.85;m&&m.confidence>=T&&(ye={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let de=ve?em():void 0,Gd=de?fo(de):void 0,Kd=this.wikiHub.getAgentWiki(e.agentId),Hs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),js=this.memoryStore.buildContext(Hs),Ws=this.memoryStore.contextFacts(Hs),zd=this.patternStore.findRelevant(e.message,e.agentId,5),Jd=this.patternStore.buildContext(zd),qs="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],F=k.length?T.filter(K=>!k.some(X=>Ve(X,K.frontmatter.name))):T;qs=m(F,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,St)&&(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),V().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),V().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),V().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 m=No({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:St??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${Un(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${Un(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await bt("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Qd=process.env.AGENTX_CONTEXT_SURGERY==="1",Xd=ue?{maxMessages:8,maxChars:2400}:Qd&&Dd(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Yd=!H&&!ue?mm(Kd,e.agentId,{notesInbox:pm(this.config)}):void 0,It=!H&&!Ye?this.sessions.buildHistoryContext(e.agentId,w,I,Xd):void 0,Zd=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Gs,Ks=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new lt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=fs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Gs=hs(m),Ks=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Me&&Me.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],F=It===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${It.length}c/${It.split(`
171
171
  `).length}L`,K=`[${e.agentId}] ${w}:${I} ${F} | session.messages=${m.length}`+(m.length>0?` first=${T.timestamp.slice(11,19)}(${T.role}:${(T.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Me.cat("context",K)}catch(g){Me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let zs;if(d.def.contextReferences&&!H)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,F]=await le("references",()=>Promise.all([Dn(d.def.workspace),Ln(d.def.workspace)]));if(k.byId.size===0&&F.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Dn(process.cwd()),Ln(process.cwd())]));m={refs:K,recipes:X}}else m={refs:k,recipes:F};this.referencesCache.set(g,m)}let T=Yr({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);T.cards.length>0&&(zs=Qr(T.cards,500*4)),T.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${T.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Js=ge||Ye?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),Qs,Tt=ge?null:Ti(e.message);if(Tt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:Tt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Tt.lookbackDays}d on this chat (cue-triggered)]`],T=[...g.turns].sort((k,F)=>k.ts.localeCompare(F.ts));for(let k of T){let F=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${F} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),Qs=m.join(`
172
172
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Tt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Vd=ue?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Xs,Ys,Zs=!1;bn||ne("request-gate");let Ae=await Os;if(Ae.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Vd==="planner"&&!ge&&!Ae.active&&!Ye&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Zs=!0,Xs=m.sessionHistory,js=m.memoryContext,Ws=m.memoryFacts,Js=m.crossChatContext,Ys=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Zs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let In=`${e.agentId}:${w}:${I}`,kt=Pr(e.message);kt&&(kt==="default"?(this.activeSouls.delete(In),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(In,kt),this.log(`[${e.agentId}] Soul switched to: ${kt}`)));let ec=this.activeSouls.get(In),tc=Rr(d.def.workspace,ec),nc=_r(tc),sc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),rc=rm(d.def.tier),oc=wm(d.def.richMessages,e.context?.via==="voice"?"voice":w),ic=d.def.tier==="claude-code"&&(ge||Xe!=="lean"||ka(xt)),Vs="";if(d.def.workspace&&!ic){let g=G(d.def.workspace,"CLAUDE.md");if(ae(g))try{let m=yt(g,"utf-8");Vs=`[Project CLAUDE.md]
173
173
  ${m.length>4e3?m.slice(0,4e3)+`
@@ -181,9 +181,9 @@ ${$e}`),m+=$e.length}catch{}}}let ac=Tn.length>0?Tn.join(`
181
181
 
182
182
  `)||void 0,At={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:xn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ye||Dd(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:ue?void 0:Jd||void 0,procedureContext:[Gs,Fs].filter(Boolean).join(`
183
183
 
184
- `)||void 0,workflowRunContext:Gd,references:zs,skillInjection:qs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Xs??It,memoryContext:js||void 0,crossChatContext:Js||void 0,longMemoryRecall:Qs||void 0,contextOnDemand:Ye&&!H?Ra(w,I):void 0,wikiContext:Yd,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Ls)}catch{return}})(),rotationMemo:Zd,eventDigest:H?void 0:gm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=ko(w,!H,d.def.richMessages);return g?fm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(At,{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 $t=e.model?void 0:Ar({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?St:null});$t?.downgraded&&this.log(`[${e.agentId}] ${$t.reason}`);let er=vr(d.def.tier,this.config.decisions.routing),tr=$t?.downgraded?Promise.resolve($t.model):!e.model&&er&&(!Ae.active||Ae.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-KWZ3X6ZV.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?St:null,cheapModel:er}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),nr=!1;tr.then(()=>{nr=!0});let Ct=Ae.active&&Ae.preprocess?await bt("select-context",()=>Wd(At),()=>({input:At,excluded:[]})):{input:At,excluded:[]};Ct.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ct.excluded.join(", ")}`);let Mt=Ei(Ct.input,ue?{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),dc=Gr(Mt,{memory:Ws,procedures:Ks,wikiContext:Ct.input.wikiContext}),vn=(Mt?.length??0)+(kn?.length??0)+(e.message?.length??0),Rt={history:Mt?.length??0,sysPrompt:kn?.length??0,message:e.message?.length??0},sr=ma(e.agentId,w,I);fa(sr,vn,Rt);let rr=ha(sr);rr&&this.log(`[${e.agentId}] ${rr}`),vn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${vn} bytes (history=${Rt.history}, sysPrompt=${Rt.sysPrompt}, message=${Rt.message})`),nr||ne("route-model");let or=await tr,ir=d.def.tier!=="claude-code"?void 0:ge?$a():Xe==="lean"?Aa(d.def.workspace,xt,void 0,w):Ma(d.def.workspace);Xe==="lean"&&!ge&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${_a(Xe,xt,w)}`);let ar=d.def.tier==="claude-code"&&!H?Do({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,cc={...e,systemPromptAppend:kn,...ir?{claudeArgs:ir}:{},...or?{model:or}:{}},se,dr=Ka({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),uc=B,cr=!1,An=!0;B=g=>{if(dr.observe(g),de&&An)for(let m of yo(g))ho(m.name,m.input)||(An=!1);uc?.(g)};try{let g=this.workflowAutoRunner;if(ye&&g){let O=ye;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${ye.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:z.runId,workflowMatchConfidence:ye.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(de&&ve)try{let O=bo(ve,e.resumedFrom);wo(ve,{runId:de,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),cr=!0,b.workflow={runId:de,workflowId:lo}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${de} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=d.def.persistentProcess?Gt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!H||z,Be=[Vi(pe),ga(pe,void 0,e.model||d.def.model)].find(Ce=>Ce&&Ce.abort);if(Be){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Be.reason}`);let Ce={content:"",error:Be.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Be.message}`;for(let pc of M.subscribers)try{pc(M.buffer)}catch{}}return Ce}ra();let ce=pa();return ce&&this.log(`[${e.agentId}] ${ce}`),null},T=Bt(e.agentId,void 0,Nt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return d.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(d.def,e);if(k.route==="local"){let O=m();if(O)return d.errors++,se=O,O}let F=d.def.tier==="claude-code",K=F?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,$e=F?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},we=()=>{X&&(L(`
184
+ `)||void 0,workflowRunContext:Gd,references:zs,skillInjection:qs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Xs??It,memoryContext:js||void 0,crossChatContext:Js||void 0,longMemoryRecall:Qs||void 0,contextOnDemand:Ye&&!H?Ra(w,I):void 0,wikiContext:Yd,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Ls)}catch{return}})(),rotationMemo:Zd,eventDigest:H?void 0:gm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=ko(w,!H,d.def.richMessages);return g?fm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(At,{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 $t=e.model?void 0:Ar({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?St:null});$t?.downgraded&&this.log(`[${e.agentId}] ${$t.reason}`);let er=vr(d.def.tier,this.config.decisions.routing),tr=$t?.downgraded?Promise.resolve($t.model):!e.model&&er&&(!Ae.active||Ae.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-MLOSXPVH.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?St:null,cheapModel:er}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),nr=!1;tr.then(()=>{nr=!0});let Ct=Ae.active&&Ae.preprocess?await bt("select-context",()=>Wd(At),()=>({input:At,excluded:[]})):{input:At,excluded:[]};Ct.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ct.excluded.join(", ")}`);let Mt=Ei(Ct.input,ue?{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),dc=Gr(Mt,{memory:Ws,procedures:Ks,wikiContext:Ct.input.wikiContext}),vn=(Mt?.length??0)+(kn?.length??0)+(e.message?.length??0),Rt={history:Mt?.length??0,sysPrompt:kn?.length??0,message:e.message?.length??0},sr=ma(e.agentId,w,I);fa(sr,vn,Rt);let rr=ha(sr);rr&&this.log(`[${e.agentId}] ${rr}`),vn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${vn} bytes (history=${Rt.history}, sysPrompt=${Rt.sysPrompt}, message=${Rt.message})`),nr||ne("route-model");let or=await tr,ir=d.def.tier!=="claude-code"?void 0:ge?$a():Xe==="lean"?Aa(d.def.workspace,xt,void 0,w):Ma(d.def.workspace);Xe==="lean"&&!ge&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${_a(Xe,xt,w)}`);let ar=d.def.tier==="claude-code"&&!H?Do({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,cc={...e,systemPromptAppend:kn,...ir?{claudeArgs:ir}:{},...or?{model:or}:{}},se,dr=Ka({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),uc=B,cr=!1,An=!0;B=g=>{if(dr.observe(g),de&&An)for(let m of yo(g))ho(m.name,m.input)||(An=!1);uc?.(g)};try{let g=this.workflowAutoRunner;if(ye&&g){let O=ye;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${ye.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:z.runId,workflowMatchConfidence:ye.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(de&&ve)try{let O=bo(ve,e.resumedFrom);wo(ve,{runId:de,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),cr=!0,b.workflow={runId:de,workflowId:lo}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${de} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=d.def.persistentProcess?Gt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!H||z,Be=[Vi(pe),ga(pe,void 0,e.model||d.def.model)].find(Ce=>Ce&&Ce.abort);if(Be){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Be.reason}`);let Ce={content:"",error:Be.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Be.message}`;for(let pc of M.subscribers)try{pc(M.buffer)}catch{}}return Ce}ra();let ce=pa();return ce&&this.log(`[${e.agentId}] ${ce}`),null},T=Bt(e.agentId,void 0,Nt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return d.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(d.def,e);if(k.route==="local"){let O=m();if(O)return d.errors++,se=O,O}let F=d.def.tier==="claude-code",K=F?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,$e=F?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},we=()=>{X&&(L(`
185
185
  `),X=!1)},lc=F?K:K?(O,z)=>{we(),K(O,z)}:void 0,$=await le("agent",async()=>{if(k.route!=="local"){let z=await this.runCloudSession(d.def,e,k,N);if(z)return z;let pe=m();if(pe)return pe}let O=await this.inTaskWorktree(d.def,cc);return xi(O.def,O.task,this.providers,lc,Mt,O.fresh?void 0:H,B,R.signal,$e)},am);if(!$.error){let O=hm(d.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([pe,Ne])=>`${pe}=${Ne}`).join(", ")||"none";$.error=`tool_required_not_called: ${O} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}ar&&Lo(ar,{toolUses:q,eventsSeen:v,error:$.error,agentId:e.agentId},O=>this.log(O));let _t=this.interruptedRuns.get(b.id);_t&&($.content="",$.error=_t,$.errorKind="interrupted");let $n=_t?void 0:this.stoppedRuns.get(b.id);$n&&($.content="",$.error=$n,$.errorKind="stopped"),se=$;let be=$.usage?Wr($.usage):void 0,gc=$.billedModel||e.model||d.def.model||void 0,Pt=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,gc,d.def.tier):void 0);if(wn=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-Ds,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:_t?!0:void 0,stopped:$n?!0:void 0,inputTokens:be?.inputTokens,outputTokens:be?.outputTokens,cacheReadTokens:be?.cacheReadTokens,cacheCreateTokens:be?.cacheCreateTokens,tier2InputTokens:be?.tier2InputTokens,tier2OutputTokens:be?.tier2OutputTokens,tier2CacheReadTokens:be?.tier2CacheReadTokens,tier2CacheCreateTokens:be?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:Ae.arm,numTurns:$.numTurns,costUsd:Pt!==void 0&&Number.isFinite(Pt)&&Pt>0?Pt:void 0,injectedContext:dc,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let O=$.error?`[error] ${$.error}`:$.content;M.buffer=O;for(let z of M.subscribers)try{z(O)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,$.content),Ja({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:$.content,taskId:N}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,$.usage,$.contextTokens),$.usage){let ce=$.contextTokens,Ce=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ce??Ce)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ce??"n/a"} tokens (cumulative turn total=${Ce}) \u2014 next turn will rotate`)}let O=Dr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}),z=G(this.wikiHub.getBaseDir(),Ai);O.capture||$i(z,e.agentId,O,ce=>this.log(ce)),O.capture&&(await Bs(Xp),Ci(z,e.agentId,()=>{let ce=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ce,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
186
186
 
187
187
  Agent: ${$.content}`,meta:lm(ee,e.context)})},ce=>this.log(ce)),Br(e.agentId,e.message,$.content,{channel:w,chatId:I,sender:xn},this.memoryStore).catch(()=>{}),zi(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=$.billedModel||e.model||d.def.model,Ne=e.context?.channel,Be=Ne&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ne}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,pe,Ne,Be),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${D()}`)}return $}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=jt(g.message);return se={content:"",error:Wt(m),errorKind:m.kind},se}finally{if(dr.stop(),cr&&de&&ve)try{let g=se?.usage,m=xo(ve,de,{error:se?se.error||void 0:R.signal.aborted?Le(R.signal).message:"run ended before completion",canceled:So(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:An,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${de} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${de} (non-fatal): ${g?.message||g}`)}_s(se),Es(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?om(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Io(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Qe,this.safe(e.agentId),t);ae(s)||Yp(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Vp(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Qe,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of he(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),S=t-1-A;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Qe);if(!ae(e))return 0;let t=0;for(let s of he(e)){let r=G(e,s),o;try{o=he(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=he(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(yt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=um){let t=G(process.cwd(),Qe);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of he(t)){let i=G(t,o),a;try{a=he(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Zp(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Qe,this.safe(e));if(!ae(s))return[];let r=he(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=he(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(yt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Qe,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=he(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(yt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Bt(t,void 0,Nt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Bn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||tt(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){nm.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Zt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:wr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{tt(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 wm(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(`
188
188
  `)}export{jo as a,Om as b,qo as c,_c as d,Go as e,Kt as f,Jm as g,Zm as h,Vm as i,rf as j,Zt as k,Vc as l,yi as m,ru as n,ou as o,iu as p,xi as q,en as r,Ai as s,Of as t,tn as u,Ru as v,Ff as w,Uf as x,jf as y,sn as z,Gf as A,ss as B,V as C,Ji as D,Ju as E,Zu as F,Yi as G,ah as H,Zi as I,na as J,Sh as K,Ih as L,da as M,Th as N,ca as O,dn as P,_h as Q,Ph as R,lt as S,ug as T,lg as U,gg as V,pg as W,mg as X,fs as Y,gn as Z,dy as _,mn as $,pn as aa,sd as ba,pt as ca,rd as da,fy as ea,hy as fa,yy as ga,wy as ha,by as ia,xy as ja,Sy as ka,Kg as la,hd as ma,Je as na,sm as oa,rm as pa,ob as qa,ib as ra,om as sa,cm as ta,lm as ua,gm as va,mm as wa,Ms as xa,Nd as ya,Bd as za,hm as Aa,Fd as Ba,Ud as Ca,wm as Da};
189
- //# sourceMappingURL=chunk-D64VFKUU.js.map
189
+ //# sourceMappingURL=chunk-7SKUXUIX.js.map
@@ -1,4 +1,4 @@
1
- import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{fa as ne,ga as re,ia as oe,ja as ie,pa as I,ua as Je}from"./chunk-H7SPRPDG.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{fa as ne,ga as re,ia as oe,ja as ie,pa as I,ua as Je}from"./chunk-UPRACUXY.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0"><dict>
4
4
  <key>Label</key><string>${t(e.label??X)}</string>
@@ -35,4 +35,4 @@ function run(argv) {
35
35
  `),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
36
36
  `),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
37
37
  `),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
38
- //# sourceMappingURL=chunk-IJYCPFLZ.js.map
38
+ //# sourceMappingURL=chunk-BBXB7X25.js.map
@@ -0,0 +1,3 @@
1
+ import{Ob as $,lb as S}from"./chunk-UPRACUXY.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as y,writeFileSync as C}from"fs";import{resolve as c}from"path";function m(t){return c(t,".agentx","email")}function u(t,e){k(c(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>c(m(t),"threads.json");function w(t){return g(D(t))??{}}function I(t,e){return w(t)[e.toLowerCase()]}function L(t,e){let r=w(t);r[e.to.toLowerCase()]=e,u(D(t),r)}var h=(t,e)=>c(m(t),"cursors",`${e}.json`);function z(t,e){return g(h(t,e))}function B(t,e,r){u(h(t,e),r)}var T=2e4,_=t=>c(m(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),a=(t,e)=>c(_(t),`${e}.json`);function U(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return u(a(t,s.id),s),s}function v(t,e){return N(e)?g(a(t,e)):null}function V(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function W(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${a(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(a(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let d=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...d?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let f=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!f.ok){u(a(t,e),{...s,error:f.error});try{y(i)}catch{}return{ok:!1,error:`not sent: ${f.error}`}}o.status="sent",delete o.error}u(a(t,e),o);try{y(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function R(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);return J(s,{name:e,address:t.address},r,{"Auto-Submitted":"auto-replied"})}async function J(t,e,r,n){let{default:s}=await import("nodemailer"),i=s.createTransport({host:t.host,port:t.port,secure:t.secure,auth:{user:t.user,pass:t.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await i.sendMail({from:e,to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:n})).messageId}finally{i.close()}}function G(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=S.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,d=i.name||t?.agents?.[r.agent]?.name||r.agent;return await R(i,d,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{I as a,L as b,z as c,B as d,U as e,v as f,V as g,W as h,P as i,R as j,J as k,G as l};
3
+ //# sourceMappingURL=chunk-DECMCWGN.js.map