agentix-cli 0.124.0 → 0.125.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 (33) hide show
  1. package/dist/{agent-W7UNXO6L.js → agent-IQV3P3CK.js} +2 -2
  2. package/dist/{board-dashboard-3AOENRSG.js → board-dashboard-H5CKFP4E.js} +2 -2
  3. package/dist/{chunk-46ACP7A7.js → chunk-326G2KKL.js} +2 -2
  4. package/dist/{chunk-K5QUQNFE.js → chunk-44A5JGRM.js} +2 -2
  5. package/dist/{chunk-6HKLRU62.js → chunk-LB4ZIQX3.js} +2 -2
  6. package/dist/chunk-NW7RVE57.js +49 -0
  7. package/dist/chunk-NW7RVE57.js.map +1 -0
  8. package/dist/{chunk-B3B7KEHJ.js → chunk-ZCUIBKKI.js} +17 -17
  9. package/dist/{chunk-B3B7KEHJ.js.map → chunk-ZCUIBKKI.js.map} +1 -1
  10. package/dist/{chunk-PAM56O25.js → chunk-ZTHSA7H3.js} +4 -4
  11. package/dist/cli.js +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/{program-EJWE7NVT.js → program-J2X6TR34.js} +255 -240
  14. package/dist/program-J2X6TR34.js.map +1 -0
  15. package/dist/{promote-DPPNEINZ.js → promote-W2BSSTRI.js} +2 -2
  16. package/dist/query-RV6SHTRN.js +2 -0
  17. package/dist/{registry-UBVBEEDW.js → registry-5PMZ3ZCT.js} +2 -2
  18. package/dist/{wiki-ZZ3MU5Y5.js → wiki-VP4LSMR5.js} +2 -2
  19. package/package.json +1 -1
  20. package/dist/chunk-YL4C63S2.js +0 -49
  21. package/dist/chunk-YL4C63S2.js.map +0 -1
  22. package/dist/program-EJWE7NVT.js.map +0 -1
  23. package/dist/query-SLUOL6MQ.js +0 -2
  24. /package/dist/{agent-W7UNXO6L.js.map → agent-IQV3P3CK.js.map} +0 -0
  25. /package/dist/{board-dashboard-3AOENRSG.js.map → board-dashboard-H5CKFP4E.js.map} +0 -0
  26. /package/dist/{chunk-46ACP7A7.js.map → chunk-326G2KKL.js.map} +0 -0
  27. /package/dist/{chunk-K5QUQNFE.js.map → chunk-44A5JGRM.js.map} +0 -0
  28. /package/dist/{chunk-6HKLRU62.js.map → chunk-LB4ZIQX3.js.map} +0 -0
  29. /package/dist/{chunk-PAM56O25.js.map → chunk-ZTHSA7H3.js.map} +0 -0
  30. /package/dist/{promote-DPPNEINZ.js.map → promote-W2BSSTRI.js.map} +0 -0
  31. /package/dist/{query-SLUOL6MQ.js.map → query-RV6SHTRN.js.map} +0 -0
  32. /package/dist/{registry-UBVBEEDW.js.map → registry-5PMZ3ZCT.js.map} +0 -0
  33. /package/dist/{wiki-ZZ3MU5Y5.js.map → wiki-VP4LSMR5.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{A as a,B as b,C as c}from"./chunk-6HKLRU62.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
- //# sourceMappingURL=agent-W7UNXO6L.js.map
1
+ import{A as a,B as b,C as c}from"./chunk-LB4ZIQX3.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
+ //# sourceMappingURL=agent-IQV3P3CK.js.map
@@ -1,4 +1,4 @@
1
- import{A as to,B as ao,C as no,a as C,b as Hr,c as zr,d as qr,e as Fr,f as Ae,g as Ur,h as Wr,i as jt,k as Gr,q as Xr,r as Kr,s as Jr,t as Vr,u as Yr,y as Qr,z as Zr}from"./chunk-BSTIA4M6.js";import{a as eo}from"./chunk-5NTWGUSJ.js";import{a as jr}from"./chunk-LNY6N73E.js";import{a as Br}from"./chunk-4VDA4UM7.js";import{a as ze,b as q,c as I,h as de,i as Pt,j as oe,k as K,l as $t,m as Or,n as Nr,o as Dr}from"./chunk-SCJ5ZXEN.js";import{$a as Rr,A as pr,B as St,Ba as Er,C as ur,Ca as Tr,D as Et,Da as Ar,E as Tt,F as At,G as mr,H as hr,K as gr,L as xr,La as Cr,M as br,Na as Te,Sa as Ir,T as U,U as vr,Ua as He,V as yr,Va as Ct,Wa as It,Xa as Mt,Ya as Lt,Za as Mr,_a as Lr,a as Zn,ab as Rt,c as bt,cb as Pr,d as wa,e as er,fb as $r,i as vt,l as Qe,n as tr,z as _t,za as Sr}from"./chunk-K5QUQNFE.js";import"./chunk-GTJIKXDB.js";import{h as Yn,i as Qn}from"./chunk-5RE2B5YQ.js";import{p as ar,t as nr}from"./chunk-S2GAEH2F.js";import{a as fr,b as B,c as wr,d as kr,h as _r}from"./chunk-BGG3ZSMW.js";import{a as sr,b as yt,d as ir,e as lr,f as wt}from"./chunk-WCXXXAHV.js";import{g as kt}from"./chunk-LQE73AZR.js";import{b as cr,c as dr}from"./chunk-2D3RYIDU.js";import"./chunk-AKLZ4YO2.js";import"./chunk-B3B7KEHJ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as G,c as Ee,d as rr,e as ka}from"./chunk-EMGB23H5.js";import{b as or}from"./chunk-JWDJMFU6.js";import{E as Jn,F as ht,G as gt,H as xt,I as ce,J as Vn,a as qn,f as Fn,g as va,h as ya,l as Un,m as Wn,n as Gn,y as Kn}from"./chunk-ITATBKUL.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-Y4CYQV7G.js";import"./chunk-SHEUCITK.js";import"./chunk-QQYXYJOG.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-AFRHKA7B.js";import"./chunk-5DFUUYEA.js";import{a as Xn}from"./chunk-WMTGAVPW.js";import"./chunk-YSIRJZWF.js";import"./chunk-6PJ6XHG4.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-GSX4NK2N.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{g as zn}from"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import{B as Yc,I as On,L as xa,O as Nn,Q as mt,R as Dn,T as Bn,V as Hn,Z as ba,a as In,b as Mn,c as Kc,oa as X,ra as ft,u as dt,v as Jc,w as ha,x as ga}from"./chunk-46JKX6CT.js";import{d as $n,e as Vc,f as ut,n as jn}from"./chunk-UIBUZ2N3.js";import{a as Ln,b as pt,c as fa,d as Rn,h as Pn}from"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function _a(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function ro(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:_a(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var se={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},Ce=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",Ot=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+Ce(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function oo(t={}){return I({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
1
+ import{A as to,B as ao,C as no,a as C,b as Hr,c as zr,d as qr,e as Fr,f as Ae,g as Ur,h as Wr,i as jt,k as Gr,q as Xr,r as Kr,s as Jr,t as Vr,u as Yr,y as Qr,z as Zr}from"./chunk-BSTIA4M6.js";import{a as eo}from"./chunk-5NTWGUSJ.js";import{a as jr}from"./chunk-LNY6N73E.js";import{a as Br}from"./chunk-4VDA4UM7.js";import{a as ze,b as q,c as I,h as de,i as Pt,j as oe,k as K,l as $t,m as Or,n as Nr,o as Dr}from"./chunk-SCJ5ZXEN.js";import{$a as Rr,A as pr,B as St,Ba as Er,C as ur,Ca as Tr,D as Et,Da as Ar,E as Tt,F as At,G as mr,H as hr,K as gr,L as xr,La as Cr,M as br,Na as Te,Sa as Ir,T as U,U as vr,Ua as He,V as yr,Va as Ct,Wa as It,Xa as Mt,Ya as Lt,Za as Mr,_a as Lr,a as Zn,ab as Rt,c as bt,cb as Pr,d as wa,e as er,fb as $r,i as vt,l as Qe,n as tr,z as _t,za as Sr}from"./chunk-44A5JGRM.js";import"./chunk-GTJIKXDB.js";import{h as Yn,i as Qn}from"./chunk-5RE2B5YQ.js";import{p as ar,t as nr}from"./chunk-S2GAEH2F.js";import{a as fr,b as B,c as wr,d as kr,h as _r}from"./chunk-BGG3ZSMW.js";import{a as sr,b as yt,d as ir,e as lr,f as wt}from"./chunk-WCXXXAHV.js";import{g as kt}from"./chunk-LQE73AZR.js";import{b as cr,c as dr}from"./chunk-2D3RYIDU.js";import"./chunk-AKLZ4YO2.js";import"./chunk-ZCUIBKKI.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as G,c as Ee,d as rr,e as ka}from"./chunk-EMGB23H5.js";import{b as or}from"./chunk-JWDJMFU6.js";import{E as Jn,F as ht,G as gt,H as xt,I as ce,J as Vn,a as qn,f as Fn,g as va,h as ya,l as Un,m as Wn,n as Gn,y as Kn}from"./chunk-ITATBKUL.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-Y4CYQV7G.js";import"./chunk-SHEUCITK.js";import"./chunk-QQYXYJOG.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-AFRHKA7B.js";import"./chunk-5DFUUYEA.js";import{a as Xn}from"./chunk-WMTGAVPW.js";import"./chunk-YSIRJZWF.js";import"./chunk-6PJ6XHG4.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-GSX4NK2N.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{g as zn}from"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import{B as Yc,I as On,L as xa,O as Nn,Q as mt,R as Dn,T as Bn,V as Hn,Z as ba,a as In,b as Mn,c as Kc,oa as X,ra as ft,u as dt,v as Jc,w as ha,x as ga}from"./chunk-46JKX6CT.js";import{d as $n,e as Vc,f as ut,n as jn}from"./chunk-UIBUZ2N3.js";import{a as Ln,b as pt,c as fa,d as Rn,h as Pn}from"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function _a(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function ro(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:_a(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var se={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},Ce=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",Ot=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+Ce(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function oo(t={}){return I({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
2
2
 
3
3
  <div class="bf-head">
4
4
  <div>
@@ -20611,4 +20611,4 @@ data: ${h.replace(/\n/g," ")}
20611
20611
  `)}catch{}}};s.stdout?.on("data",l),s.stderr?.on("data",l);let c=setInterval(()=>{try{e.write(`: hb
20612
20612
 
20613
20613
  `)}catch{}},15e3),d=()=>{clearInterval(c);try{s.kill()}catch{}try{e.end()}catch{}};t.on("close",d),s.on("exit",d),s.on("error",d)}async function Dc(t,e,a,n){let r=a.url+n,o=(t.method||"GET").toUpperCase(),i=o!=="GET"&&o!=="HEAD"?await new Promise((p,m)=>{let h=[];t.on("data",S=>h.push(S)),t.on("end",()=>p(Buffer.concat(h))),t.on("error",m)}):void 0,l={},c=t.headers["content-type"];c&&(l["Content-Type"]=Array.isArray(c)?c[0]:c);let d=t.headers["x-requested-with"];d&&(l["X-Requested-With"]=Array.isArray(d)?d[0]:d),a.token&&(l.Authorization=`Bearer ${a.token}`),l["X-Agentx-Peer"]="primary";try{let p=await fetch(r,{method:o,headers:l,body:i&&i.length>0?i:void 0}),m=Buffer.from(await p.arrayBuffer());e.writeHead(p.status,{"Content-Type":p.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),e.end(m)}catch(p){k(e,502,{error:`proxy to peer failed: ${p?.message||p}`,target:r})}}function lt(t,e){let a=t.replace(/\/+$/,""),n=(e.dashboard?.daemons||[]).find(r=>r.url.replace(/\/+$/,"")===a);return n?{url:Fc(n),token:n.dashboardToken||n.token}:null}export{Dh as applyAttachSessions,Lh as fetchDaemonAgents,Eh as handleBoardRequest,P0 as resetLiveCaches,Se as resolveNodeTargets,R0 as startBoardDashboard,Nh as withLastGood};
20614
- //# sourceMappingURL=board-dashboard-3AOENRSG.js.map
20614
+ //# sourceMappingURL=board-dashboard-H5CKFP4E.js.map
@@ -27,7 +27,7 @@ ${n}`}function Da(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
27
27
  `,l)}};O.stdout?.on("data",T=>{F+=H.write(T);let w=F.split(`
28
28
  `);F=w.pop()||"";for(let _ of w)G(_)}),O.stderr?.on("data",T=>{j+=W.write(T)});let $=await O;if(i&&i.removeEventListener("abort",L),F+=H.end(),F.trim()&&G(F),j+=W.end(),P)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,w;return T.timedOut?w=`OpenCode timed out after ${Math.round(R/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?w=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+j)?w=Fr():w=j.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...X(w),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(R){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(R?.message||"")?Fr():R?.message;return{content:l,...X(E||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{b?.(),I?.release(A)}}async function Ga(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=pe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...X(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ka(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let I=()=>({content:"",...X(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",b=s?`${s}
29
29
 
30
- ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-W7UNXO6L.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-W7UNXO6L.js"),j=await F(L),H=j.inputTokens,W=j.outputTokens;if((H===void 0||W===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),W=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||W!==void 0?{inputTokens:H||0,outputTokens:W||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=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}),h=a.list().length>$}catch($){return $ instanceof Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
30
+ ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-IQV3P3CK.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-IQV3P3CK.js"),j=await F(L),H=j.inputTokens,W=j.outputTokens;if((H===void 0||W===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),W=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||W!==void 0?{inputTokens:H||0,outputTokens:W||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=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}),h=a.list().length>$}catch($){return $ instanceof Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${$}`:$,F=$,!!T){L+=T;try{i(T,L)}catch{}}},H=!1,W=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?W():o.addEventListener("abort",W,{once:!0}));let G=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(G=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let w=T.raw.message?.content??[];for(let S of w)S.type==="text"&&typeof S.text=="string"?(I=S.text,j(S.text)):S.type==="tool_use"&&(F="");let _=T.raw.message?.usage;if(_){let S=(_.input_tokens||0)+(_.cache_read_input_tokens||0)+(_.cache_creation_input_tokens||0);S>0&&(E=S)}}if(T.type==="result"){let w=T.raw;if(w.is_error){let _=X(typeof w.result=="string"?w.result:"claude error");A=_.error,b=_.errorKind}else typeof w.result=="string"&&w.result.length>0&&(I=w.result,L||j(w.result));typeof w.session_id=="string"&&(D=w.session_id),w.usage&&(R={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(O=w.num_turns),typeof w.message?.model=="string"?P=w.message.model:typeof w.model=="string"?P=w.model:P=yt(w.modelUsage)||P}}}catch($){if(H)A="task cancelled by operator",b="cancelled";else if(G)if($ instanceof je)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,b="interrupted";else if($ instanceof Be){let T=X(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=T.error,b=T.errorKind}else{let T=X(`persistent claude process error: ${$?.message||String($)}`);A=T.error,b=T.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",W),null}finally{o&&o.removeEventListener("abort",W)}return H&&!A&&(A="task cancelled by operator",b="cancelled"),{content:H?"":I,error:A,errorKind:b,duration:Date.now()-c,usage:R,contextTokens:E,numTurns:O,billedModel:P,claudeSessionId:D}}function Zr(n){let e=ie(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?_r(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Nr(t.args,n.taskId,n.agentId)}function Xa(n){return ie(n.autonomy)||!!n.personLimits}async function Ya(n,e,t,s,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,c=a&&Rr(a,n.tier)||e.personLimits&&Lr(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?`${ms(a)}
@@ -153,4 +153,4 @@ ${te}`),m+=te.length}catch{}}}let zi=Ht.length>0?Ht.join(`
153
153
 
154
154
  Agent: ${C.content}`,meta:vu(V,e.context)})}catch{}Os(e.agentId,e.message,C.content,{channel:y,chatId:k,sender:Lt},this.memoryStore).catch(()=>{}),mo(e.agentId,e.message,C.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||d.def.model,ce=e.context?.channel,ct=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${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,Q,ce,ct),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${w()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=mt(g.message);return re={content:"",error:ht(m),errorKind:m.kind},re}finally{if(us.stop(),!cs)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:re?.error||(A.signal.aborted?Xe(A.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,at:new Date().toISOString()})}catch{}On(re)}}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:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),Ee,this.safe(e.agentId),t);ne(s)||fu(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);hu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),Ee,this.safe(e));if(!ne(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 f=K(a,l);if(ne(f))try{for(let h of ae(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],I=parseInt(p,10);if(!Number.isFinite(I)||I<i||I>s)continue;let A=Math.floor((s-I)/36e5),b=t-1-A;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),Ee);if(!ne(e))return 0;let t=0;for(let s of ae(e)){let r=K(e,s),o;try{o=ae(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),c;try{c=ae(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ye(K(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Tu){let t=K(process.cwd(),Ee);if(!ne(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=K(t,o),a;try{a=ae(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{mu(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),Ee,this.safe(e));if(!ne(s))return[];let r=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),c;try{c=ae(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(Ye(K(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),Ee,this.safe(e));if(!ne(s))return null;let r=this.safe(t),o=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ne(a))try{return JSON.parse(Ye(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=nr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||Ue(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}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=kt(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}:{}}: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}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Y().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:ws(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let I=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(I))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${I}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}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=f=>{u||(u=!0,d(f))};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:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{Ue(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}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 Pu(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(`
155
155
  `)}export{Tr as a,Gu as b,kr as c,wa as d,Ar as e,bt as f,rl as g,dl as h,cl as i,fl as j,kt as k,Ua as l,Yr as m,Wa as n,Ga as o,Ka as p,eo as q,At as r,$t as s,pd as t,jl as u,ql as v,bn as w,Y as x,ho as y,Td as z,$d as A,bo as B,ig as C,xo as D,vo as E,Po as F,xg as G,_o as H,Pt as I,kg as J,Ag as K,ze as L,Rc as M,Ec as N,Dc as O,Oc as P,Nc as Q,An as R,wu as S,bu as T,gf as U,pf as V,vu as W,ku as X,Au as Y,En as Z,Ai as _,$i as $,Cu as aa,Ci as ba,Mi as ca,Pu as da};
156
- //# sourceMappingURL=chunk-46ACP7A7.js.map
156
+ //# sourceMappingURL=chunk-326G2KKL.js.map
@@ -1,4 +1,4 @@
1
- import{a as Re}from"./chunk-GTJIKXDB.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{a as ne,b as w}from"./chunk-BGG3ZSMW.js";import{b as Jt}from"./chunk-WCXXXAHV.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKLZ4YO2.js";import{t as Xt,u as Gt}from"./chunk-B3B7KEHJ.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{G as Nt,I as te,J as ve,L as $e,b as Se}from"./chunk-ITATBKUL.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-QQYXYJOG.js";import{q as Pt}from"./chunk-5DFUUYEA.js";import{a as Ct,b as Dt}from"./chunk-WMTGAVPW.js";import{A as Rt,B as _t,ga as xe,n as ee,na as It,o as St,oa as Et,p as vt,q as Jr,ra as Tt,y as $t,z as At}from"./chunk-46JKX6CT.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
1
+ import{a as Re}from"./chunk-GTJIKXDB.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{a as ne,b as w}from"./chunk-BGG3ZSMW.js";import{b as Jt}from"./chunk-WCXXXAHV.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKLZ4YO2.js";import{t as Xt,u as Gt}from"./chunk-ZCUIBKKI.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{G as Nt,I as te,J as ve,L as $e,b as Se}from"./chunk-ITATBKUL.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-QQYXYJOG.js";import{q as Pt}from"./chunk-5DFUUYEA.js";import{a as Ct,b as Dt}from"./chunk-WMTGAVPW.js";import{A as Rt,B as _t,ga as xe,n as ee,na as It,o as St,oa as Et,p as vt,q as Jr,ra as Tt,y as $t,z as At}from"./chunk-46JKX6CT.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var si={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},oi=(t,e,n)=>{try{return Pt(t,e,n)}catch{return null}},en=864e5;function Pa(t){let e=t.now??Date.now(),n={...si,...t.thresholds},i=t.nextFire??oi,r=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",u=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(i(a.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:pi(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:tn(u),sampledRuns:l.length,flags:[],attention:null};p.flags=nn(p,u,a.schedule,c,null,e,n,i),r.push(rn(p))}let s=new Map(Qt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let l=o.get(a.workflowId);l?l.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(I=>I.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,ye)=>ye.at-I.at),g=p.map(I=>({at:I.at,status:ci(I.status)})),f=g[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",M={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(b,k.text),timezone:C}:{event:$(typeof c.event=="string"?c.event:"",k.text),filters:di(c.filter,a)},agent:ui(a),enabled:d,state:u,nextRunAt:h&&d&&b?_e(i(b,new Date(e),C)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let I=g.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:tn(g),sampledRuns:p.length,flags:[],attention:null},Q=Date.parse(a.updated||a.created||"");M.flags=h?nn(M,g,b,C,Number.isFinite(Q)?Q:null,e,n,i):ai(M,s.get(a.id)?.state==="dormant",Number.isFinite(Q)?Q:null,e,n),r.push(rn(M))}return r.sort(li).slice(0,k.routines)}function tn(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function nn(t,e,n,i,r,s,o,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=on(c,r,s,o);return p&&l.push(p),l}if(t.consecutiveFailures>=o.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${o.missedFires} scheduled fires missed`}),l}function ai(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=on(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function on(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*en?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/en)} days`:"Disabled and never ran"}}function rn(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var sn={critical:0,warning:1,info:2};function li(t,e){let n=t.attention?sn[t.attention]:3,i=e.attention?sn[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ci(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ui(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function di(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function pi(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as H,readdirSync as Pi,readFileSync as Ni}from"fs";import{resolve as R}from"path";import{randomBytes as cn}from"crypto";import{existsSync as fi,mkdirSync as mi,readdirSync as hi,readFileSync as bi,renameSync as un,unlinkSync as yi,writeFileSync as wi}from"fs";import{resolve as dn}from"path";function an(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var gi=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function ln(t,e,n,i=Re){let r=await i(t.bin,[...an(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${gi(r.stderr||r.stdout)}`}}async function Oa(t,e,n,i,r=Re){return(await r(t.bin,[...an(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ki=2e3,xi=t=>ln(t.wacli,t.to,t.text);function Ie(t){return dn(t,".agentx","whatsapp-triage","drafts")}var Si=t=>/^[a-z0-9-]{8,64}$/.test(t),ie=(t,e)=>dn(Ie(t),`${e}.json`);function pn(t,e){mi(Ie(t),{recursive:!0});let n=ie(t,e.id),i=`${n}.${process.pid}.tmp`;wi(i,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),un(i,n)}function Va(t,e,n=Date.now()){let i=e.text.trim().slice(0,ki);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${cn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return pn(t,r),r}function se(t,e){if(!Si(e))return null;try{return JSON.parse(bi(ie(t,e),"utf-8"))}catch{return null}}function gn(t,e){let n=Ie(t);return fi(n)?hi(n).filter(i=>i.endsWith(".json")).map(i=>se(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function fn(t,e,n,i={}){let r=se(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${ie(t,e)}.${process.pid}.${cn(3).toString("hex")}.claim`;try{un(ie(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??xi)(r).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}pn(t,o);try{yi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as vi,readFileSync as $i,renameSync as Ai,writeFileSync as Ri}from"fs";import{resolve as _i}from"path";function mn(t){return _i(Ae(t),"_state.json")}function A(t){try{let e=JSON.parse($i(mn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function B(t,e){vi(Ae(t),{recursive:!0});let n=mn(t),i=`${n}.${process.pid}.tmp`;Ri(i,JSON.stringify(e,null,2)+`
@@ -529,4 +529,4 @@ Document the arguments, commands, or files the skill expects. Example:
529
529
  claude-code ${xt(t)} --arg value
530
530
  \`\`\`
531
531
  `}Tt();var zr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Xr(t){return{...zr,...t??{},regions:{...t?.regions??{}},buffer:{...zr.buffer,...t?.buffer??{}}}}function td(t){try{return Xr(Et(t).screen)}catch{return Xr(void 0)}}var Ra=/^[a-z][\w-]*$/,Gr=["window","screen","menubar","notifications"];function Z(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var be=(t,e)=>Z(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Kr(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function nd(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=be(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=be(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=be(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Z(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Z(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Ra.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Kr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Z(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Z(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=be(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Gr.includes(i)&&!n.regions?.[i])try{Kr(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Gr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Qt as a,Ea as b,tt as c,Ks as d,Js as e,mc as f,hc as g,bc as h,ar as i,wc as j,xc as k,D as l,lr as m,k as n,Pa as o,Oa as p,xi as q,Va as r,fn as s,A as t,Xa as u,Ga as v,Ya as w,oe as x,Za as y,xn as z,il as A,z as B,wl as C,kl as D,_n as E,cr as F,$c as G,_c as H,vr as I,eu as J,tu as K,au as L,qo as M,lu as N,Sl as O,vl as P,$l as Q,Al as R,Rl as S,_l as T,El as U,Tl as V,Wl as W,Me as X,Fl as Y,Ul as Z,X as _,G as $,Ko as aa,bu as ba,yu as ca,wu as da,ku as ea,ct as fa,xu as ga,Fe as ha,Ue as ia,pe as ja,ms as ka,bs as la,zl as ma,qe as na,Be as oa,ys as pa,ws as qa,Xn as ra,Yn as sa,Xl as ta,Ss as ua,Gl as va,Ts as wa,Ps as xa,He as ya,Ls as za,Zn as Aa,P as Ba,Lr as Ca,Or as Da,Mr as Ea,_u as Fa,ia as Ga,Wr as Ha,Fr as Ia,ju as Ja,Wu as Ka,ka as La,Fu as Ma,Vr as Na,ge as Oa,oc as Pa,ir as Qa,ze as Ra,Qe as Sa,gc as Ta,Bu as Ua,Hu as Va,zu as Wa,Xu as Xa,Gu as Ya,Ku as Za,Ju as _a,Yu as $a,Zu as ab,zr as bb,Xr as cb,td as db,Gr as eb,nd as fb};
532
- //# sourceMappingURL=chunk-K5QUQNFE.js.map
532
+ //# sourceMappingURL=chunk-44A5JGRM.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
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=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:n,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 re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.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||""),n=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-UBVBEEDW.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*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||""),n=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-5PMZ3ZCT.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*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,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.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,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=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"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.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 T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.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),U.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:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.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{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-6HKLRU62.js.map
126
+ //# sourceMappingURL=chunk-LB4ZIQX3.js.map
@@ -0,0 +1,49 @@
1
+ import{a as O,b as j,c as E,d as T,e as D,j as _}from"./chunk-VHT7HESZ.js";import{c as R}from"./chunk-56KNKUFF.js";import{y as M,z as F}from"./chunk-BN5QMNON.js";import{b as S,c as P}from"./chunk-QOYAX2FT.js";import{readFileSync as G,existsSync as J}from"fs";F();import{resolve as $}from"path";import{execSync as K}from"child_process";async function it(r,e,i,t={}){let h=t.selectorModel??"haiku",m=t.synthModel??"sonnet",o=t.maxCandidates??3,c=t.maxHops??2,n=t.maxArticles??8,u=t.timeoutMs??6e4,g=t.log??console.error.bind(console,"[wiki-query]"),p=t.messagePath?.length?t.messagePath:void 0,s=t.graphWeight??x,a=$(e.baseDir,"_index.md");if(!J(a))return b("no-catalog",r,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let d=G(a,"utf-8"),v=Date.now(),f=[],y="";try{let l=await Y(r,N(e),i,o,p,s);l?(f=l,y=`[wiki-rerank seat] ${l.map(k=>k.title).join(" | ")}`):(y=await I(U(r,d,o,p),h,u),f=V(y))}catch(l){return g("selector failed:",l?.message),{...b("error",r,`Selector: ${l?.message||"unknown"}`),trace:{selectorMs:Date.now()-v,synthesisMs:0,selectorOutput:y}}}let A=Date.now()-v;if(f.length===0)return{...b("no-candidates",r,"Selector returned no candidates."),trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let w=Q(f,e,i,c,n);if(w.length===0)return{...b("no-candidates",r,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let C=Date.now(),W="";try{W=await I(z(r,w),m,u*2)}catch(l){return g("synthesis failed:",l?.message),{...b("error",r,`Synthesis: ${l?.message||"unknown"}`),candidates:f,walked:w.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:A,synthesisMs:Date.now()-C,selectorOutput:y}}}let L=Date.now()-C;return{answer:W.trim(),citations:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type})),candidates:f,walked:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type,hop:l.hop??0})),status:"ok",trace:{selectorMs:A,synthesisMs:L,selectorOutput:y}}}async function st(r,e,i,t={}){let h=t.maxCandidates??3,m=t.graphWeight??x,o=t.messagePath?.length?t.messagePath:void 0,c=t.pool??N(e);if(c.length===0||!r.trim())return[];let n=await Y(r,c,i,h,o,m,t.stage??"retrieve");if(!n){let u=new Set(P(r,S(c.map(H))).map(g=>g.docIndex));n=B(r,c,o,m).filter(g=>u.has(g)).slice(0,h).map(g=>({title:c[g].title,path:c[g].path}))}return n.length===0?[]:Q(n,e,i,t.maxHops??1,t.maxArticles??6)}function N(r){try{return(r.rebuildIndex().articles??[]).filter(e=>e.path&&!e.path.includes("/_versions/"))}catch{return[]}}function b(r,e,i){return{answer:"",citations:[],candidates:[],walked:[],status:r,error:i}}function Q(r,e,i,t,h){let m=new Map;for(let n of e.listArticles(i||""))m.set(n.meta.title.toLowerCase(),n.path);let o=new Map,c=[];for(let n of r)o.has(n.path)||c.push({path:n.path,hop:0});for(;c.length&&o.size<h;){let n=c.shift();if(o.has(n.path)||n.hop>t)continue;let u=i?e.readArticleAs(n.path,i):e.readArticle(n.path);if(u&&(o.set(n.path,{...u,hop:n.hop}),!(n.hop>=t)))for(let g of u.meta.related||[]){let p=m.get(g.toLowerCase());p&&!o.has(p)&&c.push({path:p,hop:n.hop+1})}}return Array.from(o.values())}async function Y(r,e,i,t,h,m=x,o="catalog-selector"){try{if(e.length<2)return null;let n=B(r,e,h,m).slice(0,j).map(s=>({id:`k${s}`,title:e[s].title||e[s].path,tags:e[s].tags,excerpt:[e[s].type?`type: ${e[s].type}`:"",(e[s].related??[]).length?`related: ${(e[s].related??[]).join(", ")}`:"",(e[s].graphPath??[]).length?`graph: ${(e[s].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),u=await M(O,E({query:r,candidates:n,excerptChars:300}),T(n),{features:{agent:i??"unknown",stage:o}});if(!u||u.mode!=="active")return null;let p=D(u.answers,n).ranked.slice(0,t).map(s=>e[Number(s.slice(1))]).filter(Boolean).map(s=>({title:s.title,path:s.path}));return p.length>0?p:null}catch{return null}}var x=.6;function B(r,e,i,t=x){let h=P(r,S(e.map(H))),m=h.reduce((a,d)=>Math.max(a,d.score),0),o=new Map(h.map(a=>[a.docIndex,m>0?a.score/m:0])),c=!!i?.length,n=a=>c&&a.graphPath?.length?_(i,a.graphPath):0,u=(a,d)=>d.score-a.score||a.i-d.i,g=e.map((a,d)=>({i:d,score:(o.get(d)??0)*(1+t*n(a))})).filter(a=>o.has(a.i)).sort(u),p=e.map((a,d)=>({i:d,score:n(a)})).filter(a=>!o.has(a.i)&&a.score>0).sort(u),s=[...g,...p].map(a=>a.i);for(let a=0;a<e.length;a++)s.includes(a)||s.push(a);return s}function H(r){return[r.title,(r.tags??[]).join(" "),(r.related??[]).join(" ")].join(" ")}function U(r,e,i,t){let h=t?.length?`
2
+ ## Intent
3
+
4
+ The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
5
+ `:"";return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
6
+
7
+ ## Question
8
+
9
+ ${r}
10
+ ${h}
11
+ ## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
12
+
13
+ ${e}
14
+
15
+ ## Your task
16
+
17
+ Pick up to ${i} articles from the catalog that are most likely to answer the question. Prefer:
18
+ - Articles whose title directly names a subject in the question.
19
+ - Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
20
+ - Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
21
+
22
+ Return ONLY valid JSON, no markdown fencing, no prose:
23
+
24
+ [
25
+ {"title": "Exact Article Title", "path": "path/from/catalog.md"},
26
+ ...
27
+ ]
28
+
29
+ If none of the articles match, return [].`}function z(r,e){let i=e.map(t=>{let h=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,m=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[h,m,"",t.content].filter(Boolean).join(`
30
+ `)}).join(`
31
+
32
+ ---
33
+
34
+ `);return`You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.
35
+
36
+ ## Question
37
+
38
+ ${r}
39
+
40
+ ## Articles (${e.length} walked from the catalog)
41
+
42
+ ${i}
43
+
44
+ ## Your task
45
+
46
+ Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
47
+
48
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function V(r){let e=r.match(/\[[\s\S]*?\]/);if(!e)return[];try{let i=JSON.parse(e[0]);return Array.isArray(i)?i.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function I(r,e,i){let{writeFileSync:t,mkdirSync:h,rmSync:m}=await import("fs"),{tmpdir:o}=await import("os"),c=$(o(),`agentx-wiki-query-${process.pid}`);h(c,{recursive:!0});let n=$(c,`prompt-${Date.now()}.txt`);t(n,r);try{let u=`cat '${n}' | claude -p - --output-format json --max-turns 1 --model ${e} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,g=K(u,{env:R(),encoding:"utf-8",timeout:i,maxBuffer:4*1024*1024});try{let p=JSON.parse(g);return String(p.result||p.content||"")}catch{return g}}finally{try{m(n,{force:!0})}catch{}}}export{it as a,st as b,N as c,x as d,B as e};
49
+ //# sourceMappingURL=chunk-NW7RVE57.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { claudeCliEnv } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle, WikiIndex } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, catalogPool(store), requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\nexport interface RetrieveOptions {\n /** Articles picked before the walk. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from the picked articles. Default 1. */\n maxHops?: number\n /** Hard cap on articles returned. Default 6. */\n maxArticles?: number\n messagePath?: string[]\n graphWeight?: number\n /** The catalog to pick from. Pass it when retrieving many times in a row,\n * so the index is not rebuilt for every call. */\n pool?: CatalogEntry[]\n /** Seat telemetry label. */\n stage?: string\n}\n\n/**\n * The retrieval half of agenticQuery, without the synthesis call: BM25\n * shortlist, rerank seat, then the `related` wikilink walk. Returns the\n * walked articles, hop 0 first.\n *\n * When the seat is off or fails, the BM25 order decides on its own, and\n * only articles the text matched are picked: an article chosen for\n * nothing but its catalog position is noise here, not a candidate. There\n * is no CLI fallback, so this never spends an LLM call.\n */\nexport async function retrieveArticles(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: RetrieveOptions = {},\n): Promise<Array<WikiArticle & { hop: number }>> {\n const maxCandidates = opts.maxCandidates ?? 3\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const pool = opts.pool ?? catalogPool(store)\n if (pool.length === 0 || !question.trim()) return []\n\n let candidates = await selectCandidatesViaSeat(\n question, pool, requesterId, maxCandidates, messagePath, graphWeight, opts.stage ?? \"retrieve\",\n )\n if (!candidates) {\n const matched = new Set(scoreAll(question, buildIndex(pool.map(catalogDoc))).map((r) => r.docIndex))\n candidates = rankCatalogPool(question, pool, messagePath, graphWeight)\n .filter((i) => matched.has(i))\n .slice(0, maxCandidates)\n .map((i) => ({ title: pool[i].title, path: pool[i].path }))\n }\n if (candidates.length === 0) return []\n return walkSubgraph(candidates, store, requesterId, opts.maxHops ?? 1, opts.maxArticles ?? 6)\n}\n\nexport type CatalogEntry = WikiIndex[\"articles\"][number]\n\n/** The catalog retrieval picks from: every indexed article but old versions. */\nexport function catalogPool(store: WikiStore): CatalogEntry[] {\n try {\n return (store.rebuildIndex().articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n } catch {\n return []\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n pool: CatalogEntry[],\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n stage = \"catalog-selector\",\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const bm25 = scoreAll(question, buildIndex(pool.map(catalogDoc)))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\n/** What BM25 sees of a catalog entry: the catalog carries no body. */\nfunction catalogDoc(a: { title: string; tags?: string[]; related?: string[] }): string {\n return [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \")\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: claudeCliEnv(), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAEzCC,IAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,MAAgB,gBAiEzB,eAAsBC,GACpBC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAaF,EAAK,YAAc,SAChCG,EAAgBH,EAAK,eAAiB,EACtCI,EAAUJ,EAAK,SAAW,EAC1BK,EAAcL,EAAK,aAAe,EAClCM,EAAYN,EAAK,WAAa,IAC9BO,EAAMP,EAAK,KAAO,QAAQ,MAAM,KAAK,QAAS,cAAc,EAC5DQ,EAAcR,EAAK,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IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMtF,EAASiG,EAAK,CAAE,IAAKC,EAAa,EAAG,SAAU,QAAS,QAASvF,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EACpH,GAAI,CACF,IAAMwF,EAAW,KAAK,MAAMb,CAAG,EAC/B,OAAO,OAAOa,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOb,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","catalogPool","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","retrieveArticles","pool","matched","scoreAll","buildIndex","catalogDoc","r","rankCatalogPool","i","status","_question","error","titleIndex","article","opened","frontier","next","target","path","stage","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","bm25","maxBm25","m","text","useGraph","branch","ancestryScore","byScore","x","y","branchOnly","ranked","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","claudeCliEnv","envelope"]}
@@ -1,12 +1,12 @@
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-6W74CHNW.js";import{a as E}from"./chunk-6PJ6XHG4.js";import{b as L}from"./chunk-CECHWYJ2.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=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=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-6W74CHNW.js";import{a as E}from"./chunk-6PJ6XHG4.js";import{b as L}from"./chunk-CECHWYJ2.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=""){return Z(r,s,t,o,i,c,p)}function Z(n,r,s,t,o,i="",c=""){let p=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
5
- `:"",p=new Map;for(let g of s){let l=g.type||"untyped",d=p.get(l)||[];d.push(g),p.set(l,d)}let u=s.length===0?"":`
5
+ `:"",m=new Map;for(let l of s){let g=l.type||"untyped",e=m.get(g)||[];e.push(l),m.set(g,e)}let u=s.length===0?"":`
6
6
  ## Existing Articles (the current catalog)
7
7
 
8
- `+Array.from(p.entries()).sort().map(([g,l])=>`**${g}**
9
- `+l.sort((d,e)=>d.title.localeCompare(e.title)).map(d=>`- [[${d.title}]] \u2014 ${d.path}`).join(`
8
+ `+Array.from(m.entries()).sort().map(([l,g])=>`**${l}**
9
+ `+g.sort((e,a)=>e.title.localeCompare(a.title)).map(e=>`- [[${e.title}]] \u2014 ${e.path}`).join(`
10
10
  `)).join(`
11
11
 
12
12
  `)+`
@@ -38,7 +38,7 @@ Path reflects type: \`<type>s/<slug>.md\` where slug is a kebab-case title.
38
38
 
39
39
  For each of the ${o} raw entries below, ask in this order:
40
40
 
41
- 1. **Does it extend an existing article?** If a person/project/concept mentioned in the entry already has an article in the catalog, produce an UPDATE with the full merged content. Prefer merging over proliferating.
41
+ 1. **Does it extend an existing article?** If a person/project/concept/event mentioned in the entry already has an article in the catalog, produce an UPDATE at that article's path with the full merged content. Prefer merging over proliferating. When the article is shown in full below, keep every fact it already has.
42
42
  2. **Does it deserve a new article?** Only if the subject is a persistent entity (a person, a project, a recurring concept, a specific event/decision) that future queries will need to find. Not every conversation deserves an article.
43
43
  3. **Does it belong in an existing \`event\` or \`decision\`?** Most work entries fold into one of these.
44
44
  4. **Can you skip it?** If the entry is small talk, a transient status ping, or already covered elsewhere \u2014 skip. The wiki is curated, not exhaustive.
@@ -111,7 +111,7 @@ sources: ["entry-id-1", "entry-id-2"]
111
111
  \`\`\`
112
112
 
113
113
  Access guidance: default \`public\`; \`private\` only for sensitive credentials or agent-specific learnings; \`shared\` with specific agent IDs when the article matters only to a subset.
114
- ${c}${u}${i}
114
+ ${p}${u}${c}${i}
115
115
  ## Gap Detection
116
116
 
117
117
  After compiling, populate a \`gaps\` array: wikilink targets you referenced but for which no article exists yet. Be specific:
@@ -146,16 +146,16 @@ ${t}`}var U=2e3,Q=300;function D(n,r,s,t){let o=t?`
146
146
  ## Worldview
147
147
 
148
148
  ${t}
149
- `:"",i=new Map;for(let l of s){let d=l.type||"untyped",e=i.get(d)||[];e.push(l),i.set(d,e)}let c=s.length>Q,p=s.length===0?"":`
149
+ `:"",i=new Map;for(let l of s){let g=l.type||"untyped",e=i.get(g)||[];e.push(l),i.set(g,e)}let c=s.length>Q,p=s.length===0?"":`
150
150
  ## Existing Articles (the current catalog${c?`, ${s.length} articles \u2014 titles only`:""})
151
151
 
152
- `+Array.from(i.entries()).sort().map(([l,d])=>`**${l}**
153
- `+d.sort((e,a)=>e.title.localeCompare(a.title)).map(e=>c?`- [[${e.title}]]`:`- [[${e.title}]] \u2014 ${e.path}`).join(`
152
+ `+Array.from(i.entries()).sort().map(([l,g])=>`**${l}**
153
+ `+g.sort((e,a)=>e.title.localeCompare(a.title)).map(e=>c?`- [[${e.title}]]`:`- [[${e.title}]] \u2014 ${e.path}`).join(`
154
154
  `)).join(`
155
155
 
156
156
  `)+`
157
- `,u=r.reduce((l,d)=>l+d.candidates.length,0),g=r.map(l=>{let d=l.corroboratingAgents.length>1?`corroborated by: ${l.corroboratingAgents.join(", ")} (${l.corroboratingAgents.length} agents)`:`single agent: ${l.corroboratingAgents[0]}`;return l.candidates.map(e=>{let a=e.memory.body.length>U?e.memory.body.slice(0,U)+`
158
- [\u2026 truncated]`:e.memory.body;return[`--- CANDIDATE ${e.stamp} ---`,`type: ${e.memory.type} | agent: ${e.agentId} | ${d} | confidence: ${l.confidence.toFixed(2)}`,`description: ${e.memory.description}`,a,"--- END CANDIDATE ---"].join(`
157
+ `,m=r.reduce((l,g)=>l+g.candidates.length,0),u=r.map(l=>{let g=l.corroboratingAgents.length>1?`corroborated by: ${l.corroboratingAgents.join(", ")} (${l.corroboratingAgents.length} agents)`:`single agent: ${l.corroboratingAgents[0]}`;return l.candidates.map(e=>{let a=e.memory.body.length>U?e.memory.body.slice(0,U)+`
158
+ [\u2026 truncated]`:e.memory.body;return[`--- CANDIDATE ${e.stamp} ---`,`type: ${e.memory.type} | agent: ${e.agentId} | ${g} | confidence: ${l.confidence.toFixed(2)}`,`description: ${e.memory.description}`,a,"--- END CANDIDATE ---"].join(`
159
159
  `)}).join(`
160
160
 
161
161
  `)}).join(`
@@ -234,10 +234,10 @@ Reference candidates ONLY by their exact stamp strings (the \`memory:...\` line
234
234
  }
235
235
  \`\`\`
236
236
 
237
- CANDIDATES (${u} memories in ${r.length} clusters):
237
+ CANDIDATES (${m} memories in ${r.length} clusters):
238
238
 
239
- ${g}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-promotions.json",N="memory:",j="failure:";function J(n){let r=n.lastIndexOf("@");return r===-1?n:n.slice(0,r)}var se=["user","feedback","project","reference"];function q(n,r){return`${n}/${r.type}_${r.name}`}function ie(n,r){return`${N}${q(n,r)}@${r.updatedAt}`}function $(n){if(!n.startsWith(N))return null;let r=n.slice(N.length),s=r.indexOf("/"),t=r.lastIndexOf("@");if(s<=0||t<=s)return null;let o=r.slice(0,s),i=r.slice(s+1,t),c=r.slice(t+1);if(!c)return null;let p=i.indexOf("_");if(p<=0)return null;let u=i.slice(0,p),g=i.slice(p+1);return!se.includes(u)||!g?null:{agentId:o,type:u,name:g,updatedAt:c,key:`${o}/${i}`}}function ae(n,r){let s=new Set;for(let o of r){let i=$(o);i&&s.add(i.key)}let t=[];for(let o of n??[]){let i=$(o);i&&s.has(i.key)||t.includes(o)||t.push(o)}for(let o of r)t.includes(o)||t.push(o);return t}function ce(n=P(process.cwd(),".agentx")){let r=new F({baseDir:n});if(!H(r.baseDir))return[];let s=[];for(let t of te(r.baseDir,{withFileTypes:!0}))if(!(!t.isDirectory()||t.name.startsWith("_")||t.name.startsWith(".")))for(let o of r.list(t.name))s.push({agentId:t.name,memory:o});return s}var pe=new Set(["promoted","skipped","proposed","rejected"]);function z(n){let r=P(n,K);if(!H(r))return[];try{let s=JSON.parse(re(r,"utf-8"));return Array.isArray(s)?s.filter(t=>t&&typeof t.stamp=="string"&&pe.has(t.decision)):[]}catch{return[]}}function C(n,r){let s=[...z(n),...r],t=new Map;for(let o of s){let i=$(o.stamp),c=i?.key??o.stamp,p=t.get(c);(!p||!i||($(p.stamp)?.updatedAt??"")<=i.updatedAt)&&t.set(c,o)}ne(P(n,K),JSON.stringify([...t.values()],null,2))}function le(n){let r=new Map;for(let s of n){let t=`${s.memory.type}_${s.memory.name}`,o=r.get(t)??[];o.push(s),r.set(t,o)}return[...r.values()].map(s=>{let t=[...new Set(s.map(c=>c.agentId))].sort(),o=["project","reference"].includes(s[0].memory.type)?.05:0,i=Math.min(.95,.5+.15*(t.length-1)+o);return{candidates:s,corroboratingAgents:t,confidence:i}})}function B(n,r){let s=n.indexOf("{");if(s===-1)return{error:"no JSON object in response"};let t=0,o=-1,i=!1,c=!1;for(let e=s;e<n.length;e++){let a=n[e];if(c){c=!1;continue}if(a==="\\"){c=!0;continue}if(a==='"'){i=!i;continue}if(!i){if(a==="{")t++;else if(a==="}"&&(t--,t===0)){o=e+1;break}}}if(o===-1)return{error:"unbalanced JSON in response"};let p;try{p=JSON.parse(n.slice(s,o))}catch(e){return{error:`JSON parse error: ${e.message}`}}if(!p||typeof p!="object"||!Array.isArray(p.articles))return{error:"response JSON missing articles array"};let u=[],g=[];for(let e of p.articles){if(!e||typeof e.path!="string"||typeof e.title!="string"||typeof e.content!="string"){u.push("article missing path/title/content \u2014 dropped");continue}let a=Array.isArray(e.promotedFrom)?e.promotedFrom.filter(y=>typeof y=="string"):[],h=a.filter(y=>r.has(y));for(let y of a)r.has(y)||u.push(`article "${e.path}" references unknown stamp "${y}" \u2014 dropped`);if(h.length===0){u.push(`article "${e.path}" has no valid promotedFrom stamps \u2014 dropped`);continue}g.push({path:e.path,title:e.title,type:typeof e.type=="string"?e.type:void 0,related:Array.isArray(e.related)?e.related.filter(y=>typeof y=="string"):void 0,tags:Array.isArray(e.tags)?e.tags.filter(y=>typeof y=="string"):[],content:e.content,promotedFrom:h})}let l=[];for(let e of Array.isArray(p.skipped)?p.skipped:[]){let a=typeof e?.memory=="string"?e.memory:typeof e?.stamp=="string"?e.stamp:"";if(!r.has(a)){a&&u.push(`skip references unknown stamp "${a}" \u2014 dropped`);continue}l.push({stamp:a,reason:typeof e.reason=="string"?e.reason:""})}let d=Array.isArray(p.gaps)?p.gaps.filter(e=>typeof e=="string"):[];return{articles:g,skipped:l,gaps:d,warnings:u}}function de(n,r,s,t={}){let o=t.types??oe,i=t.now??Date.now(),c=t.max??20,p=new Map,u=new Set,g=e=>{u.add(e);let a=$(e);if(!a)return;let h=p.get(a.key);(!h||a.updatedAt>h)&&p.set(a.key,a.updatedAt)};for(let e of r.articles)for(let a of e.sources??[])g(a);for(let e of s)g(e.stamp);let l=new Set(s.filter(e=>e.decision==="proposed"&&e.stamp.startsWith(j)).map(e=>J(e.stamp))),d=[];for(let{agentId:e,memory:a,stamp:h,occurrences:y,sessions:w,tasks:b,failure:f}of n){if(!o.includes(a.type)||t.agentFilter&&e!==t.agentFilter)continue;if(t.sinceMs!==void 0){let T=Date.parse(a.updatedAt);if(!Number.isFinite(T)||T<i-t.sinceMs)continue}if(h&&u.has(h)||h?.startsWith(j)&&l.has(J(h)))continue;let v=q(e,a),k=p.get(v);k&&a.updatedAt<=k||d.push({agentId:e,memory:a,key:v,stamp:h??ie(e,a),occurrences:y,...w?.length?{sessions:w}:{},...b?.length?{tasks:b}:{},...f?{failure:f}:{}})}return d.sort((e,a)=>(a.occurrences??0)-(e.occurrences??0)||a.memory.updatedAt.localeCompare(e.memory.updatedAt)).slice(0,c)}var me="https://api.anthropic.com/v1/messages",ge="2023-06-01";async function G(n,r,s=null){let t=r.fetchImpl??fetch,o=r.timeoutMs??18e4,i=new AbortController,c=setTimeout(()=>i.abort(),o);try{if(r.viaAgent){let a=(r.daemonUrl??"http://127.0.0.1:18800").replace(/\/+$/,""),h=s?`Your previous response failed validation: ${s}
240
- 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 u=[{role:"user",content:n}];s&&(u.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),u.push({role:"user",content:`Your previous response failed validation: ${s}
241
- Re-emit the FULL corrected JSON object.`}));let g=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:u}),signal:i.signal});if(!g.ok){let a=await g.text().catch(()=>"");throw new Error(`anthropic API ${g.status}: ${a.slice(0,500)}`)}let l=await g.json(),e=(Array.isArray(l.content)?l.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
242
- `).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,(...m)=>t(m.map(String).join(" "))),p=c.rebuildIndex(),u=z(r),g=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(g,p,u,{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 l=p.articles.map(m=>({title:m.title,path:m.path,type:m.type})),d=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,l,d);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,l,d);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(m=>m.candidates),w=new Set(y.map(m=>m.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(m=>[m.stamp,m]));for(let m of f.articles){let A=c.readArticle(m.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${m.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(m.promotedFrom,T),S={id:Y(o,m.path),createdAt:v,status:"pending",article:m,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:m.path,title:m.title,type:m.type,stamps:m.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of m.promotedFrom)k.push({stamp:X,decision:"proposed",article:m.path,proposal:S.id,at:v})}for(let m of f.skipped)k.push({stamp:m.stamp,decision:"skipped",reason:m.reason,at:v}),i.skipped.push(m);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 u=s.now??Date.now(),g=new Date(u).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??g,lastUpdated:g,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 d=new Date(u).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:d}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:d};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};
243
- //# sourceMappingURL=chunk-B3B7KEHJ.js.map
239
+ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-promotions.json",N="memory:",j="failure:";function J(n){let r=n.lastIndexOf("@");return r===-1?n:n.slice(0,r)}var se=["user","feedback","project","reference"];function q(n,r){return`${n}/${r.type}_${r.name}`}function ie(n,r){return`${N}${q(n,r)}@${r.updatedAt}`}function $(n){if(!n.startsWith(N))return null;let r=n.slice(N.length),s=r.indexOf("/"),t=r.lastIndexOf("@");if(s<=0||t<=s)return null;let o=r.slice(0,s),i=r.slice(s+1,t),c=r.slice(t+1);if(!c)return null;let p=i.indexOf("_");if(p<=0)return null;let m=i.slice(0,p),u=i.slice(p+1);return!se.includes(m)||!u?null:{agentId:o,type:m,name:u,updatedAt:c,key:`${o}/${i}`}}function ae(n,r){let s=new Set;for(let o of r){let i=$(o);i&&s.add(i.key)}let t=[];for(let o of n??[]){let i=$(o);i&&s.has(i.key)||t.includes(o)||t.push(o)}for(let o of r)t.includes(o)||t.push(o);return t}function ce(n=P(process.cwd(),".agentx")){let r=new F({baseDir:n});if(!H(r.baseDir))return[];let s=[];for(let t of te(r.baseDir,{withFileTypes:!0}))if(!(!t.isDirectory()||t.name.startsWith("_")||t.name.startsWith(".")))for(let o of r.list(t.name))s.push({agentId:t.name,memory:o});return s}var pe=new Set(["promoted","skipped","proposed","rejected"]);function z(n){let r=P(n,K);if(!H(r))return[];try{let s=JSON.parse(re(r,"utf-8"));return Array.isArray(s)?s.filter(t=>t&&typeof t.stamp=="string"&&pe.has(t.decision)):[]}catch{return[]}}function C(n,r){let s=[...z(n),...r],t=new Map;for(let o of s){let i=$(o.stamp),c=i?.key??o.stamp,p=t.get(c);(!p||!i||($(p.stamp)?.updatedAt??"")<=i.updatedAt)&&t.set(c,o)}ne(P(n,K),JSON.stringify([...t.values()],null,2))}function le(n){let r=new Map;for(let s of n){let t=`${s.memory.type}_${s.memory.name}`,o=r.get(t)??[];o.push(s),r.set(t,o)}return[...r.values()].map(s=>{let t=[...new Set(s.map(c=>c.agentId))].sort(),o=["project","reference"].includes(s[0].memory.type)?.05:0,i=Math.min(.95,.5+.15*(t.length-1)+o);return{candidates:s,corroboratingAgents:t,confidence:i}})}function B(n,r){let s=n.indexOf("{");if(s===-1)return{error:"no JSON object in response"};let t=0,o=-1,i=!1,c=!1;for(let e=s;e<n.length;e++){let a=n[e];if(c){c=!1;continue}if(a==="\\"){c=!0;continue}if(a==='"'){i=!i;continue}if(!i){if(a==="{")t++;else if(a==="}"&&(t--,t===0)){o=e+1;break}}}if(o===-1)return{error:"unbalanced JSON in response"};let p;try{p=JSON.parse(n.slice(s,o))}catch(e){return{error:`JSON parse error: ${e.message}`}}if(!p||typeof p!="object"||!Array.isArray(p.articles))return{error:"response JSON missing articles array"};let m=[],u=[];for(let e of p.articles){if(!e||typeof e.path!="string"||typeof e.title!="string"||typeof e.content!="string"){m.push("article missing path/title/content \u2014 dropped");continue}let a=Array.isArray(e.promotedFrom)?e.promotedFrom.filter(y=>typeof y=="string"):[],h=a.filter(y=>r.has(y));for(let y of a)r.has(y)||m.push(`article "${e.path}" references unknown stamp "${y}" \u2014 dropped`);if(h.length===0){m.push(`article "${e.path}" has no valid promotedFrom stamps \u2014 dropped`);continue}u.push({path:e.path,title:e.title,type:typeof e.type=="string"?e.type:void 0,related:Array.isArray(e.related)?e.related.filter(y=>typeof y=="string"):void 0,tags:Array.isArray(e.tags)?e.tags.filter(y=>typeof y=="string"):[],content:e.content,promotedFrom:h})}let l=[];for(let e of Array.isArray(p.skipped)?p.skipped:[]){let a=typeof e?.memory=="string"?e.memory:typeof e?.stamp=="string"?e.stamp:"";if(!r.has(a)){a&&m.push(`skip references unknown stamp "${a}" \u2014 dropped`);continue}l.push({stamp:a,reason:typeof e.reason=="string"?e.reason:""})}let g=Array.isArray(p.gaps)?p.gaps.filter(e=>typeof e=="string"):[];return{articles:u,skipped:l,gaps:g,warnings:m}}function de(n,r,s,t={}){let o=t.types??oe,i=t.now??Date.now(),c=t.max??20,p=new Map,m=new Set,u=e=>{m.add(e);let a=$(e);if(!a)return;let h=p.get(a.key);(!h||a.updatedAt>h)&&p.set(a.key,a.updatedAt)};for(let e of r.articles)for(let a of e.sources??[])u(a);for(let e of s)u(e.stamp);let l=new Set(s.filter(e=>e.decision==="proposed"&&e.stamp.startsWith(j)).map(e=>J(e.stamp))),g=[];for(let{agentId:e,memory:a,stamp:h,occurrences:y,sessions:w,tasks:b,failure:f}of n){if(!o.includes(a.type)||t.agentFilter&&e!==t.agentFilter)continue;if(t.sinceMs!==void 0){let T=Date.parse(a.updatedAt);if(!Number.isFinite(T)||T<i-t.sinceMs)continue}if(h&&m.has(h)||h?.startsWith(j)&&l.has(J(h)))continue;let v=q(e,a),k=p.get(v);k&&a.updatedAt<=k||g.push({agentId:e,memory:a,key:v,stamp:h??ie(e,a),occurrences:y,...w?.length?{sessions:w}:{},...b?.length?{tasks:b}:{},...f?{failure:f}:{}})}return g.sort((e,a)=>(a.occurrences??0)-(e.occurrences??0)||a.memory.updatedAt.localeCompare(e.memory.updatedAt)).slice(0,c)}var me="https://api.anthropic.com/v1/messages",ge="2023-06-01";async function G(n,r,s=null){let t=r.fetchImpl??fetch,o=r.timeoutMs??18e4,i=new AbortController,c=setTimeout(()=>i.abort(),o);try{if(r.viaAgent){let a=(r.daemonUrl??"http://127.0.0.1:18800").replace(/\/+$/,""),h=s?`Your previous response failed validation: ${s}
240
+ 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}
241
+ 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 l=await u.json(),e=(Array.isArray(l.content)?l.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
242
+ `).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,(...d)=>t(d.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 l=p.articles.map(d=>({title:d.title,path:d.path,type:d.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,l,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,l,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(d=>d.candidates),w=new Set(y.map(d=>d.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(d=>[d.stamp,d]));for(let d of f.articles){let A=c.readArticle(d.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${d.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(d.promotedFrom,T),S={id:Y(o,d.path),createdAt:v,status:"pending",article:d,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:d.path,title:d.title,type:d.type,stamps:d.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of d.promotedFrom)k.push({stamp:X,decision:"proposed",article:d.path,proposal:S.id,at:v})}for(let d of f.skipped)k.push({stamp:d.stamp,decision:"skipped",reason:d.reason,at:v}),i.skipped.push(d);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};
243
+ //# sourceMappingURL=chunk-ZCUIBKKI.js.map