agentix-cli 0.221.0 → 0.221.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{agent-5FVRGDGM.js → agent-DXKDG4DQ.js} +2 -2
  2. package/dist/{board-dashboard-ZJLIP2L4.js → board-dashboard-QV7OD4SO.js} +3 -3
  3. package/dist/{chunk-ZWD4ADV4.js → chunk-575LJSX2.js} +3 -3
  4. package/dist/{chunk-F6LT3DHK.js → chunk-AAPHOKWS.js} +2 -2
  5. package/dist/{chunk-RFVXW6F2.js → chunk-AAQOXNLE.js} +242 -242
  6. package/dist/chunk-AAQOXNLE.js.map +1 -0
  7. package/dist/chunk-EFXZACH4.js +2 -0
  8. package/dist/chunk-EFXZACH4.js.map +1 -0
  9. package/dist/chunk-FG2FPOML.js +2 -0
  10. package/dist/chunk-FG2FPOML.js.map +1 -0
  11. package/dist/{chunk-AX6CCD5P.js → chunk-FRYEUVYD.js} +3 -3
  12. package/dist/{chunk-AX6CCD5P.js.map → chunk-FRYEUVYD.js.map} +1 -1
  13. package/dist/{chunk-BX4RQ2IZ.js → chunk-LO5A3VKY.js} +2 -2
  14. package/dist/{chunk-B5QQ4IH2.js → chunk-RMB6G7X2.js} +2 -2
  15. package/dist/cli.js +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/{program-YGEXHPRD.js → program-Q4DXWAQU.js} +4 -4
  18. package/dist/{registry-KYCXXPEA.js → registry-Q3H6QR6Q.js} +2 -2
  19. package/dist/{runner-I4ZB37JE.js → runner-KWSARUS4.js} +2 -2
  20. package/dist/step-proof-GLY7XVPD.js +2 -0
  21. package/package.json +1 -1
  22. package/dist/chunk-LIY6X3LU.js +0 -2
  23. package/dist/chunk-LIY6X3LU.js.map +0 -1
  24. package/dist/chunk-RFVXW6F2.js.map +0 -1
  25. package/dist/chunk-TCM3UOEQ.js +0 -2
  26. package/dist/chunk-TCM3UOEQ.js.map +0 -1
  27. package/dist/step-proof-NMKY7T5A.js +0 -2
  28. /package/dist/{agent-5FVRGDGM.js.map → agent-DXKDG4DQ.js.map} +0 -0
  29. /package/dist/{board-dashboard-ZJLIP2L4.js.map → board-dashboard-QV7OD4SO.js.map} +0 -0
  30. /package/dist/{chunk-ZWD4ADV4.js.map → chunk-575LJSX2.js.map} +0 -0
  31. /package/dist/{chunk-F6LT3DHK.js.map → chunk-AAPHOKWS.js.map} +0 -0
  32. /package/dist/{chunk-BX4RQ2IZ.js.map → chunk-LO5A3VKY.js.map} +0 -0
  33. /package/dist/{chunk-B5QQ4IH2.js.map → chunk-RMB6G7X2.js.map} +0 -0
  34. /package/dist/{program-YGEXHPRD.js.map → program-Q4DXWAQU.js.map} +0 -0
  35. /package/dist/{registry-KYCXXPEA.js.map → registry-Q3H6QR6Q.js.map} +0 -0
  36. /package/dist/{runner-I4ZB37JE.js.map → runner-KWSARUS4.js.map} +0 -0
  37. /package/dist/{step-proof-NMKY7T5A.js.map → step-proof-GLY7XVPD.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{A as a,B as b,C as c}from"./chunk-BX4RQ2IZ.js";import"./chunk-SFQUP3BP.js";import"./chunk-LY4G7PCW.js";import"./chunk-AHWWJ7AF.js";import"./chunk-DCIYOPJF.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-5FVRGDGM.js.map
1
+ import{A as a,B as b,C as c}from"./chunk-LO5A3VKY.js";import"./chunk-SFQUP3BP.js";import"./chunk-LY4G7PCW.js";import"./chunk-AHWWJ7AF.js";import"./chunk-DCIYOPJF.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-DXKDG4DQ.js.map
@@ -1,4 +1,4 @@
1
- import{A as wd,B as Yn,D as xd,F as Cr,I as vd,K as yd,L as kd,M as _d,N as Be,O as Qn,P as Sd,Q as Ad,R as Td,S as Ed,T as Cd,U as Rd,Y as Id,Z as Pd,a as Ve,aa as Od,b as X,ba as jd,c as Z,d as Jn,da as Md,e as sd,f as od,g as id,i as ld,ia as Zn,j as dd,ja as $d,k as cd,ka as Hd,l as pd,la as Bd,m as ud,ma as Wd,n as fd,na as Fd,oa as qd,pa as zd,ra as Ud,sa as Gd,v as hd,w as gd,x as rt,y as Er,z as bd}from"./chunk-F6LT3DHK.js";import"./chunk-EFGAPAYZ.js";import{a as Ld}from"./chunk-FFOGEFPT.js";import{a as Nd,b as Dd}from"./chunk-NZQBS7GN.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as md}from"./chunk-WMZ4TGMR.js";import{b as rd}from"./chunk-2YDG5CSS.js";import{a as ad}from"./chunk-LNY6N73E.js";import{$ as _l,$b as Yl,Da as jl,Eb as Fl,Fa as Ll,Gb as ql,Hb as zl,Ib as Ul,J as bl,Ja as Ml,Kb as Gl,M as $e,N as wl,O as we,Oa as Q,P as Mn,Pa as Ar,Q as Nn,Qa as Nl,R as Dn,Ra as Dl,Rb as Vl,S as $n,Sa as $l,T as xl,Tb as He,U as Hn,Ua as Hl,Ub as Tr,V as Bn,Va as Bl,Vb as Xl,W as Wn,Wb as Kl,X as vl,Y as yl,Yb as Jl,Z as kl,Za as Wl,a as nl,aa as Sl,ba as Fn,bc as _t,c as On,ca as Al,cc as Un,d as yr,da as Tl,dc as Gn,e as al,ea as El,ec as Vn,fa as Cl,fc as Xn,ga as _r,gc as Ql,ha as qn,hc as Zl,ia as Rl,ic as ed,jc as Kn,la as Il,lc as td,na as zn,oa as Pl,oc as nd,p as Jt,qa as Yt,r as rl,ua as Ge,w as gl,xa as Ol,y as ml,ya as Sr}from"./chunk-B5QQ4IH2.js";import"./chunk-GTJIKXDB.js";import{i as el,j as tl}from"./chunk-NCMPJPXG.js";import{S as sl,U as ol,i as Gi,j as Vi,k as Xi,l as Ki,s as Yi,t as Ue,u as Qi,v as Zi}from"./chunk-VYNM7HYU.js";import{a as kt}from"./chunk-IMLAPB7G.js";import"./chunk-MRIVENBY.js";import"./chunk-GO4J44UD.js";import{a as il,b as re,c as Ne,d as ll,e as kr}from"./chunk-UKUH662W.js";import{a as cl,b as De,d as pl,e as ul,f as jn}from"./chunk-2VDO2HEK.js";import{b as dl}from"./chunk-JWDJMFU6.js";import{g as Ln}from"./chunk-LQE73AZR.js";import{b as fl,c as hl}from"./chunk-2D3RYIDU.js";import{a as D}from"./chunk-4UJDRI7W.js";import"./chunk-XC3466Z4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-SQP6A5AG.js";import{d as Ji}from"./chunk-QPABR72X.js";import"./chunk-AEFO6ES5.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{A as En,Aa as Ui,B as Ri,Ba as Kt,C as Ii,D as Pi,E as Oi,F as Cn,G as ji,H as Li,I as Rn,J as vr,N as Mi,P as Ni,Q as Di,a as yi,ba as Fi,g as _i,h as Si,ha as qi,o as Ai,q as Ti,r as Xt,s as xr,t as Ei,u as Ci,y as An,ya as Pn,z as Tn,za as zi}from"./chunk-AX6CCD5P.js";import"./chunk-MEFPXHQJ.js";import{a as H,b as F,c as ki,e as at}from"./chunk-7AB3QUGH.js";import"./chunk-TCM3UOEQ.js";import"./chunk-7YOLZGB5.js";import{n as $i,o as Hi,p as Bi}from"./chunk-IH65GDJR.js";import"./chunk-NW7B53KD.js";import{a as In,b as Wi}from"./chunk-5BT4VPJC.js";import"./chunk-3UOTLMXD.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-LIY6X3LU.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import{b as gi,c as mi,s as bi,t as wr,u as wi}from"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import{c as G}from"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-JMRFYGET.js";import"./chunk-ABMDDRZL.js";import{g as vi}from"./chunk-5QXRGX2F.js";import{b as xi}from"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-Y6KR7NXL.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as fi,b as hi}from"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import{A as No,Ab as _n,B as Do,C as $o,Cc as Vt,D as Ho,Db as Sn,E as Bo,Fa as Qo,Ha as vw,Hb as si,J as Ut,Jb as yt,K as ur,Kb as oi,Lb as ii,M as Wo,Mb as li,N as Fo,O as qo,Oa as hr,Ob as di,Q as zo,R as Uo,S as Go,Sb as Gt,T as Vo,U as Xo,Ua as _w,V as ww,Va as ne,Wa as gr,Xa as ai,Za as mr,ab as ri,cb as br,gb as Me,m as xn,n as Io,o as Po,p as Oo,pa as vn,q as jo,qa as xw,qc as ci,r as Lo,rc as pi,sc as ae,uc as ui,z as Mo}from"./chunk-VOVDWFFP.js";import{a as Ko,b as yn,c as fr,d as Jo,h as Yo}from"./chunk-KEUW6YLL.js";import{d as Zo,e as yw,g as ei,h as ti,i as kw,j as kn,r as ni}from"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";Io();function Rr(e,t,n=Date.now()){let r=Math.max(0,n-(e.updatedAt||n)),a=e.clientId?t[e.clientId]:void 0;if(!a)return{score:r/864e5,ageMs:r,rising:!1,overdue:!1};let s=r/(a*6e4);return{score:1e3+s,ageMs:r,rising:!0,overdue:s>=1}}function Vd(e,t,n=Date.now()){return e.map((r,a)=>({i:a,s:Rr(r,t,n).score})).sort((r,a)=>a.s-r.s||r.i-a.i).map(r=>r.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"/>'},st=(e,t=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+t+'" height="'+t+'" aria-hidden="true">'+e+"</svg>",ea=(e,t,n,r="")=>'<div class="ax-sec-label"><h3>'+st(e,13)+t+(n?'<span class="ax-sec-label__n" id="'+n+'"></span>':"")+"</h3>"+r+"</div>";function Xd(e={}){return Z({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:e.peers,localToken:e.localToken,body:`<div class="bf">
1
+ import{A as wd,B as Yn,D as xd,F as Cr,I as vd,K as yd,L as kd,M as _d,N as Be,O as Qn,P as Sd,Q as Ad,R as Td,S as Ed,T as Cd,U as Rd,Y as Id,Z as Pd,a as Ve,aa as Od,b as X,ba as jd,c as Z,d as Jn,da as Md,e as sd,f as od,g as id,i as ld,ia as Zn,j as dd,ja as $d,k as cd,ka as Hd,l as pd,la as Bd,m as ud,ma as Wd,n as fd,na as Fd,oa as qd,pa as zd,ra as Ud,sa as Gd,v as hd,w as gd,x as rt,y as Er,z as bd}from"./chunk-AAPHOKWS.js";import"./chunk-EFGAPAYZ.js";import{a as Ld}from"./chunk-FFOGEFPT.js";import{a as Nd,b as Dd}from"./chunk-NZQBS7GN.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as md}from"./chunk-WMZ4TGMR.js";import{b as rd}from"./chunk-2YDG5CSS.js";import{a as ad}from"./chunk-LNY6N73E.js";import{$ as _l,$b as Yl,Da as jl,Eb as Fl,Fa as Ll,Gb as ql,Hb as zl,Ib as Ul,J as bl,Ja as Ml,Kb as Gl,M as $e,N as wl,O as we,Oa as Q,P as Mn,Pa as Ar,Q as Nn,Qa as Nl,R as Dn,Ra as Dl,Rb as Vl,S as $n,Sa as $l,T as xl,Tb as He,U as Hn,Ua as Hl,Ub as Tr,V as Bn,Va as Bl,Vb as Xl,W as Wn,Wb as Kl,X as vl,Y as yl,Yb as Jl,Z as kl,Za as Wl,a as nl,aa as Sl,ba as Fn,bc as _t,c as On,ca as Al,cc as Un,d as yr,da as Tl,dc as Gn,e as al,ea as El,ec as Vn,fa as Cl,fc as Xn,ga as _r,gc as Ql,ha as qn,hc as Zl,ia as Rl,ic as ed,jc as Kn,la as Il,lc as td,na as zn,oa as Pl,oc as nd,p as Jt,qa as Yt,r as rl,ua as Ge,w as gl,xa as Ol,y as ml,ya as Sr}from"./chunk-RMB6G7X2.js";import"./chunk-GTJIKXDB.js";import{i as el,j as tl}from"./chunk-NCMPJPXG.js";import{S as sl,U as ol,i as Gi,j as Vi,k as Xi,l as Ki,s as Yi,t as Ue,u as Qi,v as Zi}from"./chunk-VYNM7HYU.js";import{a as kt}from"./chunk-IMLAPB7G.js";import"./chunk-MRIVENBY.js";import"./chunk-GO4J44UD.js";import{a as il,b as re,c as Ne,d as ll,e as kr}from"./chunk-UKUH662W.js";import{a as cl,b as De,d as pl,e as ul,f as jn}from"./chunk-2VDO2HEK.js";import{b as dl}from"./chunk-JWDJMFU6.js";import{g as Ln}from"./chunk-LQE73AZR.js";import{b as fl,c as hl}from"./chunk-2D3RYIDU.js";import{a as D}from"./chunk-4UJDRI7W.js";import"./chunk-XC3466Z4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-SQP6A5AG.js";import{d as Ji}from"./chunk-QPABR72X.js";import"./chunk-AEFO6ES5.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{A as En,Aa as Ui,B as Ri,Ba as Kt,C as Ii,D as Pi,E as Oi,F as Cn,G as ji,H as Li,I as Rn,J as vr,N as Mi,P as Ni,Q as Di,a as yi,ba as Fi,g as _i,h as Si,ha as qi,o as Ai,q as Ti,r as Xt,s as xr,t as Ei,u as Ci,y as An,ya as Pn,z as Tn,za as zi}from"./chunk-FRYEUVYD.js";import"./chunk-MEFPXHQJ.js";import{a as H,b as F,c as ki,e as at}from"./chunk-7AB3QUGH.js";import"./chunk-EFXZACH4.js";import"./chunk-7YOLZGB5.js";import{n as $i,o as Hi,p as Bi}from"./chunk-IH65GDJR.js";import"./chunk-NW7B53KD.js";import{a as In,b as Wi}from"./chunk-5BT4VPJC.js";import"./chunk-3UOTLMXD.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import{b as gi,c as mi,s as bi,t as wr,u as wi}from"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import{c as G}from"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-JMRFYGET.js";import"./chunk-ABMDDRZL.js";import{g as vi}from"./chunk-5QXRGX2F.js";import{b as xi}from"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-Y6KR7NXL.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as fi,b as hi}from"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import{A as No,Ab as _n,B as Do,C as $o,Cc as Vt,D as Ho,Db as Sn,E as Bo,Fa as Qo,Ha as vw,Hb as si,J as Ut,Jb as yt,K as ur,Kb as oi,Lb as ii,M as Wo,Mb as li,N as Fo,O as qo,Oa as hr,Ob as di,Q as zo,R as Uo,S as Go,Sb as Gt,T as Vo,U as Xo,Ua as _w,V as ww,Va as ne,Wa as gr,Xa as ai,Za as mr,ab as ri,cb as br,gb as Me,m as xn,n as Io,o as Po,p as Oo,pa as vn,q as jo,qa as xw,qc as ci,r as Lo,rc as pi,sc as ae,uc as ui,z as Mo}from"./chunk-VOVDWFFP.js";import{a as Ko,b as yn,c as fr,d as Jo,h as Yo}from"./chunk-KEUW6YLL.js";import{d as Zo,e as yw,g as ei,h as ti,i as kw,j as kn,r as ni}from"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";Io();function Rr(e,t,n=Date.now()){let r=Math.max(0,n-(e.updatedAt||n)),a=e.clientId?t[e.clientId]:void 0;if(!a)return{score:r/864e5,ageMs:r,rising:!1,overdue:!1};let s=r/(a*6e4);return{score:1e3+s,ageMs:r,rising:!0,overdue:s>=1}}function Vd(e,t,n=Date.now()){return e.map((r,a)=>({i:a,s:Rr(r,t,n).score})).sort((r,a)=>a.s-r.s||r.i-a.i).map(r=>r.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"/>'},st=(e,t=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+t+'" height="'+t+'" aria-hidden="true">'+e+"</svg>",ea=(e,t,n,r="")=>'<div class="ax-sec-label"><h3>'+st(e,13)+t+(n?'<span class="ax-sec-label__n" id="'+n+'"></span>':"")+"</h3>"+r+"</div>";function Xd(e={}){return Z({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:e.peers,localToken:e.localToken,body:`<div class="bf">
2
2
 
3
3
  <div class="bf-head">
4
4
  <div>
@@ -1767,7 +1767,7 @@ ${Qr("Connecting\u2026",`
1767
1767
 
1768
1768
  ${i||"You are "+r+"."}
1769
1769
  `)}catch{}return{summary:c}}function yv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Agent id is required.");let n=e?.patch||{},{summary:r}=D(a=>{if(!a.agents?.[t])throw new Error(`Agent "${t}" not found.`);let s=a.agents[t];return typeof n.name=="string"&&n.name.trim()&&(s.name=n.name.trim()),typeof n.model=="string"&&(s.model=n.model.trim()||void 0),typeof n.tier=="string"&&["claude-code","codex-cli","opencode","sdk","orchestrator"].includes(n.tier)&&(s.tier=n.tier),typeof n.systemPrompt=="string"&&(s.systemPrompt=n.systemPrompt.trim()||void 0),Array.isArray(n.mentions)?s.mentions=n.mentions.map(o=>String(o).trim()).filter(Boolean):typeof n.triggerWords=="string"&&(s.mentions=Mp(n.triggerWords)),typeof n.maxConcurrent=="number"&&n.maxConcurrent>=1&&(s.maxConcurrent=n.maxConcurrent),typeof n.maxExecutionMinutes=="number"&&n.maxExecutionMinutes>=1&&n.maxExecutionMinutes<=240&&(s.maxExecutionMinutes=n.maxExecutionMinutes),typeof n.permissionMode=="string"&&(s.permissionMode=n.permissionMode),(n.access==="public"||n.access==="private")&&(s.access=n.access),typeof n.wikiAbsorb=="boolean"&&Zn(s,n.wikiAbsorb),`updated agent "${t}"`});return{summary:r}}function kv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Agent id is required.");let{summary:n}=D(r=>{if(!r.agents||!r.agents[t])throw new Error(`Agent "${t}" not found.`);if(delete r.agents[t],r.channels?.telegram?.accounts)for(let a of Object.keys(r.channels.telegram.accounts))r.channels.telegram.accounts[a]?.agentBinding===t&&(r.channels.telegram.accounts[a].agentBinding="");return`removed agent "${t}"`});return{summary:n}}function _v(e){let t=String(e?.id||"").trim(),n=String(e?.agentBinding||"").trim(),r=String(e?.botUsername||"").trim(),a=String(e?.botTokenEnv||"").trim();if(!t)throw new Error("Account id is required.");if(!n)throw new Error("Choose an agent to bind this account to.");if(!a)throw new Error("Bot token env-var name is required (e.g. TG_SUPPORT_BOT_TOKEN).");let{summary:s}=D(o=>{if(o.channels=o.channels||{},o.channels.telegram=o.channels.telegram||{enabled:!0,accounts:{},policy:{dm:"pair",group:"mention-required"}},o.channels.telegram.enabled=!0,o.channels.telegram.accounts=o.channels.telegram.accounts||{},o.channels.telegram.accounts[t])throw new Error(`Telegram account "${t}" already exists.`);if(!o.agents?.[n])throw new Error(`Unknown agent "${n}".`);return o.channels.telegram.accounts[t]={token:"${"+a+"}",agentBinding:n},`added telegram account "${t}"`});return{summary:s,hint:`Add ${a}=<bot-token> to your .env file.`}}function Sv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Account id is required.");let n=e?.patch||{},{summary:r}=D(a=>{let s=a.channels?.telegram?.accounts?.[t];if(!s)throw new Error(`Account "${t}" not found.`);if(typeof n.agentBinding=="string"&&n.agentBinding.trim()){if(!a.agents?.[n.agentBinding])throw new Error(`Unknown agent "${n.agentBinding}".`);s.agentBinding=n.agentBinding.trim()}return typeof n.botUsername=="string"&&(s.botUsername=n.botUsername.trim()),typeof n.botTokenEnv=="string"&&n.botTokenEnv.trim()&&(s.token="${"+n.botTokenEnv.trim()+"}"),`updated telegram account "${t}"`});return{summary:r}}async function Ke(e){let{url:t,headers:n}=os(),r=await fetch(t+e,{headers:n}),a=await r.text();if(!r.ok)throw new Error(`daemon ${r.status}: ${a.slice(0,200)}`);try{return JSON.parse(a)}catch{return{raw:a}}}async function We(e,t){let{url:n,headers:r}=os(),a=await fetch(n+e,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t||{})}),s=await a.text();if(!a.ok)throw new Error(`daemon ${a.status}: ${s.slice(0,200)}`);try{return JSON.parse(s)}catch{return{raw:s}}}async function Av(e,t){try{let{url:n,headers:r}=os(),a=await fetch(n+t,{headers:r}),s=await a.text();e.writeHead(a.status,{"Content-Type":a.headers.get("content-type")||"image/svg+xml","Cache-Control":"no-store"}),e.end(s)}catch(n){e.writeHead(502,{"Content-Type":"text/plain; charset=utf-8"}),e.end("daemon unreachable: "+(n?.message||"unknown"))}}function os(){let e="http://127.0.0.1:18800",t={};try{let n=ae();e=n.dashboard.daemonUrl?.replace(/\/+$/,"")||e,n.dashboard.token&&(t.Authorization=`Bearer ${n.dashboard.token}`)}catch{}return{url:e,headers:t}}function rn(e){let n=ct()?.agents?.[e];if(!n)throw new Error(`Unknown agent "${e}".`);if(!n.workspace)throw new Error(`Agent "${e}" has no workspace configured.`);return n.workspace}function rs(e,t){try{return new URL(e.url||"/","http://localhost").searchParams.get(t)||""}catch{return""}}function Tv(e){let t=rs(e,"agent").trim();if(!t)throw new Error("agent= query param is required.");let n=_t(rn(t));return{agentId:t,...n}}function Ev(e){let t=rs(e,"agent").trim(),n=rs(e,"path").trim();if(!t||!n)throw new Error("agent= and path= query params are required.");return Un(rn(t),n)}function Cv(e){let t=String(e?.agent||"").trim(),n=String(e?.path||"").trim(),r=typeof e?.content=="string"?e.content:"";if(!t||!n)throw new Error("agent and path are required.");let a=Gn(rn(t),n,r);return{summary:`saved ${n} (${a.bytes} bytes)`,...a}}function Rv(e){let t=String(e?.agent||"").trim(),n=String(e?.slug||"").trim(),r=e?.title?String(e.title):void 0,a=e?.content?String(e.content):void 0;if(!t)throw new Error("agent is required.");let s=Vn(rn(t),n,{title:r,content:a});return{summary:`added skill "${n}"`,...s}}function Iv(e){let t=String(e?.agent||"").trim(),n=String(e?.slug||"").trim();if(!t||!n)throw new Error("agent and slug are required.");let r=Xn(rn(t),n);return{summary:`removed skill "${n}"`,...r}}function Pv(e){let t=String(e?.agentId||"").trim(),n=String(e?.kind||"").trim(),r=String(e?.label||"").trim();if(!t)throw new Error("agentId is required");if(!n)throw new Error("kind is required");if(!r)throw new Error("label is required");let a={},s=e?.credentials||{};for(let l of["tokenEnv","privateAppTokenEnv","apiKeyEnv","refreshTokenEnv","clientIdEnv","clientSecretEnv"]){let d=s[l];if(typeof d=="string"&&d.trim()){if(!/^[A-Z][A-Z0-9_]*$/.test(d.trim()))throw new Error(`${l} must be uppercase identifier (got "${d}")`);a[l]=d.trim()}}if(s.auth==="keyring"&&(a.auth="keyring"),typeof s.sessionDir=="string"&&s.sessionDir.trim()&&(a.sessionDir=s.sessionDir.trim()),Object.keys(a).length===0)throw new Error("at least one credential field required");let o={};for(let[l,d]of Object.entries(e?.metadata||{}))(typeof d=="string"||typeof d=="number"||typeof d=="boolean")&&(o[l]=d);let{summary:i}=D(l=>{if(!l.agents?.[t])throw new Error(`Unknown agent "${t}"`);if(l.agents[t].integrations=Array.isArray(l.agents[t].integrations)?l.agents[t].integrations:[],l.agents[t].integrations.find(d=>d.kind===n&&d.label===r))throw new Error(`integration (${n}, ${r}) already exists on ${t}`);return l.agents[t].integrations.push({kind:n,label:r,credentials:a,metadata:o,enabled:!0}),`added ${n} integration "${r}" to ${t}`});return{summary:i}}function Ov(e){let t=String(e?.agentId||"").trim(),n=String(e?.kind||"").trim(),r=String(e?.label||"").trim();if(!t)throw new Error("agentId is required");if(!n||!r)throw new Error("kind and label are required");let{summary:a}=D(s=>{let o=s.agents?.[t];if(!o)throw new Error(`Unknown agent "${t}"`);let i=o.integrations||[],l=i.findIndex(d=>d.kind===n&&d.label===r);if(l===-1)throw new Error(`integration (${n}, ${r}) not found on ${t}`);return i.splice(l,1),`removed ${n} integration "${r}" from ${t}`});return{summary:a}}function jv(e){let t=String(e?.agentId||"").trim(),n=String(e?.kind||"").trim(),r=String(e?.label||"").trim();if(!t)throw new Error("agentId is required");if(!n||!r)throw new Error("kind and label are required");let a=e?.patch||{},{summary:s}=D(o=>{let i=o.agents?.[t];if(!i)throw new Error(`Unknown agent "${t}"`);let d=(i.integrations||[]).find(c=>c.kind===n&&c.label===r);if(!d)throw new Error(`integration (${n}, ${r}) not found on ${t}`);return typeof a.enabled=="boolean"&&(d.enabled=a.enabled),a.metadata&&typeof a.metadata=="object"&&(d.metadata={...d.metadata||{},...a.metadata}),`updated integration (${n}, ${r}) on ${t}`});return{summary:s}}var Lp=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"];function Lv(e){let t=String(e?.id||"").trim(),n=String(e?.source||"").trim(),r=String(e?.agentId||"").trim(),a=String(e?.secretEnv||"").trim(),s=String(e?.description||"").trim(),o=String(e?.node||"").trim();if(!/^[a-z0-9][a-z0-9_-]*$/.test(t))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!Lp.includes(n))throw new Error(`Unknown source: ${n}`);if(!r)throw new Error("Pick an agent to bind the webhook to.");let{summary:i}=D(l=>{if(o){if(!(l.mesh?.peers||[]).find(p=>p.name===o))throw new Error(`Mesh peer "${o}" not found in mesh.peers. Add the peer first or remove the node field.`)}else if(!l.agents?.[r])throw new Error(`Unknown agent "${r}". Add it locally, or set --node <peer> to forward to a mesh peer.`);if(l.webhooks=Array.isArray(l.webhooks)?l.webhooks:[],l.webhooks.find(c=>c.id===t))throw new Error(`Webhook "${t}" already exists.`);let d={id:t,source:n,agentId:r,enabled:!0};return a&&(d.secretEnv=a),s&&(d.description=s),o&&(d.node=o),l.webhooks.push(d),`added webhook "${t}" (${n} \u2192 ${r}${o?` @ ${o}`:""})`});return{summary:i}}function Mv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Webhook id is required.");let n=e?.patch||{},{summary:r}=D(a=>{let s=(a.webhooks||[]).find(o=>o.id===t);if(!s)throw new Error(`Webhook "${t}" not found.`);if(typeof n.source=="string"&&Lp.includes(n.source)&&(s.source=n.source),typeof n.agentId=="string"&&n.agentId.trim()){if(!a.agents?.[n.agentId])throw new Error(`Unknown agent "${n.agentId}".`);s.agentId=n.agentId.trim()}return typeof n.secretEnv=="string"&&(s.secretEnv=n.secretEnv.trim()||void 0),typeof n.description=="string"&&(s.description=n.description.trim()||void 0),typeof n.enabled=="boolean"&&(s.enabled=n.enabled),`updated webhook "${t}"`});return{summary:r}}function Nv(e){let t=String(e?.url||"").trim().replace(/\/+$/,""),n=String(e?.name||"").trim(),r=String(e?.token||"").trim()||void 0;if(!t||!/^https?:\/\//.test(t))throw new Error("Peer URL must start with http:// or https://");if(!n)throw new Error("Peer name is required.");let{summary:a}=D(s=>{if(s.mesh=s.mesh||{enabled:!0,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},s.mesh.enabled=!0,s.mesh.peers=Array.isArray(s.mesh.peers)?s.mesh.peers:[],s.mesh.peers.find(i=>i.url===t))throw new Error(`Peer at ${t} already registered.`);let o={url:t,name:n};return r&&(o.token=r),s.mesh.peers.push(o),`added mesh peer "${n}"`});return{summary:a}}function Dv(e){let t=String(e?.url||"").trim().replace(/\/+$/,"");if(!t)throw new Error("Peer URL is required.");let{summary:n}=D(r=>{let a=(r.mesh?.peers||[]).length;if(r.mesh=r.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},r.mesh.peers=(r.mesh.peers||[]).filter(s=>s.url.replace(/\/+$/,"")!==t),r.mesh.peers.length===a)throw new Error(`Peer at ${t} not found.`);return`removed mesh peer ${t}`});return{summary:n}}function $v(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.mesh=r.mesh||{enabled:t,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},r.mesh.enabled=t,`mesh ${t?"enabled":"disabled"}`));return{summary:n}}function Hv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Webhook id is required.");let{summary:n}=D(r=>{let a=(r.webhooks||[]).length;if(r.webhooks=(r.webhooks||[]).filter(s=>s.id!==t),r.webhooks.length===a)throw new Error(`Webhook "${t}" not found.`);return`removed webhook "${t}"`});return{summary:n}}function Bv(e){let t=String(e?.botTokenEnv||"").trim(),n=String(e?.appTokenEnv||"").trim(),r=String(e?.agentBinding||"").trim();if(!t)throw new Error("Bot token env-var name is required (e.g. SLACK_BOT_TOKEN).");if(!n)throw new Error("App-level token env-var name is required (e.g. SLACK_APP_TOKEN).");let{summary:a}=D(s=>{if(s.channels=s.channels||{},s.channels.slack=s.channels.slack||{enabled:!1},s.channels.slack.enabled=!0,s.channels.slack.botToken="${"+t+"}",s.channels.slack.appToken="${"+n+"}",r){if(!s.agents?.[r])throw new Error(`Unknown agent "${r}".`);s.channels.slack.agentBinding=r}return"configured slack connector"});return{summary:a,hint:`Add ${t}=xoxb-\u2026 and ${n}=xapp-\u2026 to your .env.`}}function Wv(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.channels=r.channels||{},r.channels.slack=r.channels.slack||{enabled:!1},r.channels.slack.enabled=t,`slack ${t?"enabled":"disabled"}`));return{summary:n}}function Fv(e){let t=String(e?.id||"").trim(),n=String(e?.agent||"").trim(),r=String(e?.address||"").trim().toLowerCase(),a=String(e?.imapHost||"").trim(),s=String(e?.smtpHost||a).trim(),o=Number(e?.imapPort||993),i=Number(e?.smtpPort||465);if(!/^[a-z0-9][a-z0-9_-]*$/i.test(t))throw new Error("Account id: letters, numbers, - and _ (e.g. support).");if(!/^\S+@\S+\.\S+$/.test(r))throw new Error("Enter the address customers write to.");if(!a)throw new Error("Enter the IMAP server (imap.gmail.com for Gmail).");if(!Number.isInteger(o)||!Number.isInteger(i))throw new Error("Ports must be numbers.");let l=String(e?.passwordEnv||"").trim()||jd(t);if(!/^[A-Z_][A-Z0-9_]*$/.test(l))throw new Error("Password variable: capital letters, numbers and _ (e.g. EMAIL_SUPPORT_PASSWORD).");let d=String(e?.allowFrom??"*").split(/[\s,]+/).map(p=>p.trim()).filter(Boolean),{summary:c}=D(p=>{if(!p.agents?.[n])throw new Error(`Unknown agent "${n}".`);return p.channels=p.channels||{},p.channels.email=p.channels.email||{enabled:!1,accounts:{}},p.channels.email.enabled=!0,p.channels.email.accounts=p.channels.email.accounts||{},p.channels.email.accounts[t]=Od({agent:n,address:r,imapHost:a,imapPort:o,smtpHost:s,smtpPort:i,user:String(e?.user||"").trim()||void 0,passwordEnv:l,allowFrom:d,send:e?.send==="auto"?"auto":"approve"}),`email account ${t} (${r}) answered by ${n}`});return{summary:c,hint:`Add ${l}=<password> to your .env (for Gmail, an app password), then restart the daemon. To check the login first, use \`agentx connect email\` instead.`}}function qv(e){let t=String(e?.id||"").trim(),{summary:n}=D(r=>{if(!r.channels?.email?.accounts?.[t])throw new Error(`No email account "${t}".`);return delete r.channels.email.accounts[t],`email account ${t} removed`});return{summary:n}}function zv(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.channels=r.channels||{},r.channels.email=r.channels.email||{enabled:!1,accounts:{}},r.channels.email.enabled=t,`email ${t?"enabled":"disabled"}`));return{summary:n}}function Uv(e){let t=String(e?.tokenEnv||"").trim(),n=String(e?.agentBinding||"").trim();if(!t)throw new Error("Bot token env-var name is required (e.g. DISCORD_BOT_TOKEN).");let{summary:r}=D(a=>{if(a.channels=a.channels||{},a.channels.discord=a.channels.discord||{enabled:!1},a.channels.discord.enabled=!0,a.channels.discord.token="${"+t+"}",n){if(!a.agents?.[n])throw new Error(`Unknown agent "${n}".`);a.channels.discord.agentBinding=n}return"configured discord connector"});return{summary:r,hint:`Add ${t}=<bot-token> to your .env.`}}function Gv(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.channels=r.channels||{},r.channels.discord=r.channels.discord||{enabled:!1},r.channels.discord.enabled=t,`discord ${t?"enabled":"disabled"}`));return{summary:n}}function Vv(e){let t=String(e?.host||"").trim().replace(/\/+$/,""),n=String(e?.tokenEnv||"").trim(),r=parseInt(String(e?.webhookPort||"18810"),10);if(!t||!/^https?:\/\//.test(t))throw new Error("Host must start with http:// or https://");if(!n)throw new Error("Admin token env-var name is required (e.g. GITLAB_TOKEN).");if(!Number.isFinite(r)||r<1||r>65535)throw new Error("Webhook port must be between 1 and 65535.");let{summary:a}=D(s=>(s.channels=s.channels||{},s.channels.gitlab=s.channels.gitlab||{enabled:!1,routes:[],agentMappings:[]},s.channels.gitlab.enabled=!0,s.channels.gitlab.host=t,s.channels.gitlab.token="${"+n+"}",s.channels.gitlab.webhookPort=r,"configured gitlab connector"));return{summary:a,hint:`Add ${n}=<personal-access-token> to your .env. Per-project routes + per-agent tokens stay in the Advanced JSON editor.`}}function Xv(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.channels=r.channels||{},r.channels.gitlab=r.channels.gitlab||{enabled:!1,routes:[],agentMappings:[]},r.channels.gitlab.enabled=t,`gitlab ${t?"enabled":"disabled"}`));return{summary:n}}async function Kv(e){let t=String(e?.schedule||"").trim();if(!t)throw new Error("schedule is required");let{getNextCronDate:n}=await import("./scheduler-B52UIMKB.js"),r;try{r=(await import("cronstrue")).default.toString(t,{use24HourTimeFormat:!1})}catch(i){throw new Error(`Invalid cron: ${i.message||"unknown"}`)}let a=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",s=[],o=new Date;try{for(let i=0;i<3;i++)o=n(t,o,a),s.push(o.toISOString())}catch(i){throw new Error(`Cron preview failed: ${i.message}`)}return{human:r,next:s,timezone:a}}function Jv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Account id is required.");let{summary:n}=D(r=>{if(!r.channels?.telegram?.accounts?.[t])throw new Error(`Account "${t}" not found.`);return delete r.channels.telegram.accounts[t],`removed telegram account "${t}"`});return{summary:n}}function Yv(e){let t=!!e?.enabled,{summary:n}=D(r=>(r.channels=r.channels||{},r.channels.telegram=r.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},r.channels.telegram.enabled=t,`telegram ${t?"enabled":"disabled"}`));return{summary:n}}function Qv(e){let t=String(e?.id||"").trim(),n=String(e?.schedule||"").trim(),r=String(e?.agent||"").trim(),a=String(e?.prompt||"").trim();if(!/^[a-z0-9][a-z0-9_-]*$/.test(t))throw new Error("Cron id must be lowercase (letters, digits, -, _).");if(!n)throw new Error("Cron expression is required (e.g. '0 9 * * 1' for Mondays at 9am).");if(!r)throw new Error("Pick an agent to run this schedule.");if(!a)throw new Error("A prompt is required (what should the agent do?).");let{summary:s}=D(o=>{if(o.crons=o.crons||{},o.crons[t])throw new Error(`Cron "${t}" already exists.`);if(!o.agents?.[r])throw new Error(`Unknown agent "${r}".`);return o.crons[t]={schedule:n,agent:r,prompt:a,enabled:!0},`added cron "${t}"`});return{summary:s}}function Zv(e){let t=String(e?.id||"").trim();if(!t)throw new Error("Cron id is required.");let{summary:n}=D(r=>{if(!r.crons?.[t])throw new Error(`Cron "${t}" not found.`);return delete r.crons[t],`removed cron "${t}"`});return{summary:n}}function ey(){let e=ct();if(!e)return{exists:!1};let{config:t,hidden:n}=xp(e);return{exists:!0,raw:JSON.stringify(t,null,2),hidden:n}}function ty(e){let t=String(e?.raw||"");if(!t.trim())throw new Error("Config body is empty.");let n;try{n=JSON.parse(t)}catch(i){throw new Error(`Invalid JSON: ${i.message}`)}if(t.includes(Rt)){let i=null;try{i=ct()}catch{}n=vp(n,i)}let r=ci.safeParse(pi(n)),a=r.success?ui(r.data):[];if(a.length)throw new Error(a.join(" "));let s=Pt(process.cwd(),"agentx.json"),o=`${s}.bak.${Date.now()}`;if(ka(s))try{iv(s,o)}catch{}Op(s,JSON.stringify(n,null,2)+`
1770
- `,"utf-8");try{let l=ae().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";fetch(`${l}/reload`,{method:"POST"}).catch(()=>null)}catch{}return{summary:"agentx.json replaced",backupPath:o}}function Mp(e){return String(e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean).filter((t,n,r)=>r.indexOf(t)===n)}async function ny(e){let t=String(e?.agentId||"").trim(),n=String(e?.role||"").trim();if(!t)throw new Error("agentId required");if(!n)throw new Error("role required");let r=Array.isArray(e?.days)&&e.days.length>0?e.days:["mon","tue","wed","thu","fri"],a=String(e?.start||"09:00"),s=String(e?.end||"17:00"),o=e?.reportsTo?String(e.reportsTo).trim():"",i=typeof e?.utilizationTarget=="number"?e.utilizationTarget:.8,{summary:l}=D(d=>{d.business=d.business||{},d.business.orgChart=d.business.orgChart||{},d.business.orgChart[t]={role:n,...o?{reportsTo:o}:{},schedule:{days:r,start:a,end:s},utilizationTarget:i};let c=zo(d);if(c)throw new Error(c);return`orgChart "${t}" upserted`});return{summary:l}}async function ay(e){let t=String(e?.agentId||"").trim();if(!t)throw new Error("agentId required");let{summary:n}=D(r=>{if(!r.business?.orgChart||!(t in r.business.orgChart))throw new Error(`no orgChart entry for "${t}"`);return delete r.business.orgChart[t],`orgChart "${t}" removed`});return{summary:n}}async function ry(e){let t=String(e?.id||"").trim();if(!t)throw new Error("project id required");let n=e?.pm?String(e.pm).trim():"",r=e?.client?String(e.client).trim():"",a=e?.name?String(e.name).trim():"",s=e?.lead?String(e.lead).trim():"",o=[...new Set((Array.isArray(e?.team)?e.team:String(e?.team??"").split(/[\s,]+/)).map(d=>String(d).trim()).filter(Boolean).map(Wo))],i=new Set((Array.isArray(e?.clear)?e.clear:[]).map(String)),{summary:l}=D(d=>{d.business=d.business||{},d.business.projects=d.business.projects||[];let c=d.business.projects.findIndex(f=>f.id===t),p={...c>=0?d.business.projects[c]:{},id:t,...n?{pm:n}:{},...r?{client:r}:{}};for(let f of["name","lead","team"])i.has(f)&&delete p[f];a&&(p.name=a),s&&(p.lead=Bd(s)),o.length&&(p.team=o);let u=Fd(d,t,{lead:s,team:o});if(u)throw new Error(u);return c>=0?d.business.projects[c]=p:d.business.projects.push(p),c>=0?`project "${t}" updated`:`project "${t}" added`});return{summary:l}}async function sy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("client id required");let n=String(e?.kind||"").trim();if(n&&!["client","internal","own"].includes(n))throw new Error("kind must be client, internal or own");let r=String(e?.respondWithin||"").trim();if(r&&!/^\d+\s*[mhd]$/.test(r))throw new Error('respondWithin must look like "4h", "90m" or "2d"');let a=Array.isArray(e?.standing)?e.standing.map(o=>String(o).trim()).filter(Boolean):String(e?.standing||"").split(",").map(o=>o.trim()).filter(Boolean),{summary:s}=D(o=>{o.business=o.business||{},o.business.clients=o.business.clients||{};let i=!!o.business.clients[t];return o.business.clients[t]={...o.business.clients[t]||{},...e?.name?{name:String(e.name).trim()}:{},...n?{kind:n}:{},...r?{respondWithin:r}:{},standing:a},i?`client "${t}" updated`:`client "${t}" configured`});return{summary:s}}async function oy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("client id required");let{summary:n}=D(r=>{if(!r.business?.clients?.[t])throw new Error(`no client override "${t}"`);return delete r.business.clients[t],`client "${t}" reset to defaults`});return{summary:n}}async function iy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("project id required");let{summary:n}=D(r=>{let a=r.business?.projects||[],s=a.length;if(r.business.projects=a.filter(o=>o.id!==t),r.business.projects.length===s)throw new Error(`no project "${t}"`);return`project "${t}" removed`});return{summary:n}}async function ly(e){let t=String(e?.client||"").trim();if(!t)throw new Error("client required");if(!e?.chatId&&!e?.username&&!e?.senderId)throw new Error("one of chatId / username / senderId required");let{summary:n}=D(r=>{r.business=r.business||{},r.business.contactMap=r.business.contactMap||[];let a={client:t};e?.channel&&(a.channel=String(e.channel)),e?.chatId&&(a.chatId=String(e.chatId)),e?.username&&(a.username=String(e.username)),e?.senderId&&(a.senderId=String(e.senderId)),e?.project&&(a.project=String(e.project)),e?.displayName&&(a.displayName=String(e.displayName)),r.business.contactMap.push(a);let s=a.chatId||a.username||a.senderId;return`contact ${a.channel?a.channel+"/":""}${s} \u2192 ${t} added`});return{summary:n}}async function dy(e){let n=["channel","chatId","username","senderId"].filter(a=>e?.[a]);if(n.length===0)throw new Error("at least one filter (channel/chatId/username/senderId) required");let{summary:r}=D(a=>{let s=a.business?.contactMap||[],o=s.length;if(a.business.contactMap=s.filter(i=>{for(let l of n)if(i[l]!==e[l])return!0;return!1}),a.business.contactMap.length===o)throw new Error("no matching contact entry");return`${o-a.business.contactMap.length} contact entry/entries removed`});return{summary:r}}async function cy(e){let t=String(e?.id||"").trim(),n=String(e?.name||"").trim(),r=String(e?.projects||"").split(/[,\n]/).map(l=>l.trim()).filter(Boolean);if(!t)throw new Error("id required");if(!n)throw new Error("name required");if(r.length===0)throw new Error("at least one project path required");let a=e?.primaryToolLabel?String(e.primaryToolLabel).trim():"",s=Number.isFinite(Number(e?.timeRangeDays))?Number(e.timeRangeDays):30,o=Number.isFinite(Number(e?.closedWindowDays))?Number(e.closedWindowDays):30,{summary:i}=D(l=>{l.boards=Array.isArray(l.boards)?l.boards:[];let d=l.boards.findIndex(p=>p.id===t),c={id:t,name:n,source:{type:"gitlab",projects:r},timeRangeDays:s,closedWindowDays:o};if(a&&(c.primaryToolLabel=a),d>=0){let p=l.boards[d];return l.boards[d]={...p,...c,columns:p.columns,labels:p.labels},`board "${t}" updated`}return l.boards.push(c),`board "${t}" added`});return{summary:i}}async function py(e){let t=String(e?.id||"").trim();if(!t)throw new Error("id required");let{summary:n}=D(r=>{let a=Array.isArray(r.boards)?r.boards:[],s=a.length;if(r.boards=a.filter(o=>o.id!==t),r.boards.length===s)throw new Error(`board "${t}" not found`);return`board "${t}" removed`});return{summary:n}}async function uy(e){let t=String(e?.boardId||"").trim(),n=String(e?.columnId||"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"),r=String(e?.title||"").trim(),a=String(e?.kind||"scoped-label");if(!t)throw new Error("boardId required");if(!n)throw new Error("columnId required");if(!r)throw new Error("title required");if(!["open-backlog","scoped-label","closed","label"].includes(a))throw new Error("kind must be open-backlog | scoped-label | closed | label");let{summary:s}=D(o=>{let l=(Array.isArray(o.boards)?o.boards:[]).find(p=>p.id===t);if(!l)throw new Error(`board "${t}" not found`);l.columns=Array.isArray(l.columns)?l.columns:[];let d={id:n,title:r,kind:a,scopedPrefix:e?.scopedPrefix||"Status"};if(a==="scoped-label"){if(!e?.scopedLabel)throw new Error("scopedLabel required for kind=scoped-label");d.scopedLabel=String(e.scopedLabel)}if(a==="label"){if(!e?.mapsToLabel)throw new Error("mapsToLabel required for kind=label");d.mapsToLabel=String(e.mapsToLabel)}e?.accent&&(d.accent=String(e.accent));let c=l.columns.findIndex(p=>p.id===n);return c>=0?(l.columns[c]={...l.columns[c],...d},`column "${n}" updated`):(l.columns.push(d),`column "${n}" added to board "${t}"`)});return{summary:s}}async function fy(e){let t=String(e?.boardId||"").trim(),n=String(e?.columnId||"").trim();if(!t||!n)throw new Error("boardId and columnId required");let{summary:r}=D(a=>{let o=(Array.isArray(a.boards)?a.boards:[]).find(l=>l.id===t);if(!o)throw new Error(`board "${t}" not found`);let i=(o.columns||[]).length;if(o.columns=(o.columns||[]).filter(l=>l.id!==n),o.columns.length===i)throw new Error(`column "${n}" not found`);return`column "${n}" removed from board "${t}"`});return{summary:r}}async function hy(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),{actionSchema:n}=await import("./types-DO3KLIBS.js");if(!e||typeof e!="object")throw new Error("body required");let r=n.safeParse(e);if(!r.success){let s=r.error.issues[0];throw new Error(`${s.path.join(".")||"<root>"}: ${s.message}`)}let a=new t().save(r.data);return{summary:`action "${a.id}" saved (${a.kind})`,action:a}}async function gy(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),n=String(e?.id||"").trim();if(!n)throw new Error("id required");if(!new t().delete(n))throw new Error(`action "${n}" not found`);return{summary:`action "${n}" removed`}}async function my(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),{runAction:n}=await import("./runner-I4ZB37JE.js"),r=String(e?.id||"").trim();if(!r)throw new Error("id required");let a=new t().get(r);if(!a)throw new Error(`action "${r}" not found`);let s=e?.inputs&&typeof e.inputs=="object"?e.inputs:{},o=await n(a,s);return{summary:`action "${r}" ${o.ok?"ok":"failed"} (${o.durationMs}ms)`,result:o}}async function by(e){let t=e?.interval!==void 0?Number(e.interval):void 0,n=e?.timeout!==void 0?Number(e.timeout):void 0;if(t!==void 0&&(!Number.isFinite(t)||t<5||t>3600))throw new Error("interval must be 5..3600 seconds");if(n!==void 0&&(!Number.isFinite(n)||n<1||n>60))throw new Error("timeout must be 1..60 seconds");if(t===void 0&&n===void 0)throw new Error("nothing to update");let{summary:r}=D(a=>(a.mesh=a.mesh||{},a.mesh.healthCheck=a.mesh.healthCheck||{},t!==void 0&&(a.mesh.healthCheck.interval=t),n!==void 0&&(a.mesh.healthCheck.timeout=n),`mesh.healthCheck updated (interval=${a.mesh.healthCheck.interval}s, timeout=${a.mesh.healthCheck.timeout}s)`));return{summary:r}}function Np(e){let t=e?.wiki?.curator||{};return{enabled:t.enabled!==!1,agent:typeof t.agent=="string"?t.agent:""}}function wy(e){let{summary:t}=D(n=>{if(n.wiki=n.wiki||{},n.wiki.curator=n.wiki.curator||{},e&&"enabled"in e&&(n.wiki.curator.enabled=!!e.enabled),e&&"agent"in e){let a=String(e.agent||"").trim();if(!a)delete n.wiki.curator.agent;else if(n.agents?.[a])n.wiki.curator.agent=a;else throw new Error(`no agent "${a}"`)}let r=Np(n);return`wiki.curator ${r.enabled?"on":"off"}, answered by ${r.agent||"the page owner"}`});return{summary:t}}async function xy(e){let{summary:t}=D(n=>{n.notifications=n.notifications||{};let r=[];if(e&&typeof e=="object"){if("destination"in e)if(!e.destination)delete n.notifications.destination,r.push("destination cleared");else if(e.destination.channel&&e.destination.chatId)n.notifications.destination={channel:String(e.destination.channel),chatId:String(e.destination.chatId),...e.destination.accountId?{accountId:String(e.destination.accountId)}:{}},r.push(`destination=${e.destination.channel}:${e.destination.chatId}`);else throw new Error("destination requires channel + chatId");if("on"in e&&e.on&&typeof e.on=="object"){n.notifications.on=n.notifications.on||{};for(let a of["taskComplete","taskError","taskQueued"])a in e.on&&(n.notifications.on[a]=!!e.on[a]);r.push("on="+JSON.stringify(n.notifications.on))}if("longTaskThreshold"in e){let a=Number(e.longTaskThreshold);if(!Number.isFinite(a)||a<0)throw new Error("longTaskThreshold must be a non-negative number");n.notifications.longTaskThreshold=a,r.push(`threshold=${a}s`)}"local"in e&&e.local&&typeof e.local=="object"&&(n.notifications.local=ol(n.notifications.local,e.local),r.push("local="+JSON.stringify(n.notifications.local))),"ntfy"in e&&e.ntfy&&typeof e.ntfy=="object"&&(n.channels=n.channels||{},n.channels.ntfy=Hd(n.channels.ntfy,e.ntfy),r.push(`ntfy ${n.channels.ntfy.enabled?"on":"off"} (restart the daemon to apply)`))}if(r.length===0)throw new Error("nothing to update");return`notifications updated (${r.join(", ")})`});return{summary:t}}async function vy(e){if(!e||typeof e!="object")throw new Error("nothing to update");let t={};"enabled"in e&&(t.enabled=!!e.enabled),"inbox"in e&&(t.inbox=String(e.inbox??"")),"crons"in e&&(t.crons=Array.isArray(e.crons)?e.crons.map(String):String(e.crons??"").split(",")),"absorbAgent"in e&&(t.absorbAgent=String(e.absorbAgent??"")),"maxNotesPerRun"in e&&(t.maxNotesPerRun=Number(e.maxNotesPerRun)),"maxDeferrals"in e&&(t.maxDeferrals=Number(e.maxDeferrals));let{summary:n}=D(r=>Dd(r,t));return{summary:n}}async function yy(e){if(!e||typeof e!="object")throw new Error("nothing to update");let{summary:t}=D(n=>(n.screen=nd(n.screen,e),`screen updated (buffer ${n.screen.buffer?.enabled?"on":"off"})`));return{summary:t}}async function ky(e){let t=String(e?.id||"").trim();if(!t)throw new Error("webhook id required");let{summary:n}=D(r=>{let s=(Array.isArray(r.webhooks)?r.webhooks:[]).find(o=>o.id===t);if(!s)throw new Error(`webhook "${t}" not found`);if("triggers"in e){if(e.triggers===null||typeof e.triggers=="object"&&Object.keys(e.triggers).length===0)delete s.triggers;else if(typeof e.triggers=="object"){let o={};for(let[i,l]of Object.entries(e.triggers))typeof l=="string"&&l.trim()&&(o[String(i)]=l.trim());Object.keys(o).length===0?delete s.triggers:s.triggers=o}}return"defaultWorkflow"in e&&(e.defaultWorkflow?s.defaultWorkflow=String(e.defaultWorkflow).trim():delete s.defaultWorkflow),`webhook "${t}" triggers/defaultWorkflow updated`});return{summary:n}}Vt();import{resolve as Ay}from"path";function Dp(e={}){let t=e.localToken?`<script>window.AX_LOCAL_TOKEN = ${JSON.stringify(e.localToken)};</script>`:"",n=`<div id="msg" class="msg"></div>
1770
+ `,"utf-8");try{let l=ae().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";fetch(`${l}/reload`,{method:"POST"}).catch(()=>null)}catch{}return{summary:"agentx.json replaced",backupPath:o}}function Mp(e){return String(e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean).filter((t,n,r)=>r.indexOf(t)===n)}async function ny(e){let t=String(e?.agentId||"").trim(),n=String(e?.role||"").trim();if(!t)throw new Error("agentId required");if(!n)throw new Error("role required");let r=Array.isArray(e?.days)&&e.days.length>0?e.days:["mon","tue","wed","thu","fri"],a=String(e?.start||"09:00"),s=String(e?.end||"17:00"),o=e?.reportsTo?String(e.reportsTo).trim():"",i=typeof e?.utilizationTarget=="number"?e.utilizationTarget:.8,{summary:l}=D(d=>{d.business=d.business||{},d.business.orgChart=d.business.orgChart||{},d.business.orgChart[t]={role:n,...o?{reportsTo:o}:{},schedule:{days:r,start:a,end:s},utilizationTarget:i};let c=zo(d);if(c)throw new Error(c);return`orgChart "${t}" upserted`});return{summary:l}}async function ay(e){let t=String(e?.agentId||"").trim();if(!t)throw new Error("agentId required");let{summary:n}=D(r=>{if(!r.business?.orgChart||!(t in r.business.orgChart))throw new Error(`no orgChart entry for "${t}"`);return delete r.business.orgChart[t],`orgChart "${t}" removed`});return{summary:n}}async function ry(e){let t=String(e?.id||"").trim();if(!t)throw new Error("project id required");let n=e?.pm?String(e.pm).trim():"",r=e?.client?String(e.client).trim():"",a=e?.name?String(e.name).trim():"",s=e?.lead?String(e.lead).trim():"",o=[...new Set((Array.isArray(e?.team)?e.team:String(e?.team??"").split(/[\s,]+/)).map(d=>String(d).trim()).filter(Boolean).map(Wo))],i=new Set((Array.isArray(e?.clear)?e.clear:[]).map(String)),{summary:l}=D(d=>{d.business=d.business||{},d.business.projects=d.business.projects||[];let c=d.business.projects.findIndex(f=>f.id===t),p={...c>=0?d.business.projects[c]:{},id:t,...n?{pm:n}:{},...r?{client:r}:{}};for(let f of["name","lead","team"])i.has(f)&&delete p[f];a&&(p.name=a),s&&(p.lead=Bd(s)),o.length&&(p.team=o);let u=Fd(d,t,{lead:s,team:o});if(u)throw new Error(u);return c>=0?d.business.projects[c]=p:d.business.projects.push(p),c>=0?`project "${t}" updated`:`project "${t}" added`});return{summary:l}}async function sy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("client id required");let n=String(e?.kind||"").trim();if(n&&!["client","internal","own"].includes(n))throw new Error("kind must be client, internal or own");let r=String(e?.respondWithin||"").trim();if(r&&!/^\d+\s*[mhd]$/.test(r))throw new Error('respondWithin must look like "4h", "90m" or "2d"');let a=Array.isArray(e?.standing)?e.standing.map(o=>String(o).trim()).filter(Boolean):String(e?.standing||"").split(",").map(o=>o.trim()).filter(Boolean),{summary:s}=D(o=>{o.business=o.business||{},o.business.clients=o.business.clients||{};let i=!!o.business.clients[t];return o.business.clients[t]={...o.business.clients[t]||{},...e?.name?{name:String(e.name).trim()}:{},...n?{kind:n}:{},...r?{respondWithin:r}:{},standing:a},i?`client "${t}" updated`:`client "${t}" configured`});return{summary:s}}async function oy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("client id required");let{summary:n}=D(r=>{if(!r.business?.clients?.[t])throw new Error(`no client override "${t}"`);return delete r.business.clients[t],`client "${t}" reset to defaults`});return{summary:n}}async function iy(e){let t=String(e?.id||"").trim();if(!t)throw new Error("project id required");let{summary:n}=D(r=>{let a=r.business?.projects||[],s=a.length;if(r.business.projects=a.filter(o=>o.id!==t),r.business.projects.length===s)throw new Error(`no project "${t}"`);return`project "${t}" removed`});return{summary:n}}async function ly(e){let t=String(e?.client||"").trim();if(!t)throw new Error("client required");if(!e?.chatId&&!e?.username&&!e?.senderId)throw new Error("one of chatId / username / senderId required");let{summary:n}=D(r=>{r.business=r.business||{},r.business.contactMap=r.business.contactMap||[];let a={client:t};e?.channel&&(a.channel=String(e.channel)),e?.chatId&&(a.chatId=String(e.chatId)),e?.username&&(a.username=String(e.username)),e?.senderId&&(a.senderId=String(e.senderId)),e?.project&&(a.project=String(e.project)),e?.displayName&&(a.displayName=String(e.displayName)),r.business.contactMap.push(a);let s=a.chatId||a.username||a.senderId;return`contact ${a.channel?a.channel+"/":""}${s} \u2192 ${t} added`});return{summary:n}}async function dy(e){let n=["channel","chatId","username","senderId"].filter(a=>e?.[a]);if(n.length===0)throw new Error("at least one filter (channel/chatId/username/senderId) required");let{summary:r}=D(a=>{let s=a.business?.contactMap||[],o=s.length;if(a.business.contactMap=s.filter(i=>{for(let l of n)if(i[l]!==e[l])return!0;return!1}),a.business.contactMap.length===o)throw new Error("no matching contact entry");return`${o-a.business.contactMap.length} contact entry/entries removed`});return{summary:r}}async function cy(e){let t=String(e?.id||"").trim(),n=String(e?.name||"").trim(),r=String(e?.projects||"").split(/[,\n]/).map(l=>l.trim()).filter(Boolean);if(!t)throw new Error("id required");if(!n)throw new Error("name required");if(r.length===0)throw new Error("at least one project path required");let a=e?.primaryToolLabel?String(e.primaryToolLabel).trim():"",s=Number.isFinite(Number(e?.timeRangeDays))?Number(e.timeRangeDays):30,o=Number.isFinite(Number(e?.closedWindowDays))?Number(e.closedWindowDays):30,{summary:i}=D(l=>{l.boards=Array.isArray(l.boards)?l.boards:[];let d=l.boards.findIndex(p=>p.id===t),c={id:t,name:n,source:{type:"gitlab",projects:r},timeRangeDays:s,closedWindowDays:o};if(a&&(c.primaryToolLabel=a),d>=0){let p=l.boards[d];return l.boards[d]={...p,...c,columns:p.columns,labels:p.labels},`board "${t}" updated`}return l.boards.push(c),`board "${t}" added`});return{summary:i}}async function py(e){let t=String(e?.id||"").trim();if(!t)throw new Error("id required");let{summary:n}=D(r=>{let a=Array.isArray(r.boards)?r.boards:[],s=a.length;if(r.boards=a.filter(o=>o.id!==t),r.boards.length===s)throw new Error(`board "${t}" not found`);return`board "${t}" removed`});return{summary:n}}async function uy(e){let t=String(e?.boardId||"").trim(),n=String(e?.columnId||"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"),r=String(e?.title||"").trim(),a=String(e?.kind||"scoped-label");if(!t)throw new Error("boardId required");if(!n)throw new Error("columnId required");if(!r)throw new Error("title required");if(!["open-backlog","scoped-label","closed","label"].includes(a))throw new Error("kind must be open-backlog | scoped-label | closed | label");let{summary:s}=D(o=>{let l=(Array.isArray(o.boards)?o.boards:[]).find(p=>p.id===t);if(!l)throw new Error(`board "${t}" not found`);l.columns=Array.isArray(l.columns)?l.columns:[];let d={id:n,title:r,kind:a,scopedPrefix:e?.scopedPrefix||"Status"};if(a==="scoped-label"){if(!e?.scopedLabel)throw new Error("scopedLabel required for kind=scoped-label");d.scopedLabel=String(e.scopedLabel)}if(a==="label"){if(!e?.mapsToLabel)throw new Error("mapsToLabel required for kind=label");d.mapsToLabel=String(e.mapsToLabel)}e?.accent&&(d.accent=String(e.accent));let c=l.columns.findIndex(p=>p.id===n);return c>=0?(l.columns[c]={...l.columns[c],...d},`column "${n}" updated`):(l.columns.push(d),`column "${n}" added to board "${t}"`)});return{summary:s}}async function fy(e){let t=String(e?.boardId||"").trim(),n=String(e?.columnId||"").trim();if(!t||!n)throw new Error("boardId and columnId required");let{summary:r}=D(a=>{let o=(Array.isArray(a.boards)?a.boards:[]).find(l=>l.id===t);if(!o)throw new Error(`board "${t}" not found`);let i=(o.columns||[]).length;if(o.columns=(o.columns||[]).filter(l=>l.id!==n),o.columns.length===i)throw new Error(`column "${n}" not found`);return`column "${n}" removed from board "${t}"`});return{summary:r}}async function hy(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),{actionSchema:n}=await import("./types-DO3KLIBS.js");if(!e||typeof e!="object")throw new Error("body required");let r=n.safeParse(e);if(!r.success){let s=r.error.issues[0];throw new Error(`${s.path.join(".")||"<root>"}: ${s.message}`)}let a=new t().save(r.data);return{summary:`action "${a.id}" saved (${a.kind})`,action:a}}async function gy(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),n=String(e?.id||"").trim();if(!n)throw new Error("id required");if(!new t().delete(n))throw new Error(`action "${n}" not found`);return{summary:`action "${n}" removed`}}async function my(e){let{ActionStore:t}=await import("./store-TWQPEM5V.js"),{runAction:n}=await import("./runner-KWSARUS4.js"),r=String(e?.id||"").trim();if(!r)throw new Error("id required");let a=new t().get(r);if(!a)throw new Error(`action "${r}" not found`);let s=e?.inputs&&typeof e.inputs=="object"?e.inputs:{},o=await n(a,s);return{summary:`action "${r}" ${o.ok?"ok":"failed"} (${o.durationMs}ms)`,result:o}}async function by(e){let t=e?.interval!==void 0?Number(e.interval):void 0,n=e?.timeout!==void 0?Number(e.timeout):void 0;if(t!==void 0&&(!Number.isFinite(t)||t<5||t>3600))throw new Error("interval must be 5..3600 seconds");if(n!==void 0&&(!Number.isFinite(n)||n<1||n>60))throw new Error("timeout must be 1..60 seconds");if(t===void 0&&n===void 0)throw new Error("nothing to update");let{summary:r}=D(a=>(a.mesh=a.mesh||{},a.mesh.healthCheck=a.mesh.healthCheck||{},t!==void 0&&(a.mesh.healthCheck.interval=t),n!==void 0&&(a.mesh.healthCheck.timeout=n),`mesh.healthCheck updated (interval=${a.mesh.healthCheck.interval}s, timeout=${a.mesh.healthCheck.timeout}s)`));return{summary:r}}function Np(e){let t=e?.wiki?.curator||{};return{enabled:t.enabled!==!1,agent:typeof t.agent=="string"?t.agent:""}}function wy(e){let{summary:t}=D(n=>{if(n.wiki=n.wiki||{},n.wiki.curator=n.wiki.curator||{},e&&"enabled"in e&&(n.wiki.curator.enabled=!!e.enabled),e&&"agent"in e){let a=String(e.agent||"").trim();if(!a)delete n.wiki.curator.agent;else if(n.agents?.[a])n.wiki.curator.agent=a;else throw new Error(`no agent "${a}"`)}let r=Np(n);return`wiki.curator ${r.enabled?"on":"off"}, answered by ${r.agent||"the page owner"}`});return{summary:t}}async function xy(e){let{summary:t}=D(n=>{n.notifications=n.notifications||{};let r=[];if(e&&typeof e=="object"){if("destination"in e)if(!e.destination)delete n.notifications.destination,r.push("destination cleared");else if(e.destination.channel&&e.destination.chatId)n.notifications.destination={channel:String(e.destination.channel),chatId:String(e.destination.chatId),...e.destination.accountId?{accountId:String(e.destination.accountId)}:{}},r.push(`destination=${e.destination.channel}:${e.destination.chatId}`);else throw new Error("destination requires channel + chatId");if("on"in e&&e.on&&typeof e.on=="object"){n.notifications.on=n.notifications.on||{};for(let a of["taskComplete","taskError","taskQueued"])a in e.on&&(n.notifications.on[a]=!!e.on[a]);r.push("on="+JSON.stringify(n.notifications.on))}if("longTaskThreshold"in e){let a=Number(e.longTaskThreshold);if(!Number.isFinite(a)||a<0)throw new Error("longTaskThreshold must be a non-negative number");n.notifications.longTaskThreshold=a,r.push(`threshold=${a}s`)}"local"in e&&e.local&&typeof e.local=="object"&&(n.notifications.local=ol(n.notifications.local,e.local),r.push("local="+JSON.stringify(n.notifications.local))),"ntfy"in e&&e.ntfy&&typeof e.ntfy=="object"&&(n.channels=n.channels||{},n.channels.ntfy=Hd(n.channels.ntfy,e.ntfy),r.push(`ntfy ${n.channels.ntfy.enabled?"on":"off"} (restart the daemon to apply)`))}if(r.length===0)throw new Error("nothing to update");return`notifications updated (${r.join(", ")})`});return{summary:t}}async function vy(e){if(!e||typeof e!="object")throw new Error("nothing to update");let t={};"enabled"in e&&(t.enabled=!!e.enabled),"inbox"in e&&(t.inbox=String(e.inbox??"")),"crons"in e&&(t.crons=Array.isArray(e.crons)?e.crons.map(String):String(e.crons??"").split(",")),"absorbAgent"in e&&(t.absorbAgent=String(e.absorbAgent??"")),"maxNotesPerRun"in e&&(t.maxNotesPerRun=Number(e.maxNotesPerRun)),"maxDeferrals"in e&&(t.maxDeferrals=Number(e.maxDeferrals));let{summary:n}=D(r=>Dd(r,t));return{summary:n}}async function yy(e){if(!e||typeof e!="object")throw new Error("nothing to update");let{summary:t}=D(n=>(n.screen=nd(n.screen,e),`screen updated (buffer ${n.screen.buffer?.enabled?"on":"off"})`));return{summary:t}}async function ky(e){let t=String(e?.id||"").trim();if(!t)throw new Error("webhook id required");let{summary:n}=D(r=>{let s=(Array.isArray(r.webhooks)?r.webhooks:[]).find(o=>o.id===t);if(!s)throw new Error(`webhook "${t}" not found`);if("triggers"in e){if(e.triggers===null||typeof e.triggers=="object"&&Object.keys(e.triggers).length===0)delete s.triggers;else if(typeof e.triggers=="object"){let o={};for(let[i,l]of Object.entries(e.triggers))typeof l=="string"&&l.trim()&&(o[String(i)]=l.trim());Object.keys(o).length===0?delete s.triggers:s.triggers=o}}return"defaultWorkflow"in e&&(e.defaultWorkflow?s.defaultWorkflow=String(e.defaultWorkflow).trim():delete s.defaultWorkflow),`webhook "${t}" triggers/defaultWorkflow updated`});return{summary:n}}Vt();import{resolve as Ay}from"path";function Dp(e={}){let t=e.localToken?`<script>window.AX_LOCAL_TOKEN = ${JSON.stringify(e.localToken)};</script>`:"",n=`<div id="msg" class="msg"></div>
1771
1771
 
1772
1772
  <div id="disabled-banner" class="banner warn" style="display:none">
1773
1773
  <b>Graph is disabled.</b> Set <code class="mono">graph.enabled: true</code>
@@ -22968,4 +22968,4 @@ data: ${f.replace(/\n/g," ")}
22968
22968
  `)}catch{}}};o.stdout?.on("data",l),o.stderr?.on("data",l);let d=setInterval(()=>{try{t.write(`: hb
22969
22969
 
22970
22970
  `)}catch{}},15e3),c=()=>{clearInterval(d);try{o.kill()}catch{}try{t.end()}catch{}};e.on("close",c),o.on("exit",c),o.on("error",c)}async function aw(e,t,n,r){let a=n.url+r,s=(e.method||"GET").toUpperCase(),i=s!=="GET"&&s!=="HEAD"?await new Promise((p,u)=>{let f=[];e.on("data",g=>f.push(g)),e.on("end",()=>p(Buffer.concat(f))),e.on("error",u)}):void 0,l={},d=e.headers["content-type"];d&&(l["Content-Type"]=Array.isArray(d)?d[0]:d);let c=e.headers["x-requested-with"];c&&(l["X-Requested-With"]=Array.isArray(c)?c[0]:c),n.token&&(l.Authorization=`Bearer ${n.token}`),l["X-Agentx-Peer"]="primary";try{let p=await fetch(a,{method:s,headers:l,body:i&&i.length>0?i:void 0}),u=Buffer.from(await p.arrayBuffer());t.writeHead(p.status,{"Content-Type":p.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),t.end(u)}catch(p){C(t,502,{error:`proxy to peer failed: ${p?.message||p}`,target:a})}}function Ft(e,t){let n=e.replace(/\/+$/,""),r=(t.dashboard?.daemons||[]).find(a=>a.url.replace(/\/+$/,"")===n);return r?{url:To(r),token:r.dashboardToken||r.token}:null}export{u1 as RETIRED_PAGES,T1 as applyAttachSessions,ow as configNodeTargets,Vb as fetchDaemonAgents,f1 as handleBoardRequest,b1 as liveOverlaps,aD as resetLiveCaches,rD as resetWallFleetCaches,tt as resolveNodeTargets,nD as startBoardDashboard,A1 as withLastGood};
22971
- //# sourceMappingURL=board-dashboard-ZJLIP2L4.js.map
22971
+ //# sourceMappingURL=board-dashboard-QV7OD4SO.js.map
@@ -1,4 +1,4 @@
1
- import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-AX6CCD5P.js";import{b as co}from"./chunk-MEFPXHQJ.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as oo}from"./chunk-IH65GDJR.js";import{b as lo,d as Wn,e as po,f as st,i as mo}from"./chunk-NW7B53KD.js";import{a as Hn,b as uo}from"./chunk-J3SOEFRE.js";import{a as jn,b as go}from"./chunk-SIU6STB2.js";import{e as fo,i as ho,j as yo,k as wo}from"./chunk-X5C5W3E4.js";import{d as bo}from"./chunk-KWWBDLE6.js";import{f as xo,g as So}from"./chunk-HVMUYEQP.js";import{h as so,i as ro}from"./chunk-BE64IJWM.js";import{a as Ur,c as Fr}from"./chunk-MYVHVJWZ.js";import{a as Hr,b as jr,c as Wr,d as qr,l as Jr,q as zr}from"./chunk-74MHOALB.js";import{a as Gr,b as Kr}from"./chunk-LY4G7PCW.js";import{a as Qr,b as Zr}from"./chunk-DPG6VHPX.js";import{c as Xr}from"./chunk-BERWTVG2.js";import{a as Yr,b as Un}from"./chunk-A7JSRDJL.js";import{d as Vr}from"./chunk-Z5CMA4JN.js";import{b as no}from"./chunk-JMRFYGET.js";import{g as eo,h as to}from"./chunk-5QXRGX2F.js";import{c as br,d as xr}from"./chunk-AHWWJ7AF.js";import{c as Or,f as Lr}from"./chunk-JD5TCX4X.js";import{s as Er,v as Bt,w as Dr,y as Ie,z as Bn}from"./chunk-Y6KR7NXL.js";import{a as nt,b as He,f as Nt}from"./chunk-72SZI2UW.js";import{a as Fe,b as Dn}from"./chunk-FCPTN6NF.js";import{d as Br}from"./chunk-7IW25T4K.js";import{e as je,h as Nr,i as Ee}from"./chunk-QUFIUXMQ.js";import{e as Pe}from"./chunk-DSYKYZMT.js";import{Ba as vr,Cb as $r,Cc as Yc,Ea as Jc,Hb as Xc,Nb as Cr,Ob as Lt,Pb as Mr,Qb as tt,Rb as Rr,Sb as _r,Yb as Pr,ub as Ar,xb as Nn,zb as Qc}from"./chunk-VOVDWFFP.js";import{f as kr,g as et,h as Kc}from"./chunk-KEUW6YLL.js";import{j as Ln,r as zc}from"./chunk-N47Y5ADQ.js";import{a as Sr,b as fe,c as Tr,d as Ir,e as On}from"./chunk-VQRY4IDI.js";var Zc="[agentx:mid-turn",Wo="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",qo="Got it, I passed that on to the work in progress.";function qt(n,e,t){return`${n}\0${e}\0${t}`}var Vc=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function eu(n){return!!n&&!Vc.has(n)}function Go(n,e){return!eu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Wt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function tu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Zc} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
1
+ import{Da as Ho,Fa as jo,G as $o,N as Ht,O as Co,X as jt,Z as Mo,a as io,b as ao,d as Fn,f as We,i as To,j as Io,ja as Ro,k as Ut,ka as _o,la as Po,n as Ft,na as Eo,oa as Do,pa as Oo,q as ko,qa as Lo,r as vo,ta as No,ua as Bo,v as Ao,xa as Uo,ya as Fo}from"./chunk-FRYEUVYD.js";import{b as co}from"./chunk-MEFPXHQJ.js";import{a as qn}from"./chunk-W4YR2RO2.js";import{a as oo}from"./chunk-IH65GDJR.js";import{b as lo,d as Wn,e as po,f as st,i as mo}from"./chunk-NW7B53KD.js";import{a as Hn,b as uo}from"./chunk-J3SOEFRE.js";import{a as jn,b as go}from"./chunk-SIU6STB2.js";import{e as fo,i as ho,j as yo,k as wo}from"./chunk-X5C5W3E4.js";import{d as bo}from"./chunk-KWWBDLE6.js";import{f as xo,g as So}from"./chunk-HVMUYEQP.js";import{h as so,i as ro}from"./chunk-BE64IJWM.js";import{a as Ur,c as Fr}from"./chunk-MYVHVJWZ.js";import{a as Hr,b as jr,c as Wr,d as qr,l as Jr,q as zr}from"./chunk-74MHOALB.js";import{a as Gr,b as Kr}from"./chunk-LY4G7PCW.js";import{a as Qr,b as Zr}from"./chunk-DPG6VHPX.js";import{c as Xr}from"./chunk-BERWTVG2.js";import{a as Yr,b as Un}from"./chunk-A7JSRDJL.js";import{d as Vr}from"./chunk-Z5CMA4JN.js";import{b as no}from"./chunk-JMRFYGET.js";import{g as eo,h as to}from"./chunk-5QXRGX2F.js";import{c as br,d as xr}from"./chunk-AHWWJ7AF.js";import{c as Or,f as Lr}from"./chunk-JD5TCX4X.js";import{s as Er,v as Bt,w as Dr,y as Ie,z as Bn}from"./chunk-Y6KR7NXL.js";import{a as nt,b as He,f as Nt}from"./chunk-72SZI2UW.js";import{a as Fe,b as Dn}from"./chunk-FCPTN6NF.js";import{d as Br}from"./chunk-7IW25T4K.js";import{e as je,h as Nr,i as Ee}from"./chunk-QUFIUXMQ.js";import{e as Pe}from"./chunk-DSYKYZMT.js";import{Ba as vr,Cb as $r,Cc as Yc,Ea as Jc,Hb as Xc,Nb as Cr,Ob as Lt,Pb as Mr,Qb as tt,Rb as Rr,Sb as _r,Yb as Pr,ub as Ar,xb as Nn,zb as Qc}from"./chunk-VOVDWFFP.js";import{f as kr,g as et,h as Kc}from"./chunk-KEUW6YLL.js";import{j as Ln,r as zc}from"./chunk-N47Y5ADQ.js";import{a as Sr,b as fe,c as Tr,d as Ir,e as On}from"./chunk-VQRY4IDI.js";var Zc="[agentx:mid-turn",Wo="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",qo="Got it, I passed that on to the work in progress.";function qt(n,e,t){return`${n}\0${e}\0${t}`}var Vc=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function eu(n){return!!n&&!Vc.has(n)}function Go(n,e){return!eu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var Wt=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function tu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${Zc} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
2
2
  `)}function pf(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:tu(n)}}):""}Bn();Nt();var Gt="tool-set",Ko=["answer","code","full"],Jo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},nu=.1;function Qo(n){return{task:zo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:zo(n.agentPrompt,600)}:{}}}var Xo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Yo(n,e=nu){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Gn(s.answer),o=Gn(s.code),i=Gn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Zo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Jo.answer.includes(t))?"answer":e.every(t=>Jo.code.includes(t))?"code":"full"}function Vo(n,e){return Ko.indexOf(n)<Ko.indexOf(e)}function Gn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function zo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ei=!1;function ti(n,e){let t=Bt(Gt);if(t!=="off")return t==="active"&&!ei&&(ei=!0,e(`[decisions] seat "${Gt}" is set to active, but only shadow is built: it records and changes nothing`)),Ie(Gt,Qo(n),Xo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Yo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function ni(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Zo(r);Dr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Vo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function su(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function si(n,e){let t=su(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Kn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Bn();Nt();var ri="session-continuity",oi={continues:nt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:nt("Does the new request refer to something stated earlier in the conversation?")};function ii(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Jn(n.message,1200),previousRequest:n.previousMessage?Jn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Jn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function ai(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Jn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function di(n,e){let t=Br(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function kf(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=di(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function vf(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:di(n,e).token}var ci=null;function Af(n){ci=n}function Kt(n,e){let t;try{t=ci?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as en}from"execa";import{spawn as ru}from"node:child_process";import{createHash as ou}from"node:crypto";import{createInterface as iu}from"node:readline";var ke=class extends Error{},au=n=>ru("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),zn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),iu({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
3
3
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Qn=class{constructor(e=au,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=ou("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[P])=>x.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ke("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,P])=>!P.connection.busy);if(!x)throw new ke("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new zn(e,this.launchProcess)}}catch{throw new ke("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),I=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(I),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((w,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?w():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return U.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await U,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new ke(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(I),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ui=new Qn;import{execFile as Mu}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as Ci,readFileSync as Mi,rmSync as Ri}from"fs";import{join as Zt}from"path";import{tmpdir as _i}from"os";function Jt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function zt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Qt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var De=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var li=null;function rt(){return li}function Of(n){li=n}function he(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function du(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},gi=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=he(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=du(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new qe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new qe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=he(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=he(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=he(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as cu}from"child_process";import{randomUUID as uu}from"crypto";import{existsSync as lu,readFileSync as gu}from"fs";import{resolve as pu}from"path";function mu(n){let e=pu(n,"CLAUDE.md");if(!lu(e))return null;try{let t=gu(e,"utf8");return zr(t)}catch{return null}}var fu=20*60*1e3,hu=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function yu(n,e){return n.AGENTX_AGENT_ID=e.agentId,Kt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var pi=class{constructor(e={}){this.opts=e}spawn(e,t){return new Xn(e,t,this.opts)}},Xn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=cu(r,o,{cwd:t.workspace,env:Ee(yu({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:mu(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new De;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=uu(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
4
4
  `);let c=e.deadlineMs??fu,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new ot(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},hu);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
@@ -32,7 +32,7 @@ ${n}`}function _u(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
32
32
  `,l)}};w.stdout?.on("data",v=>{L+=j.write(v);let S=L.split(`
33
33
  `);L=S.pop()||"";for(let B of S)J(B)}),w.stderr?.on("data",v=>{N+=q.write(v)});let $=await w;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=vi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return I=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(P?.message||"")?vi():P?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(I)}}async function ju(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ve(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Wu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let I=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(I))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let I=n.provider||"claude-code",x=s?`${s}
34
34
 
35
- ${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-5FVRGDGM.js"),$="",v,S,B,W;for await(let E of J(M)){if(c)try{c(E)}catch{}if(E.type==="text_delta")$+=E.text,r(E.text,$);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}v=E.result.tokensUsed,E.result.inputTokens!=null&&(S=E.result.inputTokens),E.result.outputTokens!=null&&(B=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}E.result.tokensUsed!=null&&(v=E.result.tokensUsed)}else E.type==="error"&&(W=E.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-5FVRGDGM.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(I){return p?y():I?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${I.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var qu=1e3;async function Gu(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),qu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=ut(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&ts(e.agentId,n,e.model,s,"persistent");let h=ve(n,e,t),y="",I,x,P,U,w,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
35
+ ${e.message}`:e.message,P=e.context?.sender,U=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),w=e.context?.channel==="web-chat"&&U?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=qr(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:I,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Jr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-DXKDG4DQ.js"),$="",v,S,B,W;for await(let E of J(M)){if(c)try{c(E)}catch{}if(E.type==="text_delta")$+=E.text,r(E.text,$);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}v=E.result.tokensUsed,E.result.inputTokens!=null&&(S=E.result.inputTokens),E.result.outputTokens!=null&&(B=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==$){let Q=E.result.content.slice($.length);Q?($=E.result.content,r(Q,$)):$=E.result.content}E.result.tokensUsed!=null&&(v=E.result.tokensUsed)}else E.type==="error"&&(W=E.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-DXKDG4DQ.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(I){return p?y():I?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${I.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var qu=1e3;async function Gu(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),qu),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ku(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=ut(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&ts(e.agentId,n,e.model,s,"persistent");let h=ve(n,e,t),y="",I,x,P,U,w,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
36
36
  `)?`
37
37
 
38
38
  ${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");I=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(P={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(w=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Qt(S.modelUsage)||_}}}catch($){if(j)I="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)I=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);I=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);I=v.error,x=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!I&&(I="task cancelled by operator",x="cancelled"),{content:j?"":y,error:I,errorKind:x,duration:Date.now()-c,usage:P,contextTokens:U,numTurns:w,billedModel:_,claudeSessionId:R}}function Hi(n){let e=fe(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?wi(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Ii(t.args,n.taskId,n.agentId)}function Ju(n){return fe(n.autonomy)||!!n.personLimits}async function zu(n,e,t,s,r,o,i){let a=fe(e.autonomy)?e.autonomy:void 0,c=a&&bi(a,n.tier)||e.personLimits&&ki(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${Ir(a)}
@@ -189,4 +189,4 @@ ${Re}`),m+=Re.length}catch{}}}let Uc=Mn.length>0?Mn.join(`
189
189
 
190
190
  Agent: ${C.content}`,meta:rf(ee,e.context)})},ue=>this.log(ue)),Zr(e.agentId,e.message,C.content,{channel:b,chatId:T,sender:vn},this.memoryStore).catch(()=>{}),fa(e.agentId,e.message,C.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Ue=e.context?.channel,me=Ue&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ue}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,pe,Ue,me),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${O()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Jt(g.message);return se={content:"",error:zt(m),errorKind:m.kind},se}finally{if(yr.stop(),wr&&ce&&Ce)try{let g=se?.usage,m=No(Ce,ce,{error:se?se.error||void 0:R.signal.aborted?Be(R.signal).message:"run ended before completion",canceled:Bo(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Pn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Us(se),Hs(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?Zm(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Uo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||qm(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Km(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Ye,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of be(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let I=Math.floor((s-y)/36e5),x=t-1-I;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of be(e)){let r=G(e,s),o;try{o=be(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=be(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(xt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=sf){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of be(t)){let i=G(t,o),a;try{a=be(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Gm(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=be(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=be(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(xt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=be(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(xt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Ut(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=qn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){Qm.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=ut(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!Go(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(c=>c.channel===s&&c.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(qt(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(qt(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Cr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function gf(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
191
191
  `)}export{pf as a,di as b,kf as c,vf as d,Af as e,ui as f,Of as g,gi as h,mu as i,pi as j,Xt as k,Xf as l,eh as m,th as n,ih as o,ut as p,Lu as q,Ui as r,Hu as s,ju as t,Wu as u,ji as v,sn as w,zi as x,Bh as y,rn as z,pl as A,Wh as B,qh as C,Kh as D,an as E,Sl as F,Qh as G,cs as H,V as I,Sa as J,Fl as K,ql as L,ka as M,my as N,va as O,Pa as P,Cy as Q,My as R,Ba as S,Ry as T,Ua as U,pn as V,Uy as W,Fy as X,mt as Y,tp as Z,np as _,sp as $,rp as aa,op as ba,Ss as ca,yn as da,hw as ea,bn as fa,wn as ga,Ed as ha,ht as ia,Dd as ja,Iw as ka,kw as la,vw as ma,Aw as na,$w as oa,Cw as pa,Mw as qa,Np as ra,Kd as sa,Xe as ta,ic as ua,Ls as va,Ww as wa,Gw as xa,Kw as ya,Xm as za,Ym as Aa,kx as Ba,vx as Ca,Zm as Da,nf as Ea,rf as Fa,of as Ga,df as Ha,Ns as Ia,hc as Ja,yc as Ka,uf as La,wc as Ma,bc as Na,gf as Oa};
192
- //# sourceMappingURL=chunk-ZWD4ADV4.js.map
192
+ //# sourceMappingURL=chunk-575LJSX2.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-B5QQ4IH2.js";import{a as V}from"./chunk-IMLAPB7G.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{k as Be}from"./chunk-GO4J44UD.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-4UJDRI7W.js";import{ia as G}from"./chunk-AX6CCD5P.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-5BT4VPJC.js";import{s as ge,u as Oe}from"./chunk-3323WFVK.js";import{b as He}from"./chunk-JMRFYGET.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Cc as xe,J as le,Lb as Ee,M as F,S as Za,Sb as at,Va as ce,Wa as Pe,gb as et,nc as pe,rc as q,sc as Re}from"./chunk-VOVDWFFP.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
1
+ import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-RMB6G7X2.js";import{a as V}from"./chunk-IMLAPB7G.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{k as Be}from"./chunk-GO4J44UD.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-4UJDRI7W.js";import{ia as G}from"./chunk-FRYEUVYD.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-5BT4VPJC.js";import{s as ge,u as Oe}from"./chunk-3323WFVK.js";import{b as He}from"./chunk-JMRFYGET.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Cc as xe,J as le,Lb as Ee,M as F,S as Za,Sb as at,Va as ce,Wa as Pe,gb as et,nc as pe,rc as q,sc as Re}from"./chunk-VOVDWFFP.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2903,4 +2903,4 @@ tr:hover td { background: var(--bg-hover); }
2903
2903
  ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Ne/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${We(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
2904
2904
  `)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=Oe(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ge(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ge(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
2905
2905
  `)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:Le(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
2906
- //# sourceMappingURL=chunk-F6LT3DHK.js.map
2906
+ //# sourceMappingURL=chunk-AAPHOKWS.js.map