agentix-cli 0.221.1 → 0.222.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 (142) hide show
  1. package/dist/{App-QRZJGHNK.js → App-GTHE3AEN.js} +2 -2
  2. package/dist/{ChatApp-DYC2WNAP.js → ChatApp-XQ535KGJ.js} +2 -2
  3. package/dist/{absorb-eval-4FENRVXM.js → absorb-eval-VBW5ZT4O.js} +2 -2
  4. package/dist/{adapter-5WMQSSQM.js → adapter-BWCC3TCU.js} +2 -2
  5. package/dist/{agent-DXKDG4DQ.js → agent-2JGSQ4NM.js} +2 -2
  6. package/dist/{board-dashboard-QV7OD4SO.js → board-dashboard-GP44R4TJ.js} +4 -4
  7. package/dist/{chunk-AZCGU5XU.js → chunk-5NU3CFIM.js} +2 -2
  8. package/dist/{chunk-AAQOXNLE.js → chunk-5QAOPW5J.js} +240 -240
  9. package/dist/chunk-5QAOPW5J.js.map +1 -0
  10. package/dist/{chunk-AAPHOKWS.js → chunk-66GIGOWE.js} +2 -2
  11. package/dist/{chunk-AEFO6ES5.js → chunk-7Z6AKGWN.js} +2 -2
  12. package/dist/{chunk-VYNM7HYU.js → chunk-AICFBHJQ.js} +2 -2
  13. package/dist/{chunk-VOVDWFFP.js → chunk-AVJ4RR2R.js} +2 -2
  14. package/dist/chunk-AVJ4RR2R.js.map +1 -0
  15. package/dist/{chunk-WQTPSXVB.js → chunk-AYZYEYI7.js} +2 -2
  16. package/dist/{chunk-U476QMLK.js → chunk-BPTWALJN.js} +2 -2
  17. package/dist/{chunk-FRYEUVYD.js → chunk-BRUKO65H.js} +2 -2
  18. package/dist/{chunk-ABMDDRZL.js → chunk-CA7ZDUGT.js} +2 -2
  19. package/dist/{chunk-575LJSX2.js → chunk-CJ3FDM2O.js} +5 -5
  20. package/dist/{chunk-Y6KR7NXL.js → chunk-E7GOYIL7.js} +2 -2
  21. package/dist/{chunk-XC3466Z4.js → chunk-EUNCDWTP.js} +2 -2
  22. package/dist/{chunk-LO5A3VKY.js → chunk-GR6BSPIQ.js} +2 -2
  23. package/dist/{chunk-6EJJKOMW.js → chunk-GZEWEPH5.js} +3 -3
  24. package/dist/{chunk-JMRFYGET.js → chunk-HGKDI24R.js} +2 -2
  25. package/dist/{chunk-D5LIMOI6.js → chunk-HQAWGHFI.js} +2 -2
  26. package/dist/{chunk-TN3XNBQN.js → chunk-HSWRKXCK.js} +2 -2
  27. package/dist/{chunk-XPYZBWI7.js → chunk-IVMV2YSK.js} +2 -2
  28. package/dist/{chunk-GO4J44UD.js → chunk-JT6BGINS.js} +2 -2
  29. package/dist/{chunk-RMB6G7X2.js → chunk-KLLI3MBQ.js} +2 -2
  30. package/dist/{chunk-O4EQAPBB.js → chunk-NHIMHP6L.js} +2 -2
  31. package/dist/{chunk-NCMPJPXG.js → chunk-NXXYXNS3.js} +2 -2
  32. package/dist/{chunk-4UJDRI7W.js → chunk-OVLLJMI7.js} +2 -2
  33. package/dist/{chunk-JD5TCX4X.js → chunk-P5ZGTHJO.js} +2 -2
  34. package/dist/{chunk-XV7IHWQE.js → chunk-PGKN3RJV.js} +2 -2
  35. package/dist/{chunk-CIW37UJT.js → chunk-QQLXTDS2.js} +2 -2
  36. package/dist/{chunk-5QXRGX2F.js → chunk-TFXDHVHP.js} +2 -2
  37. package/dist/{chunk-5BT4VPJC.js → chunk-VZ5F3CXQ.js} +2 -2
  38. package/dist/{chunk-SQP6A5AG.js → chunk-WNQSR6RI.js} +2 -2
  39. package/dist/{chunk-NW7B53KD.js → chunk-X6TKWUY2.js} +2 -2
  40. package/dist/cli.js +1 -1
  41. package/dist/{client-W7VFEYQ3.js → client-HA6ZO6AE.js} +2 -2
  42. package/dist/{config-ZVRI3GFZ.js → config-YNYDIHQF.js} +2 -2
  43. package/dist/{config-mutate-OM4MI56W.js → config-mutate-6FOGY2HR.js} +2 -2
  44. package/dist/{config-mutator-RK3UQORI.js → config-mutator-PL26XUXG.js} +2 -2
  45. package/dist/{contributions-3WW5AJ5A.js → contributions-FHSZECVP.js} +2 -2
  46. package/dist/{doctor-AW53DQDU.js → doctor-TVOOFWSO.js} +2 -2
  47. package/dist/{follow-up-tool-N5U7U5WN.js → follow-up-tool-EU2267VV.js} +2 -2
  48. package/dist/{hub-J43NXLW3.js → hub-KOWKXWDL.js} +2 -2
  49. package/dist/index.d.ts +16 -0
  50. package/dist/index.js +1 -1
  51. package/dist/{org-tool-VNDHR7WM.js → org-tool-2QQTKDCQ.js} +2 -2
  52. package/dist/{program-Q4DXWAQU.js → program-7U7DSO7T.js} +24 -24
  53. package/dist/{promote-AO6KC3SU.js → promote-PCK4AROK.js} +2 -2
  54. package/dist/{query-W6OYKQ2U.js → query-H2VPF42I.js} +2 -2
  55. package/dist/{query-settings-2D6NCHCV.js → query-settings-G2N46YLB.js} +2 -2
  56. package/dist/{registry-Q3H6QR6Q.js → registry-PGYJ4FRA.js} +2 -2
  57. package/dist/{request-planner-SDO5MNFV.js → request-planner-XPPRK5G3.js} +2 -2
  58. package/dist/{review-candidates-EAOLCDIK.js → review-candidates-I47EBNJT.js} +2 -2
  59. package/dist/{routing-VDVZ4IYF.js → routing-AIHGJNO7.js} +2 -2
  60. package/dist/{schedule-tool-65H6URQU.js → schedule-tool-CX6YSAQY.js} +2 -2
  61. package/dist/{scheduler-B52UIMKB.js → scheduler-LEVZX5IH.js} +2 -2
  62. package/dist/{seat-5DLUHBTK.js → seat-DEV2UTKV.js} +2 -2
  63. package/dist/{select-Z3JDFC2C.js → select-ULJSZMQD.js} +2 -2
  64. package/dist/{set-enabled-FMI2GXCF.js → set-enabled-KR5BSI4O.js} +2 -2
  65. package/dist/{sprint-tool-5NJYOFIZ.js → sprint-tool-KW3ZMBKF.js} +2 -2
  66. package/dist/{tool-RW32VEIV.js → tool-5AGFJGDR.js} +2 -2
  67. package/dist/{tool-2DOU5XCQ.js → tool-FEJMTLSC.js} +2 -2
  68. package/dist/{tool-YT3WBUHS.js → tool-GI7NVYWM.js} +2 -2
  69. package/dist/tool-LE26EHHZ.js +2 -0
  70. package/dist/{tool-ZSNE7YWS.js → tool-WIP576PN.js} +2 -2
  71. package/dist/{wiki-7PQ5YVA7.js → wiki-ZAJCINRT.js} +2 -2
  72. package/dist/wiki-enrich-EE4STC4Q.js +2 -0
  73. package/package.json +1 -1
  74. package/dist/chunk-AAQOXNLE.js.map +0 -1
  75. package/dist/chunk-VOVDWFFP.js.map +0 -1
  76. package/dist/tool-AR4BLSYC.js +0 -2
  77. package/dist/wiki-enrich-IQZ5Y7A5.js +0 -2
  78. /package/dist/{App-QRZJGHNK.js.map → App-GTHE3AEN.js.map} +0 -0
  79. /package/dist/{ChatApp-DYC2WNAP.js.map → ChatApp-XQ535KGJ.js.map} +0 -0
  80. /package/dist/{absorb-eval-4FENRVXM.js.map → absorb-eval-VBW5ZT4O.js.map} +0 -0
  81. /package/dist/{adapter-5WMQSSQM.js.map → adapter-BWCC3TCU.js.map} +0 -0
  82. /package/dist/{agent-DXKDG4DQ.js.map → agent-2JGSQ4NM.js.map} +0 -0
  83. /package/dist/{board-dashboard-QV7OD4SO.js.map → board-dashboard-GP44R4TJ.js.map} +0 -0
  84. /package/dist/{chunk-AZCGU5XU.js.map → chunk-5NU3CFIM.js.map} +0 -0
  85. /package/dist/{chunk-AAPHOKWS.js.map → chunk-66GIGOWE.js.map} +0 -0
  86. /package/dist/{chunk-AEFO6ES5.js.map → chunk-7Z6AKGWN.js.map} +0 -0
  87. /package/dist/{chunk-VYNM7HYU.js.map → chunk-AICFBHJQ.js.map} +0 -0
  88. /package/dist/{chunk-WQTPSXVB.js.map → chunk-AYZYEYI7.js.map} +0 -0
  89. /package/dist/{chunk-U476QMLK.js.map → chunk-BPTWALJN.js.map} +0 -0
  90. /package/dist/{chunk-FRYEUVYD.js.map → chunk-BRUKO65H.js.map} +0 -0
  91. /package/dist/{chunk-ABMDDRZL.js.map → chunk-CA7ZDUGT.js.map} +0 -0
  92. /package/dist/{chunk-575LJSX2.js.map → chunk-CJ3FDM2O.js.map} +0 -0
  93. /package/dist/{chunk-Y6KR7NXL.js.map → chunk-E7GOYIL7.js.map} +0 -0
  94. /package/dist/{chunk-XC3466Z4.js.map → chunk-EUNCDWTP.js.map} +0 -0
  95. /package/dist/{chunk-LO5A3VKY.js.map → chunk-GR6BSPIQ.js.map} +0 -0
  96. /package/dist/{chunk-6EJJKOMW.js.map → chunk-GZEWEPH5.js.map} +0 -0
  97. /package/dist/{chunk-JMRFYGET.js.map → chunk-HGKDI24R.js.map} +0 -0
  98. /package/dist/{chunk-D5LIMOI6.js.map → chunk-HQAWGHFI.js.map} +0 -0
  99. /package/dist/{chunk-TN3XNBQN.js.map → chunk-HSWRKXCK.js.map} +0 -0
  100. /package/dist/{chunk-XPYZBWI7.js.map → chunk-IVMV2YSK.js.map} +0 -0
  101. /package/dist/{chunk-GO4J44UD.js.map → chunk-JT6BGINS.js.map} +0 -0
  102. /package/dist/{chunk-RMB6G7X2.js.map → chunk-KLLI3MBQ.js.map} +0 -0
  103. /package/dist/{chunk-O4EQAPBB.js.map → chunk-NHIMHP6L.js.map} +0 -0
  104. /package/dist/{chunk-NCMPJPXG.js.map → chunk-NXXYXNS3.js.map} +0 -0
  105. /package/dist/{chunk-4UJDRI7W.js.map → chunk-OVLLJMI7.js.map} +0 -0
  106. /package/dist/{chunk-JD5TCX4X.js.map → chunk-P5ZGTHJO.js.map} +0 -0
  107. /package/dist/{chunk-XV7IHWQE.js.map → chunk-PGKN3RJV.js.map} +0 -0
  108. /package/dist/{chunk-CIW37UJT.js.map → chunk-QQLXTDS2.js.map} +0 -0
  109. /package/dist/{chunk-5QXRGX2F.js.map → chunk-TFXDHVHP.js.map} +0 -0
  110. /package/dist/{chunk-5BT4VPJC.js.map → chunk-VZ5F3CXQ.js.map} +0 -0
  111. /package/dist/{chunk-SQP6A5AG.js.map → chunk-WNQSR6RI.js.map} +0 -0
  112. /package/dist/{chunk-NW7B53KD.js.map → chunk-X6TKWUY2.js.map} +0 -0
  113. /package/dist/{client-W7VFEYQ3.js.map → client-HA6ZO6AE.js.map} +0 -0
  114. /package/dist/{config-ZVRI3GFZ.js.map → config-YNYDIHQF.js.map} +0 -0
  115. /package/dist/{config-mutate-OM4MI56W.js.map → config-mutate-6FOGY2HR.js.map} +0 -0
  116. /package/dist/{config-mutator-RK3UQORI.js.map → config-mutator-PL26XUXG.js.map} +0 -0
  117. /package/dist/{contributions-3WW5AJ5A.js.map → contributions-FHSZECVP.js.map} +0 -0
  118. /package/dist/{doctor-AW53DQDU.js.map → doctor-TVOOFWSO.js.map} +0 -0
  119. /package/dist/{follow-up-tool-N5U7U5WN.js.map → follow-up-tool-EU2267VV.js.map} +0 -0
  120. /package/dist/{hub-J43NXLW3.js.map → hub-KOWKXWDL.js.map} +0 -0
  121. /package/dist/{org-tool-VNDHR7WM.js.map → org-tool-2QQTKDCQ.js.map} +0 -0
  122. /package/dist/{program-Q4DXWAQU.js.map → program-7U7DSO7T.js.map} +0 -0
  123. /package/dist/{promote-AO6KC3SU.js.map → promote-PCK4AROK.js.map} +0 -0
  124. /package/dist/{query-W6OYKQ2U.js.map → query-H2VPF42I.js.map} +0 -0
  125. /package/dist/{query-settings-2D6NCHCV.js.map → query-settings-G2N46YLB.js.map} +0 -0
  126. /package/dist/{registry-Q3H6QR6Q.js.map → registry-PGYJ4FRA.js.map} +0 -0
  127. /package/dist/{request-planner-SDO5MNFV.js.map → request-planner-XPPRK5G3.js.map} +0 -0
  128. /package/dist/{review-candidates-EAOLCDIK.js.map → review-candidates-I47EBNJT.js.map} +0 -0
  129. /package/dist/{routing-VDVZ4IYF.js.map → routing-AIHGJNO7.js.map} +0 -0
  130. /package/dist/{schedule-tool-65H6URQU.js.map → schedule-tool-CX6YSAQY.js.map} +0 -0
  131. /package/dist/{scheduler-B52UIMKB.js.map → scheduler-LEVZX5IH.js.map} +0 -0
  132. /package/dist/{seat-5DLUHBTK.js.map → seat-DEV2UTKV.js.map} +0 -0
  133. /package/dist/{select-Z3JDFC2C.js.map → select-ULJSZMQD.js.map} +0 -0
  134. /package/dist/{set-enabled-FMI2GXCF.js.map → set-enabled-KR5BSI4O.js.map} +0 -0
  135. /package/dist/{sprint-tool-5NJYOFIZ.js.map → sprint-tool-KW3ZMBKF.js.map} +0 -0
  136. /package/dist/{tool-RW32VEIV.js.map → tool-5AGFJGDR.js.map} +0 -0
  137. /package/dist/{tool-2DOU5XCQ.js.map → tool-FEJMTLSC.js.map} +0 -0
  138. /package/dist/{tool-YT3WBUHS.js.map → tool-GI7NVYWM.js.map} +0 -0
  139. /package/dist/{tool-AR4BLSYC.js.map → tool-LE26EHHZ.js.map} +0 -0
  140. /package/dist/{tool-ZSNE7YWS.js.map → tool-WIP576PN.js.map} +0 -0
  141. /package/dist/{wiki-7PQ5YVA7.js.map → wiki-ZAJCINRT.js.map} +0 -0
  142. /package/dist/{wiki-enrich-IQZ5Y7A5.js.map → wiki-enrich-EE4STC4Q.js.map} +0 -0
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-AZCGU5XU.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
1
+ import{d as h}from"./chunk-5NU3CFIM.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
2
  `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
4
  `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
5
  `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
- //# sourceMappingURL=chunk-WQTPSXVB.js.map
6
+ //# sourceMappingURL=chunk-AYZYEYI7.js.map
@@ -1,5 +1,5 @@
1
- import{Cc as b,sc as m}from"./chunk-VOVDWFFP.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{Cc as b,sc as m}from"./chunk-AVJ4RR2R.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-U476QMLK.js.map
5
+ //# sourceMappingURL=chunk-BPTWALJN.js.map
@@ -1,4 +1,4 @@
1
- import{a as fe}from"./chunk-7AB3QUGH.js";import{c as Ut}from"./chunk-EFXZACH4.js";import{b as Ue}from"./chunk-7YOLZGB5.js";import{b as qt,c as Gt}from"./chunk-IH65GDJR.js";import{b as Ct,f as Ft,g as _t,j as Ht,l as Bt,m as Kt,s as zt}from"./chunk-NW7B53KD.js";import{a as Lt}from"./chunk-GV7S5BAX.js";import{b as Mt,d as Et,e as jt}from"./chunk-5ONH4ITT.js";import{e as Nt,g as Ot,h as Dt,i as Le}from"./chunk-JRAG37V5.js";import{a as Pt,b as Ce,d as Fe,e as Wt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Tt}from"./chunk-A7JSRDJL.js";import{c as St,d as At}from"./chunk-AHWWJ7AF.js";import{y as xt,z as Tr}from"./chunk-Y6KR7NXL.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Va as je,gb as Pr}from"./chunk-VOVDWFFP.js";import{j as Ee,r as xr}from"./chunk-N47Y5ADQ.js";import{existsSync as Nr,mkdirSync as Jt,readFileSync as Or,writeFileSync as Dr,renameSync as Mr}from"fs";import{resolve as Yt,dirname as Er}from"path";var Vt=class{filePath;log;constructor(e={}){let t=e.baseDir??Yt(process.cwd(),".agentx");this.filePath=Yt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Nr(this.filePath))return{version:1,overrides:{}};try{let e=Or(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){Jt(Er(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Dr(t,JSON.stringify(e,null,2)),Mr(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 i=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),i}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 tn,writeFileSync as He,appendFileSync as _r,mkdirSync as Lr,existsSync as nn,statSync as Ur}from"fs";import{resolve as ge}from"path";var Qt="[Agent Memory \u2014 persistent facts from past conversations]",jr=2400;function Zt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Cr(n,e=Date.now()){let t=Et(n,e),r=n.undated?"UNVERIFIED (never checked) ":Zt(t,Nt(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 Fr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Tt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Dt(n,e);return{line:`- [${n.category}] ${Zt(o,Ot(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Xt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Qt.length,i=!1;for(let a of n){let d=e.length>0?jt(a.content,e):null,l,c,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Cr(d,t),c=d.id}else l=Fr(a,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!i?Le.length:0;if(s+f+l.line.length>jr)break;r.push({fact:a,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(i=!0)}return r}function en(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Qt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
1
+ import{a as fe}from"./chunk-7AB3QUGH.js";import{c as Ut}from"./chunk-EFXZACH4.js";import{b as Ue}from"./chunk-7YOLZGB5.js";import{b as qt,c as Gt}from"./chunk-IH65GDJR.js";import{b as Ct,f as Ft,g as _t,j as Ht,l as Bt,m as Kt,s as zt}from"./chunk-X6TKWUY2.js";import{a as Lt}from"./chunk-GV7S5BAX.js";import{b as Mt,d as Et,e as jt}from"./chunk-5ONH4ITT.js";import{e as Nt,g as Ot,h as Dt,i as Le}from"./chunk-JRAG37V5.js";import{a as Pt,b as Ce,d as Fe,e as Wt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Tt}from"./chunk-A7JSRDJL.js";import{c as St,d as At}from"./chunk-AHWWJ7AF.js";import{y as xt,z as Tr}from"./chunk-E7GOYIL7.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Va as je,gb as Pr}from"./chunk-AVJ4RR2R.js";import{j as Ee,r as xr}from"./chunk-N47Y5ADQ.js";import{existsSync as Nr,mkdirSync as Jt,readFileSync as Or,writeFileSync as Dr,renameSync as Mr}from"fs";import{resolve as Yt,dirname as Er}from"path";var Vt=class{filePath;log;constructor(e={}){let t=e.baseDir??Yt(process.cwd(),".agentx");this.filePath=Yt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Nr(this.filePath))return{version:1,overrides:{}};try{let e=Or(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){Jt(Er(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Dr(t,JSON.stringify(e,null,2)),Mr(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 i=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),i}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 tn,writeFileSync as He,appendFileSync as _r,mkdirSync as Lr,existsSync as nn,statSync as Ur}from"fs";import{resolve as ge}from"path";var Qt="[Agent Memory \u2014 persistent facts from past conversations]",jr=2400;function Zt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Cr(n,e=Date.now()){let t=Et(n,e),r=n.undated?"UNVERIFIED (never checked) ":Zt(t,Nt(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 Fr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Tt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Dt(n,e);return{line:`- [${n.category}] ${Zt(o,Ot(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Xt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Qt.length,i=!1;for(let a of n){let d=e.length>0?jt(a.content,e):null,l,c,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Cr(d,t),c=d.id}else l=Fr(a,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!i?Le.length:0;if(s+f+l.line.length>jr)break;r.push({fact:a,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(i=!0)}return r}function en(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Qt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var rn=200,Hr=7,on=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Mt(ge(e,".agentx/wiki")),nn(this.memoryDir)||Lr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Pt(t.source.channel),o=t.review??Wt(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 _r(this.filePath(e),JSON.stringify(s)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!nn(t))return[];try{let{mtimeMs:r,size:o}=Ur(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let a=tn(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:a}),a.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),i=ge(this.memoryDir,`${t}_bm25_cache.json`),a=At(s,i),d=St(e,a),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 en(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Xt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let i of r)if(o.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(i=>JSON.stringify(i)).join(`
@@ -39,4 +39,4 @@ ${n.text}`}async function Pe(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 i=JSON.parse(r[s]);(!e||i.person===e)&&o.push(i)}catch{}return o}load(){if(kt(this.file))try{let e=JSON.parse(bt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){lr(pr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${gr(4).toString("hex")}.tmp`;cr(t,JSON.stringify(e,null,2)+`
40
40
  `,{encoding:"utf-8",mode:384}),ur(t,this.file)}};import{extname as bi}from"path";var hr=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,wr=/<agentx-artifact>[\s\S]*$/i;function du(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(hr,(i,a)=>{try{let d=JSON.parse(a.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(wr,""):s).trim(),artifacts:r}}function lu(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(hr,(s,i)=>{try{let a=JSON.parse(i.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});r=(e?o.replace(wr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,i)=>s===void 0||i===void 0?o:`[${s||i}](${i})`)}var vi={".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"}},uu={bytes:20*1024*1024,perMessage:20,pathChars:512};function cu(n){return vi[bi(n).toLowerCase()]??null}var Ii=["[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 pu(n,e,t){return n==="app"&&e&&t!==!1?Ii:void 0}import{lstatSync as It,mkdirSync as $i,readdirSync as Si,realpathSync as vt,unlinkSync as Ai}from"fs";import{join as De,resolve as yr}from"path";var kr=".agentx/outbox",Ri=7*24*60*60*1e3;function xi(n,e){try{let t=vt(yr(e,n)),r=De(t,kr);return vt(r)===r&&It(r).isDirectory()?r:null}catch{return null}}function hu(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=vt(yr(t,n));It(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||$i(De(o,kr),{recursive:!0})}catch{return 0}let r=xi(n,t);return r?br(r,(e.now??Date.now())-(e.maxAgeMs??Ri)):0}function br(n,e){let t=0;for(let r of Si(n)){let o=De(n,r);try{let s=It(o);s.isDirectory()?t+=br(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(Ai(o),t++)}catch{}}return t}export{Vt as a,on as b,sn as c,qi as d,qr as e,Gi as f,zr as g,Yi as h,Vi as i,Qi as j,Zi as k,Xi as l,ea as m,ta as n,Vr as o,na as p,ra as q,aa as r,Ge as s,oo as t,da as u,la as v,so as w,ua as x,fn as y,fa as z,ga as A,mn as B,hn as C,co as D,ka as E,ba as F,$a as G,Sa as H,x as I,re as J,S as K,Je as L,xo as M,Qe as N,U as O,et as P,nt as Q,id as R,ad as S,mt as T,_s as U,qs as V,wt as W,zo as X,si as Y,Tl as Z,Nl as _,Ol as $,Dl as aa,Ml as ba,ai as ca,di as da,El as ea,jl as fa,Cl as ga,Fl as ha,Ul as ia,Hl as ja,Bl as ka,Kl as la,ql as ma,Gl as na,zl as oa,Jl as pa,Yl as qa,Vl as ra,Ql as sa,gi as ta,Zl as ua,Xl as va,eu as wa,tu as xa,mr as ya,du as za,lu as Aa,uu as Ba,cu as Ca,pu as Da,kr as Ea,hu as Fa};
42
- //# sourceMappingURL=chunk-FRYEUVYD.js.map
42
+ //# sourceMappingURL=chunk-BRUKO65H.js.map
@@ -1,4 +1,4 @@
1
- import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-5QXRGX2F.js";import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{y as C,z as K}from"./chunk-Y6KR7NXL.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-TFXDHVHP.js";import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{y as C,z as K}from"./chunk-E7GOYIL7.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-ABMDDRZL.js.map
105
+ //# sourceMappingURL=chunk-CA7ZDUGT.js.map
@@ -1,4 +1,4 @@
1
- import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-FRYEUVYD.js";import{b as co}from"./chunk-MEFPXHQJ.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as oo}from"./chunk-IH65GDJR.js";import{b as lo,d as Wn,e as po,f as st,i as mo}from"./chunk-NW7B53KD.js";import{a as Hn,b as uo}from"./chunk-J3SOEFRE.js";import{a as jn,b as go}from"./chunk-SIU6STB2.js";import{e as fo,i as ho,j as yo,k as wo}from"./chunk-X5C5W3E4.js";import{d as bo}from"./chunk-KWWBDLE6.js";import{f as xo,g as So}from"./chunk-HVMUYEQP.js";import{h as so,i as ro}from"./chunk-BE64IJWM.js";import{a as Ur,c as Fr}from"./chunk-MYVHVJWZ.js";import{a as Hr,b as jr,c as Wr,d as qr,l as Jr,q as zr}from"./chunk-74MHOALB.js";import{a as Gr,b as Kr}from"./chunk-LY4G7PCW.js";import{a as Qr,b as Zr}from"./chunk-DPG6VHPX.js";import{c as Xr}from"./chunk-BERWTVG2.js";import{a as Yr,b as Un}from"./chunk-A7JSRDJL.js";import{d as Vr}from"./chunk-Z5CMA4JN.js";import{b as no}from"./chunk-JMRFYGET.js";import{g as eo,h as to}from"./chunk-5QXRGX2F.js";import{c as br,d as xr}from"./chunk-AHWWJ7AF.js";import{c as Or,f as Lr}from"./chunk-JD5TCX4X.js";import{s as Er,v as Bt,w as Dr,y as Ie,z as Bn}from"./chunk-Y6KR7NXL.js";import{a as nt,b as He,f as Nt}from"./chunk-72SZI2UW.js";import{a as Fe,b as Dn}from"./chunk-FCPTN6NF.js";import{d as Br}from"./chunk-7IW25T4K.js";import{e as je,h as Nr,i as Ee}from"./chunk-QUFIUXMQ.js";import{e as Pe}from"./chunk-DSYKYZMT.js";import{Ba as vr,Cb as $r,Cc as Yc,Ea as Jc,Hb as Xc,Nb as Cr,Ob as Lt,Pb as Mr,Qb as tt,Rb as Rr,Sb as _r,Yb as Pr,ub as Ar,xb as Nn,zb as Qc}from"./chunk-VOVDWFFP.js";import{f as kr,g as et,h as Kc}from"./chunk-KEUW6YLL.js";import{j as Ln,r as zc}from"./chunk-N47Y5ADQ.js";import{a as Sr,b as fe,c as Tr,d as Ir,e as On}from"./chunk-VQRY4IDI.js";var Zc="[agentx:mid-turn",Wo="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",qo="Got it, I passed that on to the work in progress.";function qt(n,e,t){return`${n}\0${e}\0${t}`}var Vc=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function eu(n){return!!n&&!Vc.has(n)}function Go(n,e){return!eu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Wt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function tu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Zc} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
1
+ import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-BRUKO65H.js";import{b as co}from"./chunk-MEFPXHQJ.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as oo}from"./chunk-IH65GDJR.js";import{b as lo,d as Wn,e as po,f as st,i as mo}from"./chunk-X6TKWUY2.js";import{a as Hn,b as uo}from"./chunk-J3SOEFRE.js";import{a as jn,b as go}from"./chunk-SIU6STB2.js";import{e as fo,i as ho,j as yo,k as wo}from"./chunk-X5C5W3E4.js";import{d as bo}from"./chunk-KWWBDLE6.js";import{f as xo,g as So}from"./chunk-HVMUYEQP.js";import{h as so,i as ro}from"./chunk-BE64IJWM.js";import{a as Ur,c as Fr}from"./chunk-MYVHVJWZ.js";import{a as Hr,b as jr,c as Wr,d as qr,l as Jr,q as zr}from"./chunk-74MHOALB.js";import{a as Gr,b as Kr}from"./chunk-LY4G7PCW.js";import{a as Qr,b as Zr}from"./chunk-DPG6VHPX.js";import{c as Xr}from"./chunk-BERWTVG2.js";import{a as Yr,b as Un}from"./chunk-A7JSRDJL.js";import{d as Vr}from"./chunk-Z5CMA4JN.js";import{b as no}from"./chunk-HGKDI24R.js";import{g as eo,h as to}from"./chunk-TFXDHVHP.js";import{c as br,d as xr}from"./chunk-AHWWJ7AF.js";import{c as Or,f as Lr}from"./chunk-P5ZGTHJO.js";import{s as Er,v as Bt,w as Dr,y as Ie,z as Bn}from"./chunk-E7GOYIL7.js";import{a as nt,b as He,f as Nt}from"./chunk-72SZI2UW.js";import{a as Fe,b as Dn}from"./chunk-FCPTN6NF.js";import{d as Br}from"./chunk-7IW25T4K.js";import{e as je,h as Nr,i as Ee}from"./chunk-QUFIUXMQ.js";import{e as Pe}from"./chunk-DSYKYZMT.js";import{Ba as vr,Cb as $r,Cc as Yc,Ea as Jc,Hb as Xc,Nb as Cr,Ob as Lt,Pb as Mr,Qb as tt,Rb as Rr,Sb as _r,Yb as Pr,ub as Ar,xb as Nn,zb as Qc}from"./chunk-AVJ4RR2R.js";import{f as kr,g as et,h as Kc}from"./chunk-KEUW6YLL.js";import{j as Ln,r as zc}from"./chunk-N47Y5ADQ.js";import{a as Sr,b as fe,c as Tr,d as Ir,e as On}from"./chunk-VQRY4IDI.js";var Zc="[agentx:mid-turn",Wo="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",qo="Got it, I passed that on to the work in progress.";function qt(n,e,t){return`${n}\0${e}\0${t}`}var Vc=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function eu(n){return!!n&&!Vc.has(n)}function Go(n,e){return!eu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Wt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function tu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Zc} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
2
2
  `)}function pf(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:tu(n)}}):""}Bn();Nt();var Gt="tool-set",Ko=["answer","code","full"],Jo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},nu=.1;function Qo(n){return{task:zo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:zo(n.agentPrompt,600)}:{}}}var Xo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Yo(n,e=nu){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Gn(s.answer),o=Gn(s.code),i=Gn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Zo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Jo.answer.includes(t))?"answer":e.every(t=>Jo.code.includes(t))?"code":"full"}function Vo(n,e){return Ko.indexOf(n)<Ko.indexOf(e)}function Gn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function zo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ei=!1;function ti(n,e){let t=Bt(Gt);if(t!=="off")return t==="active"&&!ei&&(ei=!0,e(`[decisions] seat "${Gt}" is set to active, but only shadow is built: it records and changes nothing`)),Ie(Gt,Qo(n),Xo,{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=Yo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function ni(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Zo(r);Dr(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}`+(Vo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function su(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function si(n,e){let t=su(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 Kn(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)`}Bn();Nt();var ri="session-continuity",oi={continues:nt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:nt("Does the new request refer to something stated earlier in the conversation?")};function ii(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Jn(n.message,1200),previousRequest:n.previousMessage?Jn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Jn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function ai(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 Jn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function di(n,e){let t=Br(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function kf(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=di(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function vf(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:di(n,e).token}var ci=null;function Af(n){ci=n}function Kt(n,e){let t;try{t=ci?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as en}from"execa";import{spawn as ru}from"node:child_process";import{createHash as ou}from"node:crypto";import{createInterface as iu}from"node:readline";var ke=class extends Error{},au=n=>ru("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),zn=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(),iu({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)+`
3
3
  `)}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()}},Qn=class{constructor(e=au,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=ou("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[P])=>x.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ke("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,P])=>!P.connection.busy);if(!x)throw new ke("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new zn(e,this.launchProcess)}}catch{throw new ke("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),I=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(I),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((w,_)=>{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"?w():_(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(x){if(i.close(),!a&&!e.signal?.aborted)throw new ke(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(I),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())}}},ui=new Qn;import{execFile as Mu}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as Ci,readFileSync as Mi,rmSync as Ri}from"fs";import{join as Zt}from"path";import{tmpdir as _i}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 zt(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 De=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 li=null;function rt(){return li}function Of(n){li=n}function he(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function du(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},gi=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=he(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=du(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new qe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new qe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=he(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=he(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,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 cu}from"child_process";import{randomUUID as uu}from"crypto";import{existsSync as lu,readFileSync as gu}from"fs";import{resolve as pu}from"path";function mu(n){let e=pu(n,"CLAUDE.md");if(!lu(e))return null;try{let t=gu(e,"utf8");return zr(t)}catch{return null}}var fu=20*60*1e3,hu=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function yu(n,e){return n.AGENTX_AGENT_ID=e.agentId,Kt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var pi=class{constructor(e={}){this.opts=e}spawn(e,t){return new Xn(e,t,this.opts)}},Xn=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=cu(r,o,{cwd:t.workspace,env:Ee(yu({...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:mu(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 De;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=uu(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
4
4
  `);let c=e.deadlineMs??fu,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new ot(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},hu);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(`
@@ -32,7 +32,7 @@ ${n}`}function _u(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
32
32
  `,l)}};w.stdout?.on("data",v=>{L+=j.write(v);let S=L.split(`
33
33
  `);L=S.pop()||"";for(let B of S)J(B)}),w.stderr?.on("data",v=>{N+=q.write(v)});let $=await w;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=vi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return I=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(P?.message||"")?vi():P?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(I)}}async function ju(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ve(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 Wu(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 I=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(I))}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 I=n.provider||"claude-code",x=s?`${s}
34
34
 
35
- ${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-DXKDG4DQ.js"),$="",v,S,B,W;for await(let E of J(M)){if(c)try{c(E)}catch{}if(E.type==="text_delta")$+=E.text,r(E.text,$);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}v=E.result.tokensUsed,E.result.inputTokens!=null&&(S=E.result.inputTokens),E.result.outputTokens!=null&&(B=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}E.result.tokensUsed!=null&&(v=E.result.tokensUsed)}else E.type==="error"&&(W=E.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-DXKDG4DQ.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(I){return p?y():I?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${I.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var qu=1e3;async function Gu(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"}),qu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=ut(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&ts(e.agentId,n,e.model,s,"persistent");let h=ve(n,e,t),y="",I,x,P,U,w,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
35
+ ${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-2JGSQ4NM.js"),$="",v,S,B,W;for await(let E of J(M)){if(c)try{c(E)}catch{}if(E.type==="text_delta")$+=E.text,r(E.text,$);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}v=E.result.tokensUsed,E.result.inputTokens!=null&&(S=E.result.inputTokens),E.result.outputTokens!=null&&(B=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}E.result.tokensUsed!=null&&(v=E.result.tokensUsed)}else E.type==="error"&&(W=E.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-2JGSQ4NM.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(I){return p?y():I?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${I.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var qu=1e3;async function Gu(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"}),qu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=ut(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&ts(e.agentId,n,e.model,s,"persistent");let h=ve(n,e,t),y="",I,x,P,U,w,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
36
36
  `)?`
37
37
 
38
38
  ${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");I=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(P={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(w=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Qt(S.modelUsage)||_}}}catch($){if(j)I="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)I=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);I=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);I=v.error,x=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!I&&(I="task cancelled by operator",x="cancelled"),{content:j?"":y,error:I,errorKind:x,duration:Date.now()-c,usage:P,contextTokens:U,numTurns:w,billedModel:_,claudeSessionId:R}}function Hi(n){let e=fe(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?wi(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Ii(t.args,n.taskId,n.agentId)}function Ju(n){return fe(n.autonomy)||!!n.personLimits}async function zu(n,e,t,s,r,o,i){let a=fe(e.autonomy)?e.autonomy:void 0,c=a&&bi(a,n.tier)||e.personLimits&&ki(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?`${Ir(a)}
@@ -170,7 +170,7 @@ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt
170
170
  ${e.message}`),e.queuedAt=void 0}let P=la({message:e.message,home:e.context?.home}),U=ua(d.runningTasks,P,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});U&&(this.log(`[${e.agentId}] ${U.slice(0,160)}`),e.message=`${U}
171
171
  ${e.message}`),d.totalTasks++,d.lastActive=new Date;let w={...P.length?{homes:P}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(w),e.runningTaskId=w.id;let _=Lt(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(w.id,e.context??{}),e.onStart)try{e.onStart(w.id)}catch{}let R=new AbortController;this.taskAborts.set(w.id,{agentId:e.agentId,channel:w.channel,chatId:typeof w.chatId=="string"?w.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:st()?.rootId,workflowRunId:e.workflowRunId??(typeof w.chatId=="string"&&w.chatId.startsWith("workflow:")&&w.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(w.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>fc&&(M.buffer=M.buffer.slice(M.buffer.length-fc));for(let m of M.subscribers)try{m(g)}catch{}}},N=Fe();e.taskId=N,w.traceId=N;let j=this.taskAborts.get(w.id);j&&(j.traceId=N);let q=new Map,J=(g,m,k)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:k,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},$=0,v=!1,S=()=>{v||(v=!0,$&&J("first-event",$,"ok"))},B;if(t){let g=lf();B=m=>{S();let k=g(m);if(k&&L(k),wc(N,e.agentId,m),yc(q,m),hs(m,void 0,e.model||d.def.model),fs(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(S(),wc(N,e.agentId,g),yc(q,g),hs(g,void 0,e.model||d.def.model),fs(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;E?.unref?.();let Q=(d.def.preSpawnTimeoutSec??tf)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${w.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},O=()=>`task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Be(R.signal).message;/^timed out/.test(g)&&(te=w.step??"start"),this.log(`[${e.agentId}] task ${w.id} aborted in step "${w.step??"start"}" \u2014 ${g} ${O()}`)},{once:!0});let ne=g=>{w.step=g,this.log(`[${e.agentId}] step ${g} ${O()}`)},le=(g,m,k=0)=>{if(R.signal.aborted)return Promise.reject(Be(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),$=Date.now());let A=Date.now(),H=Cd(m(),zm[g]??0,g);return $d(H,R.signal,k).then(K=>(J(g,A,"ok"),K),K=>{throw J(g,A,"error"),K instanceof Qe&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${O()}`),K})},Tt=async(g,m,k,A=0)=>{try{return await le(g,m,A)}catch(H){if(H instanceof Qe)return k();throw H}},Bs=!1,In=!1,Us=g=>{if(!(!Bs||In)){In=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-w.startedAt.getTime(),error:g?.error||(R.signal.aborted?Be(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(w.id)?!0:void 0,stopped:!this.interruptedRuns.has(w.id)&&(this.stoppedRuns.has(w.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Fs=!1,Hs=g=>{if(Fs)return;Fs=!0,Us(g),this.runReleases.delete(w.id),E&&clearTimeout(E),oe(),d.activeTasks--,this.admissionTickets.get(e)?.release();let m=d.runningTasks.findIndex(A=>A.id===w.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(w.id),this.taskAborts.delete(w.id);let k=this.runEndWaiters.get(w.id);this.runEndWaiters.delete(w.id);for(let A of k??[])try{A()}catch{}M.done=!0,M.endedAt=new Date;for(let A of M.subscribers)try{A(`
172
172
  [task finished]
173
- `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(w.id),Vm).unref?.();try{let A=M.endedAt,H={id:w.id,agentId:e.agentId,channel:w.channel,chatId:w.chatId,sender:w.sender,message:e.message||"",startedAt:w.startedAt.toISOString(),endedAt:A.toISOString(),durationMs:A.getTime()-w.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(w.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(H);let K=(H.responseText||H.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:A,ok:H.ok})}}catch(A){this.log(`[${e.agentId}] task history persist failed: ${A?.message}`)}this.midTurn.endChat(qt(e.agentId,u,l)),this.messageQueue.markDone(e.agentId,u,l).then(A=>{if(A.length===0)return;this.log(`[${e.agentId}] flushing ${A.length} queued message(s) after task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`);let H=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:H,count:A.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:H,at:new Date().toISOString()});for(let X of A){let Re=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Re,queuedAt:X.queuedAt??X.timestamp}).then(Se=>(We(Se.error)||K(),this.postQueuedResponseToChannel(e.agentId,Re,Se)),Se=>{throw K(),Se}).catch(Se=>{this.log(`[${e.agentId}] queued message failed: ${Se.message}`)})}}).catch(A=>{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: ${A.message}`)})};this.runReleases.set(w.id,Hs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let b=e.context?.channel||"api",{evaluateRequest:Sc,selectRequestContext:Tc}=await import("./request-planner-SDO5MNFV.js"),js=Tt("request-gate",()=>Sc(e.message,e.agentId,b),()=>({active:!1,preprocess:!1})),kn=!1;js.then(()=>{kn=!0},()=>{kn=!0});let T=l,vn=e.context?.sender||"User",de=d.def.tier==="codex-cli",Ze=Za(this.config.session,b,d.def.tier),It=Va(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,b,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${b}:${T}`),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}));let kt=this.sessions.sessionIdleMs(e.agentId,b,T);e.freshSession||await Tt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,b,T,e.seedHistory),()=>{});let Ic=[...this.sessions.getSession(e.agentId,b,T).messages].reverse().find(g=>g.role==="agent")?.content;vd({agent:e.agentId,channel:b,chatId:T,message:e.message,previousReply:Ic,taskId:N}),this.sessions.addUserMessage(e.agentId,b,T,vn,e.message);let Ws=Date.now(),qs={agentId:e.agentId,channel:b,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ws).toISOString(),taskId:N,resumeOrigin:na(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Nn(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Ar(e.context),operator:$r(e.context),dueAt:Ad(e.context),taskType:yn(e.context)};V().emit("task:started",qs),Bs=!0;let ee,An,Gs=this.classifier;if(Gs&&b!=="a2a"&&!de){ne("classify");let g=Date.now();An=Gs.classify({text:e.message,channel:b,sender:e.context?.sender,chatId:T,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(w.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 Ks=async g=>{if(!An)return;let m;await Promise.race([An,new Promise(k=>{m=setTimeout(k,g),m.unref?.()})]),m&&clearTimeout(m)};await Ks(jm);let $e=this.config.workflows?.matching,xe,Js,zs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&zs?.enabled&&(zs.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=($e?.suggestThreshold??.65)&&(Js=Mo(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&$e?.enabled&&!i)try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${$e.mode} reasons=${m.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&m.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?xe={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 Ce=Ro(this.config.workflows,e.agentId)&&_o(e)?this.workflowRuns:void 0;if(Ce&&!xe&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list()),k=$e?.autoRunThreshold??.85;m&&m.confidence>=k&&(xe={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ce?Jm():void 0,kc=ce?Po(ce):void 0,$n=this.wikiHub.getAgentWiki(e.agentId),Qs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Xs=this.memoryStore.buildContext(Qs),Ys=this.memoryStore.contextFacts(Qs),vc=this.patternStore.findRelevant(e.message,e.agentId,5),Ac=this.patternStore.buildContext(vc),Zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),k=await le("skills",()=>g(d.def.workspace)),A=e.personLimits?.skills??[],H=A.length?k.filter(K=>!A.some(X=>tt(X,K.frontmatter.name))):k;Zs=m(H,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,b,T):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,b,T):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,b,T):void 0;if(F&&this.sessions.isSessionStale(e.agentId,b,T,kt)&&(this.log(`[${e.agentId}] session stale for ${b}:${T}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,b,T)){let g=this.sessions.getLastTurnContextTokens(e.agentId,b,T);this.log(`[${e.agentId}] tier-2 rotation for ${b}:${T} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(b)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,b,T)){let g=this.sessions.getTurnCount(e.agentId,b,T);this.log(`[${e.agentId}] max-turns rotation for ${b}:${T} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=si({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,b,T),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,b,T),idleMs:kt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${b}:${T}: ${Kn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,b,T);this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${b}:${T}: would ${Kn(m)}`)}}if(F&&d.def.tier==="claude-code"){let g=F;await Tt("rotate",()=>this.maybeRotateForContinuity(e,d,b,T,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,b,T,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${b}:${T} (quality: ${m}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let A=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${A.overallScore} (lexicon=${A.lexiconDecay}, tools=${A.toolShift}, semantic=${A.semanticDrift})`),A.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${A.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let $c=process.env.AGENTX_CONTEXT_SURGERY==="1",Cc=de?{maxMessages:8,maxChars:2400}:$c&&mc(b,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Mc=!F&&!de?df($n,e.agentId,{notesInbox:af(this.config)}):void 0,Vs;if(!F&&!de)try{let g=this.config.wiki?.decisionApprovals?.required===!0,m=xo(So($n,e.agentId),$n.baseDir,g);Vs=bo(m,Date.now())||void 0}catch{}let vt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,b,T,Cc):void 0,Rc=F?void 0:this.sessions.getRotationMemo(e.agentId,b,T)??void 0,er,tr=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new mt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=Ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){er=Ts(m),tr=m.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of m)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Pe&&Pe.cat)try{let m=this.sessions.getSession(e.agentId,b,T).messages,k=m[0],A=m[m.length-1],H=vt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${vt.length}c/${vt.split(`
173
+ `)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(w.id),Vm).unref?.();try{let A=M.endedAt,H={id:w.id,agentId:e.agentId,channel:w.channel,chatId:w.chatId,sender:w.sender,message:e.message||"",startedAt:w.startedAt.toISOString(),endedAt:A.toISOString(),durationMs:A.getTime()-w.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(w.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(H);let K=(H.responseText||H.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:A,ok:H.ok})}}catch(A){this.log(`[${e.agentId}] task history persist failed: ${A?.message}`)}this.midTurn.endChat(qt(e.agentId,u,l)),this.messageQueue.markDone(e.agentId,u,l).then(A=>{if(A.length===0)return;this.log(`[${e.agentId}] flushing ${A.length} queued message(s) after task=${w.id} chat=${u}:${l} at=${new Date().toISOString()}`);let H=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:H,count:A.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:H,at:new Date().toISOString()});for(let X of A){let Re=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Re,queuedAt:X.queuedAt??X.timestamp}).then(Se=>(We(Se.error)||K(),this.postQueuedResponseToChannel(e.agentId,Re,Se)),Se=>{throw K(),Se}).catch(Se=>{this.log(`[${e.agentId}] queued message failed: ${Se.message}`)})}}).catch(A=>{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: ${A.message}`)})};this.runReleases.set(w.id,Hs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let b=e.context?.channel||"api",{evaluateRequest:Sc,selectRequestContext:Tc}=await import("./request-planner-XPPRK5G3.js"),js=Tt("request-gate",()=>Sc(e.message,e.agentId,b),()=>({active:!1,preprocess:!1})),kn=!1;js.then(()=>{kn=!0},()=>{kn=!0});let T=l,vn=e.context?.sender||"User",de=d.def.tier==="codex-cli",Ze=Za(this.config.session,b,d.def.tier),It=Va(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,b,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${b}:${T}`),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}));let kt=this.sessions.sessionIdleMs(e.agentId,b,T);e.freshSession||await Tt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,b,T,e.seedHistory),()=>{});let Ic=[...this.sessions.getSession(e.agentId,b,T).messages].reverse().find(g=>g.role==="agent")?.content;vd({agent:e.agentId,channel:b,chatId:T,message:e.message,previousReply:Ic,taskId:N}),this.sessions.addUserMessage(e.agentId,b,T,vn,e.message);let Ws=Date.now(),qs={agentId:e.agentId,channel:b,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ws).toISOString(),taskId:N,resumeOrigin:na(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Nn(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Ar(e.context),operator:$r(e.context),dueAt:Ad(e.context),taskType:yn(e.context)};V().emit("task:started",qs),Bs=!0;let ee,An,Gs=this.classifier;if(Gs&&b!=="a2a"&&!de){ne("classify");let g=Date.now();An=Gs.classify({text:e.message,channel:b,sender:e.context?.sender,chatId:T,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(w.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 Ks=async g=>{if(!An)return;let m;await Promise.race([An,new Promise(k=>{m=setTimeout(k,g),m.unref?.()})]),m&&clearTimeout(m)};await Ks(jm);let $e=this.config.workflows?.matching,xe,Js,zs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&zs?.enabled&&(zs.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=($e?.suggestThreshold??.65)&&(Js=Mo(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&$e?.enabled&&!i)try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${$e.mode} reasons=${m.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&m.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?xe={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 Ce=Ro(this.config.workflows,e.agentId)&&_o(e)?this.workflowRuns:void 0;if(Ce&&!xe&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ht({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=jt({agentId:e.agentId,channel:b,message:e.message,intentPath:ee?.path},g.list()),k=$e?.autoRunThreshold??.85;m&&m.confidence>=k&&(xe={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ce?Jm():void 0,kc=ce?Po(ce):void 0,$n=this.wikiHub.getAgentWiki(e.agentId),Qs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Xs=this.memoryStore.buildContext(Qs),Ys=this.memoryStore.contextFacts(Qs),vc=this.patternStore.findRelevant(e.message,e.agentId,5),Ac=this.patternStore.buildContext(vc),Zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),k=await le("skills",()=>g(d.def.workspace)),A=e.personLimits?.skills??[],H=A.length?k.filter(K=>!A.some(X=>tt(X,K.frontmatter.name))):k;Zs=m(H,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,b,T):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,b,T):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,b,T):void 0;if(F&&this.sessions.isSessionStale(e.agentId,b,T,kt)&&(this.log(`[${e.agentId}] session stale for ${b}:${T}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,b,T)){let g=this.sessions.getLastTurnContextTokens(e.agentId,b,T);this.log(`[${e.agentId}] tier-2 rotation for ${b}:${T} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(b)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,b,T)){let g=this.sessions.getTurnCount(e.agentId,b,T);this.log(`[${e.agentId}] max-turns rotation for ${b}:${T} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=si({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,b,T),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,b,T),idleMs:kt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${b}:${T}: ${Kn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,b,T,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,b,T);this.sessions.clearClaudeSessionId(e.agentId,b,T),V().emit("session:rotated",{agentId:e.agentId,channel:b,chatId:T,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${b}:${T}: would ${Kn(m)}`)}}if(F&&d.def.tier==="claude-code"){let g=F;await Tt("rotate",()=>this.maybeRotateForContinuity(e,d,b,T,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,b,T,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${b}:${T} (quality: ${m}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let A=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${A.overallScore} (lexicon=${A.lexiconDecay}, tools=${A.toolShift}, semantic=${A.semanticDrift})`),A.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${A.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let $c=process.env.AGENTX_CONTEXT_SURGERY==="1",Cc=de?{maxMessages:8,maxChars:2400}:$c&&mc(b,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Mc=!F&&!de?df($n,e.agentId,{notesInbox:af(this.config)}):void 0,Vs;if(!F&&!de)try{let g=this.config.wiki?.decisionApprovals?.required===!0,m=xo(So($n,e.agentId),$n.baseDir,g);Vs=bo(m,Date.now())||void 0}catch{}let vt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,b,T,Cc):void 0,Rc=F?void 0:this.sessions.getRotationMemo(e.agentId,b,T)??void 0,er,tr=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new mt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=Ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){er=Ts(m),tr=m.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of m)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Pe&&Pe.cat)try{let m=this.sessions.getSession(e.agentId,b,T).messages,k=m[0],A=m[m.length-1],H=vt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${vt.length}c/${vt.split(`
174
174
  `).length}L`,K=`[${e.agentId}] ${b}:${T} ${H} | session.messages=${m.length}`+(m.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${A.timestamp.slice(11,19)}(${A.role}:${(A.content||"").slice(0,40).replace(/\n/g," ")})`:"");Pe.cat("context",K)}catch(g){Pe.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let nr;if(d.def.contextReferences&&!F)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[A,H]=await le("references",()=>Promise.all([Hn(d.def.workspace),jn(d.def.workspace)]));if(A.byId.size===0&&H.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Hn(process.cwd()),jn(process.cwd())]));m={refs:K,recipes:X}}else m={refs:A,recipes:H};this.referencesCache.set(g,m)}let k=go({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);k.cards.length>0&&(nr=uo(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let sr=ge||Ve?"":this.sessions.getCrossSessionSummary(e.agentId,b,T,e.message),rr,At=ge?null:Gi(e.message);if(At)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:b,chatId:T,lookbackDays:At.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${At.lookbackDays}d on this chat (cue-triggered)]`],k=[...g.turns].sort((A,H)=>A.ts.localeCompare(H.ts));for(let A of k){let H=A.ts.slice(11,16)+" "+A.day,K=A.role==="user"?A.senderName||"User":A.senderName||"Agent";m.push(`${H} ${K}: ${A.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]"),rr=m.join(`
175
175
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${At.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let _c=de?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",or,ir,ar=!1;kn||ne("request-gate");let Me=await js;if(Me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),_c==="planner"&&!ge&&!Me.active&&!Ve&&b!=="voice"&&b!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:b,chatId:T,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(ar=!0,or=m.sessionHistory,Xs=m.memoryContext,Ys=m.memoryFacts,sr=m.crossChatContext,ir=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)`)}ar&&F&&(this.sessions.clearClaudeSessionId(e.agentId,b,T),F=void 0)}let Cn=`${e.agentId}:${b}:${T}`,$t=Wr(e.message);$t&&($t==="default"?(this.activeSouls.delete(Cn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Cn,$t),this.log(`[${e.agentId}] Soul switched to: ${$t}`)));let Pc=this.activeSouls.get(Cn),Ec=Hr(d.def.workspace,Pc),Dc=jr(Ec),Oc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Lc=Ym(d.def.tier),Nc=gf(d.def.richMessages,e.context?.via==="voice"?"voice":b),Bc=d.def.tier==="claude-code"&&(ge||Ze!=="lean"||ed(It)),dr="";if(d.def.workspace&&!Bc){let g=G(d.def.workspace,"CLAUDE.md");if(ae(g))try{let m=xt(g,"utf-8");dr=`[Project CLAUDE.md]
176
176
  ${m.length>4e3?m.slice(0,4e3)+`
@@ -184,9 +184,9 @@ ${Re}`),m+=Re.length}catch{}}}let Uc=Mn.length>0?Mn.join(`
184
184
 
185
185
  `)||void 0,Mt={channel:b,chatId:T,channelScope:e.context?.group?"group":b==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,b),systemPrompt:d.def.systemPrompt,sender:vn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ve||mc(b,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:de?void 0:Ac||void 0,procedureContext:[er,Js].filter(Boolean).join(`
186
186
 
187
- `)||void 0,workflowRunContext:kc,references:nr,skillInjection:Zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:or??vt,memoryContext:Xs||void 0,crossChatContext:sr||void 0,longMemoryRecall:rr||void 0,contextOnDemand:Ve&&!F?id(b,T):void 0,wikiContext:Mc,handoverNote:this.buildHandoverNote(e.agentId,b,T),watcherNote:(()=>{try{return this.runNote?.(qs)}catch{return}})(),rotationMemo:Rc,ownerDecisions:Vs,eventDigest:F?void 0:of(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Ho(b,!F,d.def.richMessages);return g?cf(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(Mt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Rt=e.model?void 0:Lr({tier:d.def.tier,channel:b,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?kt:null});Rt?.downgraded&&this.log(`[${e.agentId}] ${Rt.reason}`);let cr=Or(d.def.tier,this.config.decisions.routing),ur=Rt?.downgraded?Promise.resolve(Rt.model):!e.model&&cr&&(!Me.active||Me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-VDVZ4IYF.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:b,isFollowUp:!!F,sessionIdleMs:F?kt:null,cheapModel:cr}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),lr=!1;ur.then(()=>{lr=!0});let _t=Me.active&&Me.preprocess?await Tt("select-context",()=>Tc(Mt),()=>({input:Mt,excluded:[]})):{input:Mt,excluded:[]};_t.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${_t.excluded.join(", ")}`);let Pt=ta(_t.input,de?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Fc=oo(Pt,{memory:Ys,procedures:tr,wikiContext:_t.input.wikiContext}),_n=(Pt?.length??0)+(Rn?.length??0)+(e.message?.length??0),Et={history:Pt?.length??0,sysPrompt:Rn?.length??0,message:e.message?.length??0},gr=qa(e.agentId,b,T);Ga(gr,_n,Et);let pr=Ka(gr);pr&&this.log(`[${e.agentId}] ${pr}`),_n>16e3&&this.log(`[${e.agentId}] large context for ${b}:${T}: ${_n} bytes (history=${Et.history}, sysPrompt=${Et.sysPrompt}, message=${Et.message})`),lr||ne("route-model");let mr=await ur,fr=d.def.tier!=="claude-code"?void 0:ge?sd():Ze==="lean"?nd(d.def.workspace,It,void 0,b):od(d.def.workspace);Ze==="lean"&&!ge&&!F&&this.log(`[${e.agentId}] session profile for ${b}: ${ad(Ze,It,b)}`);let hr=d.def.tier==="claude-code"&&!F?ti({message:e.message??"",agent:e.agentId,channel:b,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,Hc={...e,systemPromptAppend:Rn,...fr?{claudeArgs:fr}:{},...mr?{model:mr}:{}},se,yr=Td({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),jc=B,wr=!1,Pn=!0;B=g=>{if(yr.observe(g),ce&&Pn)for(let m of Do(g))Eo(m.name,m.input)||(Pn=!1);jc?.(g)};try{let g=this.workflowAutoRunner;if(xe&&g){let D=xe;try{let z=await le("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:b,chatId:T,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:b,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${xe.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:D.follow?`Started the workflow "${z.title??D.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:xe.workflowId,workflowRunId:z.runId,workflowMatchConfidence:xe.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ce)try{let D=Lo(Ce,e.resumedFrom);Oo(Ce,{runId:ce,agentId:e.agentId,channel:b,chatId:T,message:e.message,taskId:N,...D?{continues:D}:{}}),wr=!0,w.workflow={runId:ce,workflowId:Co}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${D?.message||D}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=d.def.persistentProcess?rt():null,z=D!=null&&D.hasLive({agentId:e.agentId,channel:b,chatId:T}),pe=!!F||z,me=[Aa(pe),ja(pe,void 0,e.model||d.def.model)].find(_e=>_e&&_e.abort);if(me){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${me.reason}`);let _e={content:"",error:me.message,errorKind:"dispatch_hold",..."retryAt"in me&&typeof me.retryAt=="number"?{retryAt:me.retryAt}:{},duration:0};if(!t){M.buffer=`[error] ${me.message}`;for(let Gc of M.subscribers)try{Gc(M.buffer)}catch{}}return _e}Da();let ue=Wa();return ue&&this.log(`[${e.agentId}] ${ue}`),null},k=Ft(e.agentId,void 0,Ut(e.agentId,e.context?.chatId));if(k){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){M.buffer=`[error] ${k.message}`;for(let D of M.subscribers)try{D(M.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let A=this.planCloudSession(d.def,e);if(A.route==="local"){let D=m();if(D)return d.errors++,se=D,D}let H=d.def.tier==="claude-code",K=H?t:(D,z)=>{D&&L(D),t&&t(D,z)},X=!1,Re=H?s:D=>{D&&(X?L(D):(L(`\u{1F4AD} ${D}`),X=!0)),s&&s(D)},Se=()=>{X&&(L(`
187
+ `)||void 0,workflowRunContext:kc,references:nr,skillInjection:Zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:or??vt,memoryContext:Xs||void 0,crossChatContext:sr||void 0,longMemoryRecall:rr||void 0,contextOnDemand:Ve&&!F?id(b,T):void 0,wikiContext:Mc,handoverNote:this.buildHandoverNote(e.agentId,b,T),watcherNote:(()=>{try{return this.runNote?.(qs)}catch{return}})(),rotationMemo:Rc,ownerDecisions:Vs,eventDigest:F?void 0:of(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Ho(b,!F,d.def.richMessages);return g?cf(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(Mt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Rt=e.model?void 0:Lr({tier:d.def.tier,channel:b,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?kt:null});Rt?.downgraded&&this.log(`[${e.agentId}] ${Rt.reason}`);let cr=Or(d.def.tier,this.config.decisions.routing),ur=Rt?.downgraded?Promise.resolve(Rt.model):!e.model&&cr&&(!Me.active||Me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-AIHGJNO7.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:b,isFollowUp:!!F,sessionIdleMs:F?kt:null,cheapModel:cr}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),lr=!1;ur.then(()=>{lr=!0});let _t=Me.active&&Me.preprocess?await Tt("select-context",()=>Tc(Mt),()=>({input:Mt,excluded:[]})):{input:Mt,excluded:[]};_t.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${_t.excluded.join(", ")}`);let Pt=ta(_t.input,de?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Fc=oo(Pt,{memory:Ys,procedures:tr,wikiContext:_t.input.wikiContext}),_n=(Pt?.length??0)+(Rn?.length??0)+(e.message?.length??0),Et={history:Pt?.length??0,sysPrompt:Rn?.length??0,message:e.message?.length??0},gr=qa(e.agentId,b,T);Ga(gr,_n,Et);let pr=Ka(gr);pr&&this.log(`[${e.agentId}] ${pr}`),_n>16e3&&this.log(`[${e.agentId}] large context for ${b}:${T}: ${_n} bytes (history=${Et.history}, sysPrompt=${Et.sysPrompt}, message=${Et.message})`),lr||ne("route-model");let mr=await ur,fr=d.def.tier!=="claude-code"?void 0:ge?sd():Ze==="lean"?nd(d.def.workspace,It,void 0,b):od(d.def.workspace);Ze==="lean"&&!ge&&!F&&this.log(`[${e.agentId}] session profile for ${b}: ${ad(Ze,It,b)}`);let hr=d.def.tier==="claude-code"&&!F?ti({message:e.message??"",agent:e.agentId,channel:b,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,Hc={...e,systemPromptAppend:Rn,...fr?{claudeArgs:fr}:{},...mr?{model:mr}:{}},se,yr=Td({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),jc=B,wr=!1,Pn=!0;B=g=>{if(yr.observe(g),ce&&Pn)for(let m of Do(g))Eo(m.name,m.input)||(Pn=!1);jc?.(g)};try{let g=this.workflowAutoRunner;if(xe&&g){let D=xe;try{let z=await le("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:b,chatId:T,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:b,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${xe.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:D.follow?`Started the workflow "${z.title??D.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:xe.workflowId,workflowRunId:z.runId,workflowMatchConfidence:xe.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ce)try{let D=Lo(Ce,e.resumedFrom);Oo(Ce,{runId:ce,agentId:e.agentId,channel:b,chatId:T,message:e.message,taskId:N,...D?{continues:D}:{}}),wr=!0,w.workflow={runId:ce,workflowId:Co}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${D?.message||D}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=d.def.persistentProcess?rt():null,z=D!=null&&D.hasLive({agentId:e.agentId,channel:b,chatId:T}),pe=!!F||z,me=[Aa(pe),ja(pe,void 0,e.model||d.def.model)].find(_e=>_e&&_e.abort);if(me){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${me.reason}`);let _e={content:"",error:me.message,errorKind:"dispatch_hold",..."retryAt"in me&&typeof me.retryAt=="number"?{retryAt:me.retryAt}:{},duration:0};if(!t){M.buffer=`[error] ${me.message}`;for(let Gc of M.subscribers)try{Gc(M.buffer)}catch{}}return _e}Da();let ue=Wa();return ue&&this.log(`[${e.agentId}] ${ue}`),null},k=Ft(e.agentId,void 0,Ut(e.agentId,e.context?.chatId));if(k){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){M.buffer=`[error] ${k.message}`;for(let D of M.subscribers)try{D(M.buffer)}catch{}}return d.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let A=this.planCloudSession(d.def,e);if(A.route==="local"){let D=m();if(D)return d.errors++,se=D,D}let H=d.def.tier==="claude-code",K=H?t:(D,z)=>{D&&L(D),t&&t(D,z)},X=!1,Re=H?s:D=>{D&&(X?L(D):(L(`\u{1F4AD} ${D}`),X=!0)),s&&s(D)},Se=()=>{X&&(L(`
188
188
  `),X=!1)},Wc=H?K:K?(D,z)=>{Se(),K(D,z)}:void 0,C=await le("agent",async()=>{if(A.route!=="local"){let z=await this.runCloudSession(d.def,e,A,N);if(z)return z;let pe=m();if(pe)return pe}let D=await this.inTaskWorktree(d.def,Hc);return ji(D.def,D.task,this.providers,Wc,Pt,D.fresh?void 0:F,B,R.signal,Re)},ef);if(!C.error){let D=uf(d.def.toolUseRequired,q);if(D){let z=Array.from(q.entries()).map(([pe,Ue])=>`${pe}=${Ue}`).join(", ")||"none";C.error=`tool_required_not_called: ${D} (invoked: ${z})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${z}`)}}hr&&ni(hr,{toolUses:q,eventsSeen:v,error:C.error,agentId:e.agentId},D=>this.log(D));let Dt=this.interruptedRuns.get(w.id);Dt&&(C.content="",C.error=Dt,C.errorKind="interrupted");let En=Dt?void 0:this.stoppedRuns.get(w.id);En&&(C.content="",C.error=En,C.errorKind="stopped"),se=C;let Te=C.usage?so(C.usage):void 0,qc=C.billedModel||e.model||d.def.model||void 0,Ot=C.costUsd??(C.usage?this.tokenTracker.runCost(C.usage,qc,d.def.tier):void 0);if(In=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:b,chatId:T,durationMs:Date.now()-Ws,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Dt?!0:void 0,stopped:En?!0:void 0,inputTokens:Te?.inputTokens,outputTokens:Te?.outputTokens,cacheReadTokens:Te?.cacheReadTokens,cacheCreateTokens:Te?.cacheCreateTokens,tier2InputTokens:Te?.tier2InputTokens,tier2OutputTokens:Te?.tier2OutputTokens,tier2CacheReadTokens:Te?.tier2CacheReadTokens,tier2CacheCreateTokens:Te?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:Me.arm,numTurns:C.numTurns,costUsd:Ot!==void 0&&Number.isFinite(Ot)&&Ot>0?Ot:void 0,injectedContext:Fc,finalResponse:C.content||void 0,billedModel:C.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let D=C.error?`[error] ${C.error}`:C.content;M.buffer=D;for(let z of M.subscribers)try{z(D)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,b,T,C.content),kd({agent:e.agentId,channel:b,chatId:T,request:e.message,reply:C.content,taskId:N}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,b,T,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,b,T,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,b,T,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,b,T,C.usage,C.contextTokens),C.usage){let ue=C.contextTokens,_e=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(ue??_e)>=this.sessions.getTierTwoThresholdTokens(b)&&this.log(`[${e.agentId}] TIER-2 HIT on ${b}:${T}: context=${ue??"n/a"} tokens (cumulative turn total=${_e}) \u2014 next turn will rotate`)}let D=Qr({channel:b,content:`User: ${e.message}`,responseLength:C.content.length}),z=G(this.wikiHub.getBaseDir(),zi);D.capture||Qi(z,e.agentId,D,ue=>this.log(ue)),D.capture&&(await Ks(Wm),Xi(z,e.agentId,()=>{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:b,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
189
189
 
190
190
  Agent: ${C.content}`,meta:rf(ee,e.context)})},ue=>this.log(ue)),Zr(e.agentId,e.message,C.content,{channel:b,chatId:T,sender:vn},this.memoryStore).catch(()=>{}),fa(e.agentId,e.message,C.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Ue=e.context?.channel,me=Ue&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ue}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,pe,Ue,me),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${O()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Jt(g.message);return se={content:"",error:zt(m),errorKind:m.kind},se}finally{if(yr.stop(),wr&&ce&&Ce)try{let g=se?.usage,m=No(Ce,ce,{error:se?se.error||void 0:R.signal.aborted?Be(R.signal).message:"run ended before completion",canceled:Bo(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Pn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Us(se),Hs(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?Zm(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:Uo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||qm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Km(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Ye,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of be(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 I=Math.floor((s-y)/36e5),x=t-1-I;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of be(e)){let r=G(e,s),o;try{o=be(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=be(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(xt(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=sf){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of be(t)){let i=G(t,o),a;try{a=be(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Gm(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=be(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=be(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(xt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=be(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(xt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Ut(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=qn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){Qm.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=ut(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}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!Go(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(c=>c.channel===s&&c.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(qt(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(qt(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId: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:Cr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function gf(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(`
191
191
  `)}export{pf as a,di as b,kf as c,vf as d,Af as e,ui as f,Of as g,gi as h,mu as i,pi as j,Xt as k,Xf as l,eh as m,th as n,ih as o,ut as p,Lu as q,Ui as r,Hu as s,ju as t,Wu as u,ji as v,sn as w,zi as x,Bh as y,rn as z,pl as A,Wh as B,qh as C,Kh as D,an as E,Sl as F,Qh as G,cs as H,V as I,Sa as J,Fl as K,ql as L,ka as M,my as N,va as O,Pa as P,Cy as Q,My as R,Ba as S,Ry as T,Ua as U,pn as V,Uy as W,Fy as X,mt as Y,tp as Z,np as _,sp as $,rp as aa,op as ba,Ss as ca,yn as da,hw as ea,bn as fa,wn as ga,Ed as ha,ht as ia,Dd as ja,Iw as ka,kw as la,vw as ma,Aw as na,$w as oa,Cw as pa,Mw as qa,Np as ra,Kd as sa,Xe as ta,ic as ua,Ls as va,Ww as wa,Gw as xa,Kw as ya,Xm as za,Ym as Aa,kx as Ba,vx as Ca,Zm as Da,nf as Ea,rf as Fa,of as Ga,df as Ha,Ns as Ia,hc as Ja,yc as Ka,uf as La,wc as Ma,bc as Na,gf as Oa};
192
- //# sourceMappingURL=chunk-575LJSX2.js.map
192
+ //# sourceMappingURL=chunk-CJ3FDM2O.js.map
@@ -1,4 +1,4 @@
1
- import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Bc as tt,Cc as nt}from"./chunk-VOVDWFFP.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Bc as tt,Cc as nt}from"./chunk-AVJ4RR2R.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
- //# sourceMappingURL=chunk-Y6KR7NXL.js.map
114
+ //# sourceMappingURL=chunk-E7GOYIL7.js.map
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-ABMDDRZL.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-CA7ZDUGT.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
249
249
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
250
250
  Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
251
251
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
252
- //# sourceMappingURL=chunk-XC3466Z4.js.map
252
+ //# sourceMappingURL=chunk-EUNCDWTP.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,r=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await ne.readFile(r,"utf8"),l=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await ne.writeFile(r,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${l.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-Q3H6QR6Q.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-PGYJ4FRA.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,r=t;return o?.length&&(r+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function Oe(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:p=!1,dryRun:c=!1,onProgress:d,abortSignal:u}=n,m=u?{...r,abortSignal:u}:r;if(!e.generateRaw)return mt(n);let I=new se(s,{interactive:a,overwrite:p,dryRun:c,acmeContext:n.acmeContext,abortSignal:u}),D=be(l);if(n.acmeContext)for(let g of ct)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(n.mcpTools?.length)for(let g of n.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,O=0,A="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),k.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let S=null,H=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?S=x.result:x.type==="error"&&(H=x.error);if(H&&!S)throw new Error(H);if(!S)throw new Error("generateRawStream returned no raw_result event");g=S,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(S){if(S.message?.includes("not available"))return mt(n);throw S}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,O+=g.usage.output_tokens;let P=g._streamedText;for(let S of g.content)S.type==="text"&&(A+=S.text,P===void 0&&d?.({type:"text_delta",text:S.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let S=g.content.filter(v=>v.type==="tool_use");if(S.length===0)break;C.push({role:"assistant",content:g.content});let H=[];for(let v of S){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),k.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&n.mcpDispatch){let h=await n.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),H.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:H}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:A,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:O||void 0,iterations:_}}async function mt(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,maxIterations:s=5}=n,l=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${n.projectInstructions}`),n.memoryContext&&o.push(n.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{We as a,Xt as b,Qt as c,Je as d,Ke as e,Xe as f,Qe as g,Pe as h,ee as i,Re as j,ce as k,te as l,Pt as m,oe as n,Et as o,f as p,ot as q,rt as r,Me as s,de as t,W as u,re as v,lt as w,Ee as x,$e as y,se as z,gt as A,tn as B,on as C};
126
- //# sourceMappingURL=chunk-LO5A3VKY.js.map
126
+ //# sourceMappingURL=chunk-GR6BSPIQ.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-5QXRGX2F.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-Y6KR7NXL.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-TFXDHVHP.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-E7GOYIL7.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-ZVRI3GFZ.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-6EJJKOMW.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-YNYDIHQF.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-GZEWEPH5.js.map