agentix-cli 0.153.0 → 0.153.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 (27) hide show
  1. package/dist/{board-dashboard-OZJSS6EM.js → board-dashboard-UZF7MQZA.js} +3 -3
  2. package/dist/{chunk-R4R7EYY3.js → chunk-BNOGNRAM.js} +2 -2
  3. package/dist/{chunk-P24P43ZB.js → chunk-DZRD6BE4.js} +2 -2
  4. package/dist/{chunk-SW6HCRLU.js → chunk-IFOFBI3U.js} +2 -2
  5. package/dist/chunk-LQS27HSV.js +6 -0
  6. package/dist/chunk-LQS27HSV.js.map +1 -0
  7. package/dist/{chunk-D6U37WO3.js → chunk-VAK4LT62.js} +2 -2
  8. package/dist/{chunk-IJQ2UUMZ.js → chunk-XQ2VU6MM.js} +3 -3
  9. package/dist/{chunk-MOCDP7Q3.js → chunk-ZAH74SFX.js} +2 -2
  10. package/dist/cli.js +1 -1
  11. package/dist/{doctor-UT32WKCP.js → doctor-QWVUVWTF.js} +2 -2
  12. package/dist/{grants-HSLB62EG.js → grants-YGA654NI.js} +2 -2
  13. package/dist/index.js +1 -1
  14. package/dist/{program-NU6QIXJJ.js → program-2YK3YCBX.js} +5 -5
  15. package/package.json +1 -1
  16. package/dist/chunk-24QMHUU2.js +0 -5
  17. package/dist/chunk-24QMHUU2.js.map +0 -1
  18. /package/dist/{board-dashboard-OZJSS6EM.js.map → board-dashboard-UZF7MQZA.js.map} +0 -0
  19. /package/dist/{chunk-R4R7EYY3.js.map → chunk-BNOGNRAM.js.map} +0 -0
  20. /package/dist/{chunk-P24P43ZB.js.map → chunk-DZRD6BE4.js.map} +0 -0
  21. /package/dist/{chunk-SW6HCRLU.js.map → chunk-IFOFBI3U.js.map} +0 -0
  22. /package/dist/{chunk-D6U37WO3.js.map → chunk-VAK4LT62.js.map} +0 -0
  23. /package/dist/{chunk-IJQ2UUMZ.js.map → chunk-XQ2VU6MM.js.map} +0 -0
  24. /package/dist/{chunk-MOCDP7Q3.js.map → chunk-ZAH74SFX.js.map} +0 -0
  25. /package/dist/{doctor-UT32WKCP.js.map → doctor-QWVUVWTF.js.map} +0 -0
  26. /package/dist/{grants-HSLB62EG.js.map → grants-YGA654NI.js.map} +0 -0
  27. /package/dist/{program-NU6QIXJJ.js.map → program-2YK3YCBX.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{A as xo,B as bo,C as vo,D as yo,H as wo,I as ko,M as Bt,N as To,O as Ao,P as Co,R as Io,S as Mo,a as oo,b as so,c as io,d as lo,j as co,k as po,l as uo,o as Ie,p as mo,q as fo,r as Ht,t as ho,z as go}from"./chunk-SW6HCRLU.js";import{a as _o}from"./chunk-5NTWGUSJ.js";import{a as So,b as Eo}from"./chunk-NZQBS7GN.js";import"./chunk-XVTD6I34.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as C}from"./chunk-CFPRIE6F.js";import{a as eo}from"./chunk-LNY6N73E.js";import{a as ro}from"./chunk-BKHIR2YJ.js";import{a as Ue,b as z,c as I,h as ue,i as Nt,j as se,k as K,l as Dt,m as to,n as ao,o as no}from"./chunk-B2QYMUTD.js";import{$a as Vr,Aa as Fr,B as Ct,C as Lr,Ca as Ur,D as ze,Da as Wr,E as Pr,Ea as Gr,F as It,G as Mt,H as Rt,I as $r,L as jr,M as Or,Ma as Xr,N as Nr,Oa as Ce,Ta as Kr,U,V as Dr,Va as Fe,W as Hr,Wa as Lt,Xa as Pt,Ya as $t,Za as jt,_a as Jr,a as br,ab as Yr,bb as Ot,c as St,d as Ia,db as Qr,e as vr,gb as Zr,i as Et,l as rt,n as yr,v as Rr}from"./chunk-D6U37WO3.js";import"./chunk-GTJIKXDB.js";import{h as gr,i as xr}from"./chunk-GDLO7FC7.js";import{D as wr,F as kr,a as mr,j as fr,k as hr}from"./chunk-MOCDP7Q3.js";import{a as H,b as Br,c as qr,g as zr}from"./chunk-7LN4VKDU.js";import{a as ur}from"./chunk-IMLAPB7G.js";import{g as At}from"./chunk-LQE73AZR.js";import{b as Cr,c as Ir}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import{o as Mr}from"./chunk-24QMHUU2.js";import"./chunk-3LU2ZQZJ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as G,c as Ae,d as _r,e as Ma}from"./chunk-EMGB23H5.js";import{a as Er,b as qe,d as Tr,e as Ar,f as Tt}from"./chunk-YMX3QCV7.js";import{b as Sr}from"./chunk-JWDJMFU6.js";import"./chunk-MNG2AMKZ.js";import"./chunk-ZQONMM3B.js";import"./chunk-KP7KDLZ2.js";import{F as cr,W as wt,X as kt,Y as _t,Z as pe,_ as pr,a as nr,f as rr,g as Aa,h as Ca,l as or,n as sr,o as ir,z as dr}from"./chunk-S5FRIHWM.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-AFRHKA7B.js";import"./chunk-5TTHN7DP.js";import"./chunk-LH3GOBZP.js";import{a as lr}from"./chunk-BFONYVOM.js";import"./chunk-3UOTLMXD.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-RUQMUDSX.js";import"./chunk-JPZBWHNZ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import{g as ar}from"./chunk-RJCHFDF3.js";import"./chunk-WPNRDEHW.js";import"./chunk-HVNWI63Z.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-JNG3P5V2.js";import"./chunk-7I7IEX4S.js";import{F as ka,Ja as Zn,K as Pc,Ka as er,L as _a,La as X,M as Sa,Ma as tr,T as $c,Ua as yt,_ as Kn,a as qn,b as zn,ba as Ea,c as Mc,ea as Jn,ga as vt,ha as Vn,ja as Yn,la as Qn,pa as Ta,x as gt,y as Rc}from"./chunk-5VPU5FHB.js";import{a as Fn,b as xt,c as wa,d as Un,h as Wn}from"./chunk-BRK6M6LA.js";import{d as Gn,e as Lc,f as bt,n as Xn}from"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function Ra(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function Ro(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:Ra(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var ie={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"/>'},Me=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",qt=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+Me(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function Lo(t={}){return I({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
1
+ import{A as xo,B as bo,C as vo,D as yo,H as wo,I as ko,M as Bt,N as To,O as Ao,P as Co,R as Io,S as Mo,a as oo,b as so,c as io,d as lo,j as co,k as po,l as uo,o as Ie,p as mo,q as fo,r as Ht,t as ho,z as go}from"./chunk-IFOFBI3U.js";import{a as _o}from"./chunk-5NTWGUSJ.js";import{a as So,b as Eo}from"./chunk-NZQBS7GN.js";import"./chunk-XVTD6I34.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as C}from"./chunk-CFPRIE6F.js";import{a as eo}from"./chunk-LNY6N73E.js";import{a as ro}from"./chunk-BKHIR2YJ.js";import{a as Ue,b as z,c as I,h as ue,i as Nt,j as se,k as K,l as Dt,m as to,n as ao,o as no}from"./chunk-B2QYMUTD.js";import{$a as Vr,Aa as Fr,B as Ct,C as Lr,Ca as Ur,D as ze,Da as Wr,E as Pr,Ea as Gr,F as It,G as Mt,H as Rt,I as $r,L as jr,M as Or,Ma as Xr,N as Nr,Oa as Ce,Ta as Kr,U,V as Dr,Va as Fe,W as Hr,Wa as Lt,Xa as Pt,Ya as $t,Za as jt,_a as Jr,a as br,ab as Yr,bb as Ot,c as St,d as Ia,db as Qr,e as vr,gb as Zr,i as Et,l as rt,n as yr,v as Rr}from"./chunk-VAK4LT62.js";import"./chunk-GTJIKXDB.js";import{h as gr,i as xr}from"./chunk-GDLO7FC7.js";import{D as wr,F as kr,a as mr,j as fr,k as hr}from"./chunk-ZAH74SFX.js";import{a as H,b as Br,c as qr,g as zr}from"./chunk-7LN4VKDU.js";import{a as ur}from"./chunk-IMLAPB7G.js";import{g as At}from"./chunk-LQE73AZR.js";import{b as Cr,c as Ir}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import{o as Mr}from"./chunk-LQS27HSV.js";import"./chunk-3LU2ZQZJ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as G,c as Ae,d as _r,e as Ma}from"./chunk-EMGB23H5.js";import{a as Er,b as qe,d as Tr,e as Ar,f as Tt}from"./chunk-YMX3QCV7.js";import{b as Sr}from"./chunk-JWDJMFU6.js";import"./chunk-MNG2AMKZ.js";import"./chunk-ZQONMM3B.js";import"./chunk-KP7KDLZ2.js";import{F as cr,W as wt,X as kt,Y as _t,Z as pe,_ as pr,a as nr,f as rr,g as Aa,h as Ca,l as or,n as sr,o as ir,z as dr}from"./chunk-S5FRIHWM.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-AFRHKA7B.js";import"./chunk-5TTHN7DP.js";import"./chunk-LH3GOBZP.js";import{a as lr}from"./chunk-BFONYVOM.js";import"./chunk-3UOTLMXD.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-RUQMUDSX.js";import"./chunk-JPZBWHNZ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import{g as ar}from"./chunk-RJCHFDF3.js";import"./chunk-WPNRDEHW.js";import"./chunk-HVNWI63Z.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-JNG3P5V2.js";import"./chunk-7I7IEX4S.js";import{F as ka,Ja as Zn,K as Pc,Ka as er,L as _a,La as X,M as Sa,Ma as tr,T as $c,Ua as yt,_ as Kn,a as qn,b as zn,ba as Ea,c as Mc,ea as Jn,ga as vt,ha as Vn,ja as Yn,la as Qn,pa as Ta,x as gt,y as Rc}from"./chunk-5VPU5FHB.js";import{a as Fn,b as xt,c as wa,d as Un,h as Wn}from"./chunk-BRK6M6LA.js";import{d as Gn,e as Lc,f as bt,n as Xn}from"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function Ra(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function Ro(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:Ra(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var ie={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"/>'},Me=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",qt=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+Me(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function Lo(t={}){return I({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
2
2
 
3
3
  <div class="bf-head">
4
4
  <div>
@@ -21249,7 +21249,7 @@ main h2 { font-size: 20px; margin: 4px 0 8px; }
21249
21249
  Live dashboard: http://${g}:${n}
21250
21250
  `),console.log(" (no boards configured \u2014 '/' serves the live view; add a board with 'agentx board add')")):(console.log(`
21251
21251
  Kanban dashboard: http://${g}:${n}
21252
- `),console.log(` Boards: ${a.map(k=>k.id).join(", ")}`)),r==="127.0.0.1"&&!o?console.log(" (bound to localhost; no auth token \u2014 safe default)"):r!=="127.0.0.1"&&!o&&console.log(" \u26A0 bound to a non-loopback address without a token \u2014 writes are UNAUTHENTICATED")})}var xg=new Set(["/","/live","/mesh","/monitor","/activity","/boards","/glossary","/workflows","/workflows/editor","/procedures","/processes","/graph","/setup","/admin","/admin/graph","/approvals","/people","/places","/admin/health","/admin/observability","/admin/ledger","/admin/cost","/admin/projects","/admin/wiki"]);async function bg(t,e,a){let n=new URL(t.url||"/","http://localhost"),r=n.pathname,o=(t.method||"GET").toUpperCase();if((t.url||"/").split(/[?#]/)[0]!==r){w(e,404,{error:"not found"});return}if(Dr(t.headers)==="foreign"&&Hr(o)){w(e,403,{error:"Forbidden: request from a page on another origin"});return}if(o==="OPTIONS"){e.writeHead(204),e.end();return}if(await As(t,e,r,o,{nodeName:a.config.node?.name,root:process.cwd(),people:()=>st(a.config.people),members:vc(a.config.members.logRetentionDays),db:()=>tt(),linkFor:(u,f)=>Jo(u,f,{gitlab:a.config.channels.gitlab?.host})})||await dc(t,e,r,o,{nodeName:a.config.node?.name,fleet:Dn(a.config),desk:Dg(a.config),push:Nn(a.config),announce:Sl(a.config),chat:Sc(a.config),voice:qg(a.config),camera:zg(a.config),places:bc(a.config),pins:co(a.config,process.cwd()),assetLinks:()=>id(a.config)}))return;let s=o==="GET"?Go(r):null;if(s){e.writeHead(200,{"Content-Type":s.type,"Cache-Control":"public, max-age=86400"}),e.end(s.body);return}if(o==="GET"&&xg.has(r)&&_o("page",r),o==="GET"&&r==="/"){let u=oo();if(!u.configExists||u.agentCount===0){e.writeHead(302,{Location:"/setup"}),e.end();return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(un({peers:D(a.config)}));return}if(o==="GET"&&r==="/boards"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(pl({peers:D(a.config)}));return}if(o==="GET"&&r==="/live"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(un({peers:D(a.config)}));return}if(o==="POST"&&r.match(/^\/webhook\/n8n\/[A-Za-z0-9._:-]{1,64}$/)){try{let[u]=await Te(a.config);if(!u){w(e,503,{error:"no node available"});return}let f=await new Promise(y=>{let E="";t.on("data",x=>E+=x),t.on("end",()=>y(E)),t.on("error",()=>y(""))}),v=await fetch(u.url+r,{method:"POST",headers:{"Content-Type":"application/json",...u.token?{Authorization:`Bearer ${u.token}`}:{}},body:f||"{}"});e.writeHead(v.status,{"Content-Type":"application/json"}),e.end(await v.text())}catch(u){w(e,502,{error:"could not reach the node",message:String(u?.message||u)})}return}if(r==="/api/assistant"||r.startsWith("/api/assistant/")){try{let u=await Te(a.config),f=o==="POST"?void 0:n.searchParams.get("node"),v=o==="POST"?await re(t):void 0,y=v?.node??f,E=y?u.find(L=>L.url===y):u[0];if(!E){w(e,400,{error:"unknown node"});return}let x=n.search?n.search.replace(/([?&])node=[^&]*/,"$1").replace(/[?&]$/,""):"",A=await fetch(E.url+r+x,{method:o,headers:{"Content-Type":"application/json",...E.token?{Authorization:`Bearer ${E.token}`}:{}},...o==="POST"?{body:JSON.stringify({...v,node:void 0})}:{}});w(e,A.status,await A.json().catch(()=>({error:`HTTP ${A.status}`})))}catch(u){w(e,502,{error:"could not reach the node",message:u?.message||String(u)})}return}if(o==="POST"&&r==="/api/workflows/editor/chat"){try{let u=await re(t),f={"Content-Type":"application/json"};a.config.dashboard.token&&(f.Authorization=`Bearer ${a.config.dashboard.token}`);let v=a.config.dashboard.daemonUrl.replace(/\/+$/,""),y=await fetch(`${v}/api/workflows/editor/chat`,{method:"POST",headers:f,body:JSON.stringify(u??{})}),E=await y.json().catch(()=>({error:`HTTP ${y.status}`}));w(e,y.status,E)}catch(u){w(e,502,{error:"daemon unreachable",message:u.message||String(u)})}return}if(o==="GET"&&r==="/api/n8n/workflows"){try{let[u]=await Te(a.config);if(!u){w(e,200,{configured:!1,workflows:[]});return}let f=await fetch(u.url+"/api/n8n/workflows",{headers:u.token?{Authorization:`Bearer ${u.token}`}:{}});w(e,f.status,await f.json().catch(()=>({configured:!1,workflows:[]})))}catch{w(e,200,{configured:!1,workflows:[]})}return}if(o==="GET"&&r==="/workflows/editor"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(No({peers:D(a.config)}));return}if(o==="GET"&&r==="/activity"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(Oo({peers:D(a.config),view:n.searchParams.get("view")}));return}if(o==="GET"&&r==="/monitor"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(Lo({peers:D(a.config)}));return}if(r==="/api/monitor"||r.startsWith("/api/monitor/")){let u=new AbortController,f=setTimeout(()=>u.abort(),8e3);try{let v=xr(await Te(a.config,u.signal),a.config.mesh.peers);if(o==="GET"&&r==="/api/monitor"){let L=await Promise.all(v.map(async _=>{try{let R=await fetch(_.url+"/monitor",{headers:_.token?{Authorization:`Bearer ${_.token}`}:{},signal:u.signal});if(!R.ok)throw new Error(`HTTP ${R.status}`);return{name:_.name,url:_.url,ok:!0,data:await R.json()}}catch(R){return{name:_.name,url:_.url,ok:!1,error:R.message}}}));w(e,200,{nodes:L});return}let y=v.find(L=>L.url===n.searchParams.get("node"));if(!y){w(e,400,{error:"Select a known node"});return}let E=r.slice(13);if(!(o==="GET"&&["discover","actions","activity"].includes(E)||o==="POST"&&["register","ended","action","retry","clear"].includes(E))){w(e,405,{error:"Unknown monitor operation"});return}let x=o==="POST"?JSON.stringify(await gr(t)):void 0,A=await fetch(y.url+"/monitor/"+E+(E==="actions"?"?offset="+encodeURIComponent(n.searchParams.get("offset")||"0"):E==="activity"?"?hours="+encodeURIComponent(n.searchParams.get("hours")||"24"):""),{method:o,body:x,signal:u.signal,headers:{"Content-Type":"application/json",...y.token?{Authorization:`Bearer ${y.token}`}:{}}});w(e,A.status,await A.json())}catch(v){w(e,502,{error:v.message})}finally{clearTimeout(f)}return}if(o==="GET"&&r==="/mesh"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(sl({peers:D(a.config)}));return}if(o==="GET"&&r==="/places"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(cc({peers:D(a.config)}));return}if(o==="GET"&&r==="/guests"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(il({peers:D(a.config)}));return}if(o==="GET"&&r==="/api/guests"||o==="POST"&&/^\/api\/guests\/[^/]+\/(pause|resume|end|update)$/.test(r)){try{let u={"Content-Type":"application/json"};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=a.config.dashboard.daemonUrl.replace(/\/+$/,""),v=o==="POST"?await re(t).catch(()=>({})):void 0,y=await fetch(`${f}${r.replace(/^\/api\/guests/,"/mesh/guests")}`,{method:o,headers:u,...v!==void 0?{body:JSON.stringify(v??{})}:{}});w(e,y.status,await y.json().catch(()=>({error:`HTTP ${y.status}`})))}catch(u){w(e,502,{error:"daemon unreachable",message:u.message||String(u)})}return}if(o==="GET"&&r==="/glossary"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ul({peers:D(a.config)}));return}if(o==="GET"&&r==="/workflows"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ml({peers:D(a.config)}));return}if(o==="GET"&&r==="/procedures"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(fl({peers:D(a.config)}));return}if(o==="GET"&&r==="/processes"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ro({}));return}let l=o==="GET"&&r.match(/^\/tasks\/([^/]+)$/);if(l){let u=n.searchParams.get("agent")||"",f=n.searchParams.get("node")||a.config.dashboard.daemonUrl;if(!u){e.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),e.end("<p>Missing <code>?agent=</code>. Open this task from the Live page.</p>");return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(hl({taskId:decodeURIComponent(l[1]),agentId:u,agentName:n.searchParams.get("name")||void 0,channel:n.searchParams.get("channel")||void 0,archived:n.searchParams.get("archived")==="1",ask:n.searchParams.get("ask")||void 0,askAt:n.searchParams.get("at")||void 0,nodeUrl:f,peers:D(a.config)}));return}let d=o==="GET"&&r.match(/^\/agents\/([^/]+)\/history$/);if(d){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(gl({agentId:decodeURIComponent(d[1]),agentName:n.searchParams.get("name")||void 0,nodeUrl:n.searchParams.get("node")||a.config.dashboard.daemonUrl,peers:D(a.config)}));return}if(o==="GET"&&r==="/graph"){e.writeHead(302,{Location:"/admin/graph"}),e.end();return}if(o==="GET"&&r==="/setup"){so(t,e);return}if(o==="POST"&&r==="/api/setup"){await io(t,e);return}if(o==="POST"&&r==="/api/setup/start-daemon"){await lo(t,e);return}if(o==="GET"&&r==="/admin"){Ds(t,e,D(a.config),a.token);return}if(o==="GET"&&r==="/approvals"){ei(e,D(a.config),a.token);return}if(o==="GET"&&r==="/admin/graph"){Gs(t,e,D(a.config),a.token);return}if(o==="GET"&&(r==="/admin/health"||r==="/admin/observability")){if(r==="/admin/observability"){e.writeHead(302,{Location:"/admin/health"}),e.end();return}ci(t,e,D(a.config));return}if(r.startsWith("/api/admin/")||r.startsWith("/api/workflows")||r.startsWith("/api/agents")){let u=n.searchParams.get("peer")==="fleet"?"fleet":String(t.headers["x-agentx-peer"]||"").trim()||n.searchParams.get("peer")||"";if(u==="fleet"){if(r==="/api/admin/activity-graph"){await Kg(t,e,a);return}if(r==="/api/admin/activity-graph/stream"){await cn(t,e,r,v=>Tc(v,a.config));return}let f=r.match(/^\/api\/admin\/activity-graph\/dispatch\/(.+)$/);if(f){let v=decodeURIComponent(f[1]),y=v.indexOf("::");if(y>0){let E=v.slice(0,y),x=v.slice(y+2),A=a.config.node?.id||a.config.node?.name||"local";if(E===A)t.url=`/api/admin/activity-graph/dispatch/${encodeURIComponent(x)}`;else{let L=(a.config.dashboard?.daemons||[]).find(_=>(_.name||_.url)===E);if(L){let _=ft(L.url.replace(/\/+$/,""),a.config);if(_){await wc(t,e,_,`/api/admin/activity-graph/dispatch/${encodeURIComponent(x)}`);return}}w(e,404,{error:`unknown node "${E}" in fleet dispatch id`});return}}}}else if(u&&u!=="primary"){let f=ft(u,a.config);if(!f){w(e,404,{error:`unknown peer: ${u}`});return}let v=(n.search||"").replace(/[?&]peer=[^&]*/g,E=>E.startsWith("?")?"?":"");await wc(t,e,f,r+(v==="?"?"":v));return}}if(o==="GET"&&r.startsWith("/api/admin/observability/")&&await pi(t,e,r))return;if(o==="GET"&&r==="/api/admin/logs/stream"){await Jg(t,e);return}if(o==="GET"&&r==="/api/admin/doctor"){try{let{runDoctorChecks:u}=await import("./doctor-UT32WKCP.js"),v=new URL(t.url||"/","http://_").searchParams.get("running")!=="false",y=await u({running:v});w(e,200,y)}catch(u){w(e,500,{error:u?.message||String(u)})}return}if(o==="GET"&&r==="/admin/ledger"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(hi({peers:D(a.config)}));return}if(o==="GET"&&r.startsWith("/api/admin/ledger/")&&await fi(t,e,r))return;if(o==="GET"&&r==="/admin/cost"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(gi({peers:D(a.config)}));return}if(o==="GET"&&r==="/admin/projects"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(xi({peers:D(a.config)}));return}if(o==="GET"&&(r==="/admin/wiki"||r.startsWith("/admin/wiki/"))){if(r==="/admin/wiki"){e.writeHead(302,{Location:"/admin/wiki/"}),e.end();return}await Eg(a)(t,e);return}if(o==="GET"&&r==="/admin/activity-graph"){e.writeHead(302,{Location:"/activity?view=map"}),e.end();return}if(o==="GET"&&r==="/api/admin/activity-graph"&&await Bi(t,e,r)||o==="GET"&&r.startsWith("/api/admin/activity-graph/stream")&&await cn(t,e,r)||o==="GET"&&r.startsWith("/api/admin/activity-graph/dispatch/")&&await zi(t,e,r))return;let p=o==="GET"&&r.match(/^\/admin\/agents\/([a-z0-9][a-z0-9_-]*)$/);if(p){Wi(t,e,p[1],D(a.config),a.token);return}if(r.startsWith("/api/admin/")&&a.token){let u=t.headers.authorization||"",f=u.startsWith("Bearer ")?u.slice(7):"";if(f!==a.token){let v=new G,y=f?v.verify(f):null;if(!y||!Ae(y,"dashboard:write")){w(e,401,{error:"unauthorized"});return}}}if(o==="GET"&&r==="/api/admin/config"){await Hs(t,e);return}if(o==="GET"&&r==="/api/admin/voice-health"){w(e,200,Fr()??{checkedAt:null,missing:[]});return}if(r.startsWith("/api/admin/approvals")){await ti(t,e,r,n);return}if(await ni(t,e,r,{people:()=>st(a.config.people),members:vc(a.config.members.logRetentionDays),root:process.cwd(),db:()=>tt(),peers:D(a.config),localToken:a.token}))return;if(r.startsWith("/api/admin/graph/")){await Xs(t,e,r);return}if(r.startsWith("/api/admin/agent/")){await Gi(t,e,r);return}if(r.startsWith("/api/admin/")){await Bs(t,e,r);return}if(o==="GET"&&r==="/sortable.min.js"){e.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"public, max-age=86400"}),e.end(Cs);return}if(o==="GET"&&r.startsWith("/assets/")){let u=r.slice(8);if(!/^[a-zA-Z0-9._-]+\.(js|map|css)$/.test(u)){w(e,400,{error:"invalid asset name"});return}let f=Gg("web/"+u);try{let v=await Xg(f),y=u.endsWith(".map")?"application/json; charset=utf-8":u.endsWith(".css")?"text/css; charset=utf-8":"application/javascript; charset=utf-8",E=n.searchParams.has("v");e.writeHead(200,{"Content-Type":y,"Cache-Control":E?"public, max-age=31536000, immutable":"public, max-age=60"}),e.end(v)}catch{w(e,404,{error:"asset not found",hint:"run: npm run build:web"})}return}if(o==="GET"&&r==="/api/live"){try{let u=await at(a.config);w(e,200,u)}catch(u){w(e,502,{error:u.message})}return}if(o==="GET"&&r==="/api/mesh"){try{let u=n.searchParams.get("date")||new Date().toISOString().slice(0,10),f=n.searchParams.get("timezone")||"UTC",v=await at(a.config,{date:u,timezone:f});w(e,200,v)}catch(u){w(e,502,{error:u.message})}return}if(o==="GET"&&r==="/api/mesh/analytics"){let u=(f,v,y,E)=>{let x=parseInt(n.searchParams.get(f)||"",10);return Number.isFinite(x)?Math.max(y,Math.min(E,x)):v};try{let f=await Te(a.config);w(e,200,await ll(f,{days:u("days",30,0,180),tzOffsetMinutes:u("tzOffset",0,-840,840),limit:u("limit",60,1,200)}))}catch(f){w(e,502,{error:f.message})}return}if(o==="GET"&&r==="/api/mesh/day"){let u=n.searchParams.get("day")||"";if(!/^\d{4}-\d{2}-\d{2}$/.test(u)){w(e,400,{error:"day=YYYY-MM-DD query param required"});return}let f=(v,y,E,x)=>{let A=parseInt(n.searchParams.get(v)||"",10);return Number.isFinite(A)?Math.max(E,Math.min(x,A)):y};try{let v=await Te(a.config);w(e,200,await cl(v,{day:u,tzOffsetMinutes:f("tzOffset",0,-840,840),limit:f("limit",40,1,200)}))}catch(v){w(e,502,{error:v.message})}return}if(o==="GET"&&(r==="/api/mesh/thread"||r==="/api/mesh/job"||r==="/api/mesh/run"||r==="/api/mesh/conversation")){let u=n.searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}let f=n.searchParams,v;if(r==="/api/mesh/thread"){let[y,E,x]=[f.get("agent"),f.get("channel"),f.get("chat")];if(!y||!E||!x){w(e,400,{error:"agent, channel, chat required"});return}v=`/analytics/thread?agent=${encodeURIComponent(y)}&channel=${encodeURIComponent(E)}&chat=${encodeURIComponent(x)}&limit=${encodeURIComponent(f.get("limit")||"120")}`}else if(r==="/api/mesh/job"){let[y,E]=[f.get("kind"),f.get("key")];if(!y||!E){w(e,400,{error:"kind and key required"});return}v=`/analytics/job?kind=${encodeURIComponent(y)}&key=${encodeURIComponent(E)}&limit=${encodeURIComponent(f.get("limit")||"120")}`}else if(r==="/api/mesh/conversation"){let[y,E,x]=[f.get("agent"),f.get("channel"),f.get("chat")];if(!y||!E||!x){w(e,400,{error:"agent, channel, chat required"});return}v=`/analytics/conversation?agent=${encodeURIComponent(y)}&channel=${encodeURIComponent(E)}&chat=${encodeURIComponent(x)}&tzOffset=${encodeURIComponent(f.get("tzOffset")||"0")}`}else{let y=f.get("task");if(!y){w(e,400,{error:"task required"});return}v=`/analytics/run/${encodeURIComponent(y)}`}try{await dl(e,await Te(a.config),u,v)}catch(y){w(e,502,{error:y.message})}return}if(o==="GET"&&r==="/api/live/stream"){Lg(t,e,a.config);return}if(o==="GET"&&r==="/api/task/stream"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("agent"),y=u.searchParams.get("task");if(!f||!v||!y){w(e,400,{error:"node, agent, task query params required"});return}await Pg(t,e,a,f,v,y);return}if(o==="GET"&&r==="/api/task/history"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("agent"),y=u.searchParams.get("task"),E=u.searchParams.get("limit")||"50";if(!f||!v){w(e,400,{error:"node and agent query params required"});return}await Og(e,a,f,v,y,E);return}if(o==="POST"&&r==="/api/task/action"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("task"),y=u.searchParams.get("kind");if(!f||!v||y!=="cancel"&&y!=="followup"){w(e,400,{error:"node, task, kind=cancel|followup query params required"});return}await Ng(t,e,a,f,v,y);return}if(o==="POST"&&r==="/api/voice/stop"){let u=new URL(t.url||"/","http://localhost").searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,"/voice/stop");return}if(o==="GET"&&r==="/api/agents"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/agents",{headers:u});if(!f.ok)throw new Error(`HTTP ${f.status}`);let v=await f.json();w(e,200,v)}catch(u){w(e,502,{error:u.message||"agents fetch failed"})}return}if(o==="GET"&&r==="/api/business/status"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/business/status",{headers:u});if(!f.ok){w(e,f.status,{error:`HTTP ${f.status}`});return}w(e,200,await f.json())}catch(u){w(e,502,{error:u.message||"business status fetch failed"})}return}if(o==="POST"&&r==="/api/draft"){let u=await re(t);try{let f=await Ug(a.config,u);w(e,200,f)}catch(f){w(e,502,{error:f.message||"draft failed"})}return}let c=r.match(/^\/api\/public\/agents\/([^/]+)\/messages$/);if(c&&o==="POST"){let u=c[1];if(!$g(t,e,[`agent:${u}`]))return;await jg(t,e,a.config,u);return}if(o==="GET"&&r==="/api/node/build"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/health",{headers:u,signal:AbortSignal.timeout(3e3)});if(!f.ok)throw new Error(`HTTP ${f.status}`);w(e,200,zr(await f.json()))}catch(u){w(e,502,{error:u.message||"daemon not reachable"})}return}if(r.startsWith("/api/")&&a.token){let u=t.headers.authorization||"",f=u.startsWith("Bearer ")?u.slice(7):"";if(f!==a.token){let v=new G,y=f?v.verify(f):null;if(!y||!Ae(y,"dashboard:write")){w(e,401,{error:"unauthorized"});return}}}if(o==="GET"&&r==="/api/mesh/feed"){await Tg(e,a.config,n.searchParams);return}if((o==="POST"||o==="PATCH"||o==="DELETE"||o==="PUT")&&r.startsWith("/api/")&&t.headers["x-requested-with"]!=="agentx-board"){w(e,400,{error:"missing X-Requested-With: agentx-board"});return}if(r==="/api/wiki/curate"||r==="/api/wiki/curate/restore"){try{let u={"Content-Type":"application/json"};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=a.config.dashboard.daemonUrl.replace(/\/+$/,""),v=o==="POST"?JSON.stringify(await re(t)??{}):void 0,y=await fetch(`${f}${r}${n.search}`,{method:o,headers:u,...v?{body:v}:{}});w(e,y.status,await y.json().catch(()=>({error:`HTTP ${y.status}`})))}catch(u){w(e,502,{error:"daemon unreachable",message:u?.message||String(u)})}return}if(await rd(t,e,r,o,bc(a.config)))return;if(o==="POST"&&(r==="/api/signals/stop"||r==="/api/signals/resume"||r==="/api/signals/drop")){let u=new URL(t.url||"/","http://localhost").searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,r);return}if(o==="POST"&&(r==="/api/node/restart"||r==="/api/node/restart/cancel")){let u=n.searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,r==="/api/node/restart"?"/daemon/restart":"/daemon/restart/cancel");return}if(o==="GET"&&r==="/events"){let f=new URL(t.url||"/","http://localhost").searchParams.toString();e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let v=[{name:a.config.node.name||"local",url:a.config.dashboard.daemonUrl,token:a.config.dashboard.token},...(a.config.dashboard.daemons||[]).map(A=>({name:A.name,url:A.url,token:A.token}))],y={flag:!1},E=[];t.on("close",()=>{y.flag=!0;for(let A of E)try{A.abort()}catch{}});let x=setInterval(()=>{if(!y.flag)try{e.write(`: ping
21252
+ `),console.log(` Boards: ${a.map(k=>k.id).join(", ")}`)),r==="127.0.0.1"&&!o?console.log(" (bound to localhost; no auth token \u2014 safe default)"):r!=="127.0.0.1"&&!o&&console.log(" \u26A0 bound to a non-loopback address without a token \u2014 writes are UNAUTHENTICATED")})}var xg=new Set(["/","/live","/mesh","/monitor","/activity","/boards","/glossary","/workflows","/workflows/editor","/procedures","/processes","/graph","/setup","/admin","/admin/graph","/approvals","/people","/places","/admin/health","/admin/observability","/admin/ledger","/admin/cost","/admin/projects","/admin/wiki"]);async function bg(t,e,a){let n=new URL(t.url||"/","http://localhost"),r=n.pathname,o=(t.method||"GET").toUpperCase();if((t.url||"/").split(/[?#]/)[0]!==r){w(e,404,{error:"not found"});return}if(Dr(t.headers)==="foreign"&&Hr(o)){w(e,403,{error:"Forbidden: request from a page on another origin"});return}if(o==="OPTIONS"){e.writeHead(204),e.end();return}if(await As(t,e,r,o,{nodeName:a.config.node?.name,root:process.cwd(),people:()=>st(a.config.people),members:vc(a.config.members.logRetentionDays),db:()=>tt(),linkFor:(u,f)=>Jo(u,f,{gitlab:a.config.channels.gitlab?.host})})||await dc(t,e,r,o,{nodeName:a.config.node?.name,fleet:Dn(a.config),desk:Dg(a.config),push:Nn(a.config),announce:Sl(a.config),chat:Sc(a.config),voice:qg(a.config),camera:zg(a.config),places:bc(a.config),pins:co(a.config,process.cwd()),assetLinks:()=>id(a.config)}))return;let s=o==="GET"?Go(r):null;if(s){e.writeHead(200,{"Content-Type":s.type,"Cache-Control":"public, max-age=86400"}),e.end(s.body);return}if(o==="GET"&&xg.has(r)&&_o("page",r),o==="GET"&&r==="/"){let u=oo();if(!u.configExists||u.agentCount===0){e.writeHead(302,{Location:"/setup"}),e.end();return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(un({peers:D(a.config)}));return}if(o==="GET"&&r==="/boards"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(pl({peers:D(a.config)}));return}if(o==="GET"&&r==="/live"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(un({peers:D(a.config)}));return}if(o==="POST"&&r.match(/^\/webhook\/n8n\/[A-Za-z0-9._:-]{1,64}$/)){try{let[u]=await Te(a.config);if(!u){w(e,503,{error:"no node available"});return}let f=await new Promise(y=>{let E="";t.on("data",x=>E+=x),t.on("end",()=>y(E)),t.on("error",()=>y(""))}),v=await fetch(u.url+r,{method:"POST",headers:{"Content-Type":"application/json",...u.token?{Authorization:`Bearer ${u.token}`}:{}},body:f||"{}"});e.writeHead(v.status,{"Content-Type":"application/json"}),e.end(await v.text())}catch(u){w(e,502,{error:"could not reach the node",message:String(u?.message||u)})}return}if(r==="/api/assistant"||r.startsWith("/api/assistant/")){try{let u=await Te(a.config),f=o==="POST"?void 0:n.searchParams.get("node"),v=o==="POST"?await re(t):void 0,y=v?.node??f,E=y?u.find(L=>L.url===y):u[0];if(!E){w(e,400,{error:"unknown node"});return}let x=n.search?n.search.replace(/([?&])node=[^&]*/,"$1").replace(/[?&]$/,""):"",A=await fetch(E.url+r+x,{method:o,headers:{"Content-Type":"application/json",...E.token?{Authorization:`Bearer ${E.token}`}:{}},...o==="POST"?{body:JSON.stringify({...v,node:void 0})}:{}});w(e,A.status,await A.json().catch(()=>({error:`HTTP ${A.status}`})))}catch(u){w(e,502,{error:"could not reach the node",message:u?.message||String(u)})}return}if(o==="POST"&&r==="/api/workflows/editor/chat"){try{let u=await re(t),f={"Content-Type":"application/json"};a.config.dashboard.token&&(f.Authorization=`Bearer ${a.config.dashboard.token}`);let v=a.config.dashboard.daemonUrl.replace(/\/+$/,""),y=await fetch(`${v}/api/workflows/editor/chat`,{method:"POST",headers:f,body:JSON.stringify(u??{})}),E=await y.json().catch(()=>({error:`HTTP ${y.status}`}));w(e,y.status,E)}catch(u){w(e,502,{error:"daemon unreachable",message:u.message||String(u)})}return}if(o==="GET"&&r==="/api/n8n/workflows"){try{let[u]=await Te(a.config);if(!u){w(e,200,{configured:!1,workflows:[]});return}let f=await fetch(u.url+"/api/n8n/workflows",{headers:u.token?{Authorization:`Bearer ${u.token}`}:{}});w(e,f.status,await f.json().catch(()=>({configured:!1,workflows:[]})))}catch{w(e,200,{configured:!1,workflows:[]})}return}if(o==="GET"&&r==="/workflows/editor"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(No({peers:D(a.config)}));return}if(o==="GET"&&r==="/activity"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(Oo({peers:D(a.config),view:n.searchParams.get("view")}));return}if(o==="GET"&&r==="/monitor"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(Lo({peers:D(a.config)}));return}if(r==="/api/monitor"||r.startsWith("/api/monitor/")){let u=new AbortController,f=setTimeout(()=>u.abort(),8e3);try{let v=xr(await Te(a.config,u.signal),a.config.mesh.peers);if(o==="GET"&&r==="/api/monitor"){let L=await Promise.all(v.map(async _=>{try{let R=await fetch(_.url+"/monitor",{headers:_.token?{Authorization:`Bearer ${_.token}`}:{},signal:u.signal});if(!R.ok)throw new Error(`HTTP ${R.status}`);return{name:_.name,url:_.url,ok:!0,data:await R.json()}}catch(R){return{name:_.name,url:_.url,ok:!1,error:R.message}}}));w(e,200,{nodes:L});return}let y=v.find(L=>L.url===n.searchParams.get("node"));if(!y){w(e,400,{error:"Select a known node"});return}let E=r.slice(13);if(!(o==="GET"&&["discover","actions","activity"].includes(E)||o==="POST"&&["register","ended","action","retry","clear"].includes(E))){w(e,405,{error:"Unknown monitor operation"});return}let x=o==="POST"?JSON.stringify(await gr(t)):void 0,A=await fetch(y.url+"/monitor/"+E+(E==="actions"?"?offset="+encodeURIComponent(n.searchParams.get("offset")||"0"):E==="activity"?"?hours="+encodeURIComponent(n.searchParams.get("hours")||"24"):""),{method:o,body:x,signal:u.signal,headers:{"Content-Type":"application/json",...y.token?{Authorization:`Bearer ${y.token}`}:{}}});w(e,A.status,await A.json())}catch(v){w(e,502,{error:v.message})}finally{clearTimeout(f)}return}if(o==="GET"&&r==="/mesh"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(sl({peers:D(a.config)}));return}if(o==="GET"&&r==="/places"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(cc({peers:D(a.config)}));return}if(o==="GET"&&r==="/guests"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(il({peers:D(a.config)}));return}if(o==="GET"&&r==="/api/guests"||o==="POST"&&/^\/api\/guests\/[^/]+\/(pause|resume|end|update)$/.test(r)){try{let u={"Content-Type":"application/json"};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=a.config.dashboard.daemonUrl.replace(/\/+$/,""),v=o==="POST"?await re(t).catch(()=>({})):void 0,y=await fetch(`${f}${r.replace(/^\/api\/guests/,"/mesh/guests")}`,{method:o,headers:u,...v!==void 0?{body:JSON.stringify(v??{})}:{}});w(e,y.status,await y.json().catch(()=>({error:`HTTP ${y.status}`})))}catch(u){w(e,502,{error:"daemon unreachable",message:u.message||String(u)})}return}if(o==="GET"&&r==="/glossary"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ul({peers:D(a.config)}));return}if(o==="GET"&&r==="/workflows"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ml({peers:D(a.config)}));return}if(o==="GET"&&r==="/procedures"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(fl({peers:D(a.config)}));return}if(o==="GET"&&r==="/processes"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(ro({}));return}let l=o==="GET"&&r.match(/^\/tasks\/([^/]+)$/);if(l){let u=n.searchParams.get("agent")||"",f=n.searchParams.get("node")||a.config.dashboard.daemonUrl;if(!u){e.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),e.end("<p>Missing <code>?agent=</code>. Open this task from the Live page.</p>");return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(hl({taskId:decodeURIComponent(l[1]),agentId:u,agentName:n.searchParams.get("name")||void 0,channel:n.searchParams.get("channel")||void 0,archived:n.searchParams.get("archived")==="1",ask:n.searchParams.get("ask")||void 0,askAt:n.searchParams.get("at")||void 0,nodeUrl:f,peers:D(a.config)}));return}let d=o==="GET"&&r.match(/^\/agents\/([^/]+)\/history$/);if(d){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(gl({agentId:decodeURIComponent(d[1]),agentName:n.searchParams.get("name")||void 0,nodeUrl:n.searchParams.get("node")||a.config.dashboard.daemonUrl,peers:D(a.config)}));return}if(o==="GET"&&r==="/graph"){e.writeHead(302,{Location:"/admin/graph"}),e.end();return}if(o==="GET"&&r==="/setup"){so(t,e);return}if(o==="POST"&&r==="/api/setup"){await io(t,e);return}if(o==="POST"&&r==="/api/setup/start-daemon"){await lo(t,e);return}if(o==="GET"&&r==="/admin"){Ds(t,e,D(a.config),a.token);return}if(o==="GET"&&r==="/approvals"){ei(e,D(a.config),a.token);return}if(o==="GET"&&r==="/admin/graph"){Gs(t,e,D(a.config),a.token);return}if(o==="GET"&&(r==="/admin/health"||r==="/admin/observability")){if(r==="/admin/observability"){e.writeHead(302,{Location:"/admin/health"}),e.end();return}ci(t,e,D(a.config));return}if(r.startsWith("/api/admin/")||r.startsWith("/api/workflows")||r.startsWith("/api/agents")){let u=n.searchParams.get("peer")==="fleet"?"fleet":String(t.headers["x-agentx-peer"]||"").trim()||n.searchParams.get("peer")||"";if(u==="fleet"){if(r==="/api/admin/activity-graph"){await Kg(t,e,a);return}if(r==="/api/admin/activity-graph/stream"){await cn(t,e,r,v=>Tc(v,a.config));return}let f=r.match(/^\/api\/admin\/activity-graph\/dispatch\/(.+)$/);if(f){let v=decodeURIComponent(f[1]),y=v.indexOf("::");if(y>0){let E=v.slice(0,y),x=v.slice(y+2),A=a.config.node?.id||a.config.node?.name||"local";if(E===A)t.url=`/api/admin/activity-graph/dispatch/${encodeURIComponent(x)}`;else{let L=(a.config.dashboard?.daemons||[]).find(_=>(_.name||_.url)===E);if(L){let _=ft(L.url.replace(/\/+$/,""),a.config);if(_){await wc(t,e,_,`/api/admin/activity-graph/dispatch/${encodeURIComponent(x)}`);return}}w(e,404,{error:`unknown node "${E}" in fleet dispatch id`});return}}}}else if(u&&u!=="primary"){let f=ft(u,a.config);if(!f){w(e,404,{error:`unknown peer: ${u}`});return}let v=(n.search||"").replace(/[?&]peer=[^&]*/g,E=>E.startsWith("?")?"?":"");await wc(t,e,f,r+(v==="?"?"":v));return}}if(o==="GET"&&r.startsWith("/api/admin/observability/")&&await pi(t,e,r))return;if(o==="GET"&&r==="/api/admin/logs/stream"){await Jg(t,e);return}if(o==="GET"&&r==="/api/admin/doctor"){try{let{runDoctorChecks:u}=await import("./doctor-QWVUVWTF.js"),v=new URL(t.url||"/","http://_").searchParams.get("running")!=="false",y=await u({running:v});w(e,200,y)}catch(u){w(e,500,{error:u?.message||String(u)})}return}if(o==="GET"&&r==="/admin/ledger"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(hi({peers:D(a.config)}));return}if(o==="GET"&&r.startsWith("/api/admin/ledger/")&&await fi(t,e,r))return;if(o==="GET"&&r==="/admin/cost"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(gi({peers:D(a.config)}));return}if(o==="GET"&&r==="/admin/projects"){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(xi({peers:D(a.config)}));return}if(o==="GET"&&(r==="/admin/wiki"||r.startsWith("/admin/wiki/"))){if(r==="/admin/wiki"){e.writeHead(302,{Location:"/admin/wiki/"}),e.end();return}await Eg(a)(t,e);return}if(o==="GET"&&r==="/admin/activity-graph"){e.writeHead(302,{Location:"/activity?view=map"}),e.end();return}if(o==="GET"&&r==="/api/admin/activity-graph"&&await Bi(t,e,r)||o==="GET"&&r.startsWith("/api/admin/activity-graph/stream")&&await cn(t,e,r)||o==="GET"&&r.startsWith("/api/admin/activity-graph/dispatch/")&&await zi(t,e,r))return;let p=o==="GET"&&r.match(/^\/admin\/agents\/([a-z0-9][a-z0-9_-]*)$/);if(p){Wi(t,e,p[1],D(a.config),a.token);return}if(r.startsWith("/api/admin/")&&a.token){let u=t.headers.authorization||"",f=u.startsWith("Bearer ")?u.slice(7):"";if(f!==a.token){let v=new G,y=f?v.verify(f):null;if(!y||!Ae(y,"dashboard:write")){w(e,401,{error:"unauthorized"});return}}}if(o==="GET"&&r==="/api/admin/config"){await Hs(t,e);return}if(o==="GET"&&r==="/api/admin/voice-health"){w(e,200,Fr()??{checkedAt:null,missing:[]});return}if(r.startsWith("/api/admin/approvals")){await ti(t,e,r,n);return}if(await ni(t,e,r,{people:()=>st(a.config.people),members:vc(a.config.members.logRetentionDays),root:process.cwd(),db:()=>tt(),peers:D(a.config),localToken:a.token}))return;if(r.startsWith("/api/admin/graph/")){await Xs(t,e,r);return}if(r.startsWith("/api/admin/agent/")){await Gi(t,e,r);return}if(r.startsWith("/api/admin/")){await Bs(t,e,r);return}if(o==="GET"&&r==="/sortable.min.js"){e.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"public, max-age=86400"}),e.end(Cs);return}if(o==="GET"&&r.startsWith("/assets/")){let u=r.slice(8);if(!/^[a-zA-Z0-9._-]+\.(js|map|css)$/.test(u)){w(e,400,{error:"invalid asset name"});return}let f=Gg("web/"+u);try{let v=await Xg(f),y=u.endsWith(".map")?"application/json; charset=utf-8":u.endsWith(".css")?"text/css; charset=utf-8":"application/javascript; charset=utf-8",E=n.searchParams.has("v");e.writeHead(200,{"Content-Type":y,"Cache-Control":E?"public, max-age=31536000, immutable":"public, max-age=60"}),e.end(v)}catch{w(e,404,{error:"asset not found",hint:"run: npm run build:web"})}return}if(o==="GET"&&r==="/api/live"){try{let u=await at(a.config);w(e,200,u)}catch(u){w(e,502,{error:u.message})}return}if(o==="GET"&&r==="/api/mesh"){try{let u=n.searchParams.get("date")||new Date().toISOString().slice(0,10),f=n.searchParams.get("timezone")||"UTC",v=await at(a.config,{date:u,timezone:f});w(e,200,v)}catch(u){w(e,502,{error:u.message})}return}if(o==="GET"&&r==="/api/mesh/analytics"){let u=(f,v,y,E)=>{let x=parseInt(n.searchParams.get(f)||"",10);return Number.isFinite(x)?Math.max(y,Math.min(E,x)):v};try{let f=await Te(a.config);w(e,200,await ll(f,{days:u("days",30,0,180),tzOffsetMinutes:u("tzOffset",0,-840,840),limit:u("limit",60,1,200)}))}catch(f){w(e,502,{error:f.message})}return}if(o==="GET"&&r==="/api/mesh/day"){let u=n.searchParams.get("day")||"";if(!/^\d{4}-\d{2}-\d{2}$/.test(u)){w(e,400,{error:"day=YYYY-MM-DD query param required"});return}let f=(v,y,E,x)=>{let A=parseInt(n.searchParams.get(v)||"",10);return Number.isFinite(A)?Math.max(E,Math.min(x,A)):y};try{let v=await Te(a.config);w(e,200,await cl(v,{day:u,tzOffsetMinutes:f("tzOffset",0,-840,840),limit:f("limit",40,1,200)}))}catch(v){w(e,502,{error:v.message})}return}if(o==="GET"&&(r==="/api/mesh/thread"||r==="/api/mesh/job"||r==="/api/mesh/run"||r==="/api/mesh/conversation")){let u=n.searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}let f=n.searchParams,v;if(r==="/api/mesh/thread"){let[y,E,x]=[f.get("agent"),f.get("channel"),f.get("chat")];if(!y||!E||!x){w(e,400,{error:"agent, channel, chat required"});return}v=`/analytics/thread?agent=${encodeURIComponent(y)}&channel=${encodeURIComponent(E)}&chat=${encodeURIComponent(x)}&limit=${encodeURIComponent(f.get("limit")||"120")}`}else if(r==="/api/mesh/job"){let[y,E]=[f.get("kind"),f.get("key")];if(!y||!E){w(e,400,{error:"kind and key required"});return}v=`/analytics/job?kind=${encodeURIComponent(y)}&key=${encodeURIComponent(E)}&limit=${encodeURIComponent(f.get("limit")||"120")}`}else if(r==="/api/mesh/conversation"){let[y,E,x]=[f.get("agent"),f.get("channel"),f.get("chat")];if(!y||!E||!x){w(e,400,{error:"agent, channel, chat required"});return}v=`/analytics/conversation?agent=${encodeURIComponent(y)}&channel=${encodeURIComponent(E)}&chat=${encodeURIComponent(x)}&tzOffset=${encodeURIComponent(f.get("tzOffset")||"0")}`}else{let y=f.get("task");if(!y){w(e,400,{error:"task required"});return}v=`/analytics/run/${encodeURIComponent(y)}`}try{await dl(e,await Te(a.config),u,v)}catch(y){w(e,502,{error:y.message})}return}if(o==="GET"&&r==="/api/live/stream"){Lg(t,e,a.config);return}if(o==="GET"&&r==="/api/task/stream"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("agent"),y=u.searchParams.get("task");if(!f||!v||!y){w(e,400,{error:"node, agent, task query params required"});return}await Pg(t,e,a,f,v,y);return}if(o==="GET"&&r==="/api/task/history"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("agent"),y=u.searchParams.get("task"),E=u.searchParams.get("limit")||"50";if(!f||!v){w(e,400,{error:"node and agent query params required"});return}await Og(e,a,f,v,y,E);return}if(o==="POST"&&r==="/api/task/action"){let u=new URL(t.url||"/","http://localhost"),f=u.searchParams.get("node"),v=u.searchParams.get("task"),y=u.searchParams.get("kind");if(!f||!v||y!=="cancel"&&y!=="followup"){w(e,400,{error:"node, task, kind=cancel|followup query params required"});return}await Ng(t,e,a,f,v,y);return}if(o==="POST"&&r==="/api/voice/stop"){let u=new URL(t.url||"/","http://localhost").searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,"/voice/stop");return}if(o==="GET"&&r==="/api/agents"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/agents",{headers:u});if(!f.ok)throw new Error(`HTTP ${f.status}`);let v=await f.json();w(e,200,v)}catch(u){w(e,502,{error:u.message||"agents fetch failed"})}return}if(o==="GET"&&r==="/api/business/status"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/business/status",{headers:u});if(!f.ok){w(e,f.status,{error:`HTTP ${f.status}`});return}w(e,200,await f.json())}catch(u){w(e,502,{error:u.message||"business status fetch failed"})}return}if(o==="POST"&&r==="/api/draft"){let u=await re(t);try{let f=await Ug(a.config,u);w(e,200,f)}catch(f){w(e,502,{error:f.message||"draft failed"})}return}let c=r.match(/^\/api\/public\/agents\/([^/]+)\/messages$/);if(c&&o==="POST"){let u=c[1];if(!$g(t,e,[`agent:${u}`]))return;await jg(t,e,a.config,u);return}if(o==="GET"&&r==="/api/node/build"){try{let u={};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=await fetch(a.config.dashboard.daemonUrl.replace(/\/+$/,"")+"/health",{headers:u,signal:AbortSignal.timeout(3e3)});if(!f.ok)throw new Error(`HTTP ${f.status}`);w(e,200,zr(await f.json()))}catch(u){w(e,502,{error:u.message||"daemon not reachable"})}return}if(r.startsWith("/api/")&&a.token){let u=t.headers.authorization||"",f=u.startsWith("Bearer ")?u.slice(7):"";if(f!==a.token){let v=new G,y=f?v.verify(f):null;if(!y||!Ae(y,"dashboard:write")){w(e,401,{error:"unauthorized"});return}}}if(o==="GET"&&r==="/api/mesh/feed"){await Tg(e,a.config,n.searchParams);return}if((o==="POST"||o==="PATCH"||o==="DELETE"||o==="PUT")&&r.startsWith("/api/")&&t.headers["x-requested-with"]!=="agentx-board"){w(e,400,{error:"missing X-Requested-With: agentx-board"});return}if(r==="/api/wiki/curate"||r==="/api/wiki/curate/restore"){try{let u={"Content-Type":"application/json"};a.config.dashboard.token&&(u.Authorization=`Bearer ${a.config.dashboard.token}`);let f=a.config.dashboard.daemonUrl.replace(/\/+$/,""),v=o==="POST"?JSON.stringify(await re(t)??{}):void 0,y=await fetch(`${f}${r}${n.search}`,{method:o,headers:u,...v?{body:v}:{}});w(e,y.status,await y.json().catch(()=>({error:`HTTP ${y.status}`})))}catch(u){w(e,502,{error:"daemon unreachable",message:u?.message||String(u)})}return}if(await rd(t,e,r,o,bc(a.config)))return;if(o==="POST"&&(r==="/api/signals/stop"||r==="/api/signals/resume"||r==="/api/signals/drop")){let u=new URL(t.url||"/","http://localhost").searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,r);return}if(o==="POST"&&(r==="/api/node/restart"||r==="/api/node/restart/cancel")){let u=n.searchParams.get("node");if(!u){w(e,400,{error:"node query param required"});return}await xa(t,e,a,u,r==="/api/node/restart"?"/daemon/restart":"/daemon/restart/cancel");return}if(o==="GET"&&r==="/events"){let f=new URL(t.url||"/","http://localhost").searchParams.toString();e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let v=[{name:a.config.node.name||"local",url:a.config.dashboard.daemonUrl,token:a.config.dashboard.token},...(a.config.dashboard.daemons||[]).map(A=>({name:A.name,url:A.url,token:A.token}))],y={flag:!1},E=[];t.on("close",()=>{y.flag=!0;for(let A of E)try{A.abort()}catch{}});let x=setInterval(()=>{if(!y.flag)try{e.write(`: ping
21253
21253
 
21254
21254
  `)}catch{}},15e3);t.on("close",()=>clearInterval(x));for(let A of v)(async()=>{let L={Accept:"text/event-stream"};A.token&&(L.Authorization=`Bearer ${A.token}`);let _=new AbortController;E.push(_);try{let R=await fetch(`${A.url.replace(/\/+$/,"")}/events${f?`?${f}`:""}`,{headers:L,signal:_.signal});if(!R.ok||!R.body)return;let j=R.body.getReader(),$=new TextDecoder,O="";for(;!y.flag;){let{done:W,value:ce}=await j.read();if(W)break;O+=$.decode(ce,{stream:!0});let Q;for(;(Q=O.indexOf(`
21255
21255
 
@@ -21304,4 +21304,4 @@ data: ${g.replace(/\n/g," ")}
21304
21304
  `)}catch{}}};s.stdout?.on("data",l),s.stderr?.on("data",l);let d=setInterval(()=>{try{e.write(`: hb
21305
21305
 
21306
21306
  `)}catch{}},15e3),p=()=>{clearInterval(d);try{s.kill()}catch{}try{e.end()}catch{}};t.on("close",p),s.on("exit",p),s.on("error",p)}async function wc(t,e,a,n){let r=a.url+n,o=(t.method||"GET").toUpperCase(),i=o!=="GET"&&o!=="HEAD"?await new Promise((c,m)=>{let g=[];t.on("data",k=>g.push(k)),t.on("end",()=>c(Buffer.concat(g))),t.on("error",m)}):void 0,l={},d=t.headers["content-type"];d&&(l["Content-Type"]=Array.isArray(d)?d[0]:d);let p=t.headers["x-requested-with"];p&&(l["X-Requested-With"]=Array.isArray(p)?p[0]:p),a.token&&(l.Authorization=`Bearer ${a.token}`),l["X-Agentx-Peer"]="primary";try{let c=await fetch(r,{method:o,headers:l,body:i&&i.length>0?i:void 0}),m=Buffer.from(await c.arrayBuffer());e.writeHead(c.status,{"Content-Type":c.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),e.end(m)}catch(c){w(e,502,{error:`proxy to peer failed: ${c?.message||c}`,target:r})}}function ft(t,e){let a=t.replace(/\/+$/,""),n=(e.dashboard?.daemons||[]).find(r=>r.url.replace(/\/+$/,"")===a);return n?{url:Ec(n),token:n.dashboardToken||n.token}:null}export{Rg as applyAttachSessions,Sg as fetchDaemonAgents,bg as handleBoardRequest,Y_ as resetLiveCaches,Te as resolveNodeTargets,V_ as startBoardDashboard,Mg as withLastGood};
21307
- //# sourceMappingURL=board-dashboard-OZJSS6EM.js.map
21307
+ //# sourceMappingURL=board-dashboard-UZF7MQZA.js.map
@@ -1,3 +1,3 @@
1
- import{n as x,p as A}from"./chunk-24QMHUU2.js";import{a as w,e as D}from"./chunk-2QNT5JDS.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
1
+ import{n as x,p as A}from"./chunk-LQS27HSV.js";import{a as w,e as D}from"./chunk-2QNT5JDS.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
2
2
  `)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
3
- //# sourceMappingURL=chunk-R4R7EYY3.js.map
3
+ //# sourceMappingURL=chunk-BNOGNRAM.js.map
@@ -1,7 +1,7 @@
1
- import{B as k,D as O,G as I,q as R,t as x,z as N}from"./chunk-MOCDP7Q3.js";import{a as E}from"./chunk-OSH2PEBH.js";import{La as j,Ua as F}from"./chunk-5VPU5FHB.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{B as k,D as O,G as I,q as R,t as x,z as N}from"./chunk-ZAH74SFX.js";import{a as E}from"./chunk-OSH2PEBH.js";import{La as j,Ua as F}from"./chunk-5VPU5FHB.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
3
  `)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{G(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function de(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=le(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ue(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
6
6
  `))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
7
- //# sourceMappingURL=chunk-P24P43ZB.js.map
7
+ //# sourceMappingURL=chunk-DZRD6BE4.js.map
@@ -1,4 +1,4 @@
1
- import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-CFPRIE6F.js";import{c as Me,d as le,e as P,f as de,g as j}from"./chunk-B2QYMUTD.js";import{a as We}from"./chunk-7LN4VKDU.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as Re,e as De}from"./chunk-LQE73AZR.js";import{b as ze}from"./chunk-MRIVENBY.js";import{n as se,p as _e}from"./chunk-24QMHUU2.js";import{b as Y}from"./chunk-YMX3QCV7.js";import{G as J}from"./chunk-S5FRIHWM.js";import{a as G,b as K}from"./chunk-BFONYVOM.js";import{a as Pe}from"./chunk-RUQMUDSX.js";import{c as Ce,d as Ie}from"./chunk-OWNQ2FD4.js";import{a as Ee}from"./chunk-ROLSSYXE.js";import{Ia as oe,Ka as F,L as ae,La as Se,M as $e,T as Rt,Ua as ie,ia as Ae,pa as Dt}from"./chunk-5VPU5FHB.js";import{existsSync as H,readFileSync as Je,writeFileSync as Ye,appendFileSync as Wt,mkdirSync as Mt}from"fs";import{dirname as Nt,resolve as W}from"path";import{fileURLToPath as Ot}from"url";import{hostname as Ut}from"os";import{spawn as Lt}from"child_process";function Ge(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
1
+ import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-CFPRIE6F.js";import{c as Me,d as le,e as P,f as de,g as j}from"./chunk-B2QYMUTD.js";import{a as We}from"./chunk-7LN4VKDU.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as Re,e as De}from"./chunk-LQE73AZR.js";import{b as ze}from"./chunk-MRIVENBY.js";import{n as se,p as _e}from"./chunk-LQS27HSV.js";import{b as Y}from"./chunk-YMX3QCV7.js";import{G as J}from"./chunk-S5FRIHWM.js";import{a as G,b as K}from"./chunk-BFONYVOM.js";import{a as Pe}from"./chunk-RUQMUDSX.js";import{c as Ce,d as Ie}from"./chunk-OWNQ2FD4.js";import{a as Ee}from"./chunk-ROLSSYXE.js";import{Ia as oe,Ka as F,L as ae,La as Se,M as $e,T as Rt,Ua as ie,ia as Ae,pa as Dt}from"./chunk-5VPU5FHB.js";import{existsSync as H,readFileSync as Je,writeFileSync as Ye,appendFileSync as Wt,mkdirSync as Mt}from"fs";import{dirname as Nt,resolve as W}from"path";import{fileURLToPath as Ot}from"url";import{hostname as Ut}from"os";import{spawn as Lt}from"child_process";function Ge(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -859,4 +859,4 @@ tr:hover td { background: var(--bg-hover); }
859
859
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
860
860
  ${r}`).all(t,...n,...a).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Ta(e,t){return wt(e,t,ae,"ORDER BY created_at")}function Ra(e,t,n=50){return wt(e,t,[...ae,...$e],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}Dt();var we="member:",Mn=90,Nn="members",On="tailscale-user-login",Un=400,Ln=60*60*1e3;function Bn(e){let t=e.scopes.find(n=>n.startsWith(we));return t?t.slice(we.length):null}function At(e,t){if(!e)return null;let n=t.verify(e),r=n?Bn(n):null;return n&&r?{rec:n,personId:r}:null}function Oa(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${we}${n.id}`],expiresInDays:Mn}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:a.id,person:n}}var jn=Math.round(Re/6e4);function Hn(e){return e==="client"?"Your project":"My work"}function Ua(e){let t=Hn(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": 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, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","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: ${De(e.code)}`,` The code works once, for ${jn} 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(`
861
861
  `)}var qn="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",Fn="Too many machines are waiting for the owner's answer. Try again later.",$t="That code didn't work. Check it, or ask the person who invited you for a new one.",St=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ct(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function Gn(e){if(!Ct(e))return null;let t=St(e,On).toLowerCase();return t?t.slice(0,80):null}function Kn(e){let t=e.socket?.remoteAddress||"unknown";if(!Ct(e))return t;let n=St(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function Jn(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Yn(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function La(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(v=>console.log(v)),o=Kn(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[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,l="";try{let v=await Y(e,2048);s=v.code,l=Jn(v.machine)}catch{}let d=t.codes.redeem(s),c=d?At(d.token,t.tokens):null;if(await Vn(n,t.minMs??Un),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:$t}};t.limiter.succeed(o);let{rec:m,personId:p}=c,w=t.people().find(v=>v.id===p);if(!w)return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${p} refused from ${o}: person no longer listed`),{status:403,body:{error:$t}};let g=Gn(e),f=Yn(w);if(f.length&&(!g||!f.includes(g)))return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:`network login ${g??"missing"}; expected ${f.join(" or ")}`}),a(`[member] ${p}: pairing from ${o} refused: the network says "${g??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:qn}};let C=l||"Unnamed machine",x=w.name.slice(0,40),b=_e(t.root,{title:`New machine for ${x}`,ask:`From ${o}, ${g?`network login ${g}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${x}'s own work?`,recommend:`Yes if ${x} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Nn},{now:r()});return b.ok?(t.members.add({tokenId:m.id,personId:p,name:C,state:"pending",cardId:b.card.id,address:o,...g?{network:g}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:p,device:m.id,event:"paired",address:o,detail:C}),a(`[member] ${p} paired "${C}" from ${o}; waiting for the owner (card ${b.card.id})`),{status:200,body:{person:p,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:b.error}),a(`[member] ${p}: pairing from ${o} refused: ${b.error}`),{status:503,body:{error:Fn}})}var re="this machine is not paired",Xn="waiting for the owner to approve this machine";function It(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function Ba(e,t){return t.state==="pending"&&t.cardId?It(se(e,t.cardId)):null}function ja(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=At(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Et(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,m=It(c);if(m==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(m==="no"){let p=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:p}),t.members.log({person:s,device:i.id,event:"refused",detail:p}),a(`[member] ${s}: "${l.name}" refused: ${p}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:Xn,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=Ln||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Et(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function Ha(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Et(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Vn(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pt=["gitlab","github"];function Qn(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pt.includes(r))throw new Error(`Request status works on ${Pt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function Ga(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Ka(e){let{summary:t}=X(n=>Qn(n,e?.channel,!!e?.enabled));return{summary:t}}function Ya(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Xa(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function Va(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Qa(e,t){if(t){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 Zn="https://ntfy.sh";function eo(e){return{enabled:!!e?.enabled,server:e?.server||Zn,topicSet:!!e?.topic,tokenSet:!!e?.token}}function to(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Xe as a,cr as b,pr as c,ur as d,xr as e,yr as f,tn as g,an as h,me as i,kr as j,wr as k,kt as l,Sa as m,Ca as n,Ir as o,Er as p,Pr as q,Pa as r,Ta as s,Ra as t,Mn as u,Oa as v,jn as w,Hn as x,Ua as y,Kn as z,La as A,Ba as B,ja as C,Et as D,Ha as E,Pt as F,Qn as G,Ga as H,Ka as I,Ya as J,Xa as K,Va as L,Qa as M,eo as N,to as O,Cn as P,Vr as Q,ra as R,aa as S};
862
- //# sourceMappingURL=chunk-SW6HCRLU.js.map
862
+ //# sourceMappingURL=chunk-IFOFBI3U.js.map
@@ -0,0 +1,6 @@
1
+ import{c as v,d as R,f as E,g as T}from"./chunk-MNG2AMKZ.js";import{existsSync as H,linkSync as Q,mkdirSync as j,readdirSync as X,readFileSync as Z,renameSync as ee,unlinkSync as te,writeFileSync as M}from"fs";import{resolve as U}from"path";function L(e){return e?.kind==="retro"||e?.kind==="retro-check"}var N={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function q(e,t,n){let r=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${r}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(t.status==="decided"&&t.verdict==="yes")||t.choice===N.keep||!t.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(t.choice===N.remove?`The operator chose to remove it. Delete ${r} as a pull request.`:`The operator chose to loosen it. Narrow ${r} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),t.choice_suggested&&i.push(A),n&&i.push("The operator's note:",n),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}var A="(The operator gave a plain yes, taken as the suggested option.)";function C(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==S}function F(e,t,n){let r=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!C(t))return r.push("Change nothing. Do not propose these fixes again on your own."),r;r.push(`The operator picked this fix: ${t.choice}`),t.choice_suggested&&r.push(A);let i=e.specs?.[(t.choices??[]).indexOf(t.choice)];return i&&r.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&r.push("The operator's note on the fix:",n),r.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),r}var S="None of these";function P(e,t){let n=e.list?` in the "${e.list}" list`:"",r=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return r.push(t?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),r}var u={title:120,ask:300,answers:3},D=["resurface","bring-back","weekly","cleanup"],w={perDay:5,resurface:3},z=[/\bhttps?:\/\/\S+/gi,/(?:[\w.-]+\/)*[\w.-]+[#!]\d+\b/g,/[#!]\d+\b/g,/\b[0-9A-HJKMNP-TV-Z]{26}\b/gi,/\b(?:req|dlg|snd)-[\w-]+/gi,/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\b/gi];function J(e){return z.reduce((t,n)=>t.replace(n," "),e)}function B(e){let t=J(e);return t===e||t.split(/\s+/).filter(r=>/\p{L}/u.test(r)).length>=2?null:`title is only a reference ("${e.trim()}"); say what it is in plain words, and put the link in the body or source`}function K(e){let t=typeof e.title=="string"?e.title:"",n=typeof e.ask=="string"?e.ask:"";if(!t.trim())return"title is missing: say what it is in plain words";if(t.length>u.title)return`title is longer than ${u.title} characters`;let r=B(t);return r||(n.trim()?n.length>u.ask?`ask is longer than ${u.ask} characters`:(n.match(/\?/g)??[]).length>1?"ask holds more than one question: one card asks one thing":(e.choices?.length??0)>u.answers?`more than ${u.answers} choices`:null:"ask is missing: one card asks one thing")}function ge(e,t){if(e.length>u.title)return`title is longer than ${u.title} characters`;let n=B(e);return n||(t.length>u.ask?`message is longer than ${u.ask} characters`:null)}function fe(e,t){let n=t?.trim().replace(/\s+/g," ")||"nothing, FYI";return`${e}
2
+ To do: ${n}`}function Y(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function W(e,t,n){let r=Y(n),i=e.filter(o=>o.followup&&Date.parse(o.created_at)>=r);return i.length>=w.perDay?`the follow-up screen budget is used up today (${w.perDay} cards): raise it again tomorrow`:t==="resurface"&&i.filter(o=>o.followup==="resurface").length>=w.resurface?`${w.resurface} resurface cards were already raised today: raise it again tomorrow`:null}function pe(e,t){let n=e.title?.trim();return e.origin?.kind==="request"?[`[screen gate] Request ${e.id}${n?` ("${n}")`:""} was not shown to the owner: ${t}.`,`It is still on his list. Say what it is: agentx_request {action:"describe", id:"${e.id}", headline:"<a few plain words>", need:"<what you need from him>"}.`].join(" "):[`[screen gate] Your card ${e.id}${n?` ("${n}")`:""} was not shown to the owner: ${t}.`,"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:",`one question, title up to ${u.title} characters, ask up to ${u.ask}, at most ${u.answers} choices.`].join(" ")}var V=["discard","keep","pause"];function I(e){return e==="approve"?"keep":V.includes(e)?e:null}var l={title:120,ask:300,recommend:300,source:500,note:500,resolution:300,pendingPerAgent:25},re={defaultExpiryDays:3,maxExpiryDays:30};function m(e){return U(e,".agentx","approvals")}var ne=/^[a-z0-9][a-z0-9-]{0,80}$/;function G(e){return ne.test(e)}function O(e,t){if(!G(t))throw new Error(`invalid card id: ${t}`);return U(m(e),`${t}.json`)}function ie(e,t){let n=new Date(e).toISOString().slice(0,10),r=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${r||"card"}-${Math.random().toString(36).slice(2,6).padEnd(4,"0")}`}function x(e,t){j(m(e),{recursive:!0});let n=O(e,t.id),r=`${n}.${process.pid}.tmp`;M(r,JSON.stringify(t,null,2)+`
3
+ `),ee(r,n)}function oe(e,t){j(m(e),{recursive:!0});for(let n=1;;n++){let r=n===1?t:{...t,id:`${t.id}-${n}`},i=O(e,r.id),o=`${i}.${process.pid}.tmp`;M(o,JSON.stringify(r,null,2)+`
4
+ `);try{return Q(o,i),r}catch(s){if(s.code!=="EEXIST")throw s}finally{te(o)}}}function _(e,t){if(!G(t))return null;try{let n=JSON.parse(Z(O(e,t),"utf-8")),r=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:I(n.if_silent)??"keep",...n.outcome?{outcome:I(n.outcome)??"keep"}:{},...r?{if_silent_asked:"approve"}:{}}}catch{return null}}function y(e,t){let n=m(e);if(!H(n))return[];let r=[];for(let i of X(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=_(e,i.slice(0,-5));o&&(!t||o.status===t)&&r.push(o)}return r}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function se(e,t,n){let r=t+n.maxExpiryDays*864e5,i,o=a(e);if(!o)i=t+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=t+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=t?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,r)).toISOString()}}function ae(e,t={}){let n=t.now??Date.now(),r=t.settings??re,i=a(e.title),o=a(e.ask),s=a(e.recommend),d=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!d)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>l.title)return{ok:!1,error:`title is longer than ${l.title} characters`};if(o.length>l.ask)return{ok:!1,error:`ask is longer than ${l.ask} characters`};if(s.length>l.recommend)return{ok:!1,error:`recommend is longer than ${l.recommend} characters`};let f=a(e.if_silent).toLowerCase(),h=I(f);if(!h)return{ok:!1,error:`if_silent must be one of ${V.join(", ")}`};let c=se(e.expires,n,r);if(!c.ok)return c;let p=a(e.source);if(p.length>l.source)return{ok:!1,error:`source is longer than ${l.source} characters`};if(p&&/^[a-z][a-z0-9+.-]*:/i.test(p)&&!/^https?:\/\//i.test(p))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let b=v(e);if(!b.ok)return b;let k=a(e.followup).toLowerCase();if(k&&!D.includes(k))return{ok:!1,error:`followup must be one of ${D.join(", ")}`};let $,g=e.reply;return g&&typeof g=="object"&&a(g.channel)&&a(g.chatId)&&($={channel:a(g.channel),chatId:a(g.chatId),...a(g.accountId)?{accountId:a(g.accountId)}:{}}),{ok:!0,card:{id:ie(n,i),title:i,ask:o,recommend:s,if_silent:h,...f==="approve"?{if_silent_asked:"approve"}:{},expires:c.at,...p?{source:p}:{},raised_by:d,...t.node?{node:t.node}:{},created_at:new Date(n).toISOString(),...$?{reply:$}:{},...b.value,...t.origin?{origin:t.origin}:{},...k?{followup:k}:{},status:"pending"}}}function ce(e,t){if(!(!t.source||t.origin))return e.find(n=>!n.origin&&n.source===t.source&&n.raised_by===t.raised_by&&(n.node??"")===(t.node??""))}function _e(e,t,n={}){let r=ae(t,n);if(!r.ok)return r;let i=K(r.card);if(i)return{ok:!1,error:i};if(r.card.followup){let c=W(y(e),r.card.followup,n.now??Date.now());if(c)return{ok:!1,error:c}}let o=y(e,"pending"),s=ce(o,r.card);if(s)return{ok:!1,error:`a card from you on this source is still pending: ${s.id}. Wait for its answer, or resolve it first and then raise the new one.`};let d=c=>L(c.origin),f=d(r.card),h=o.filter(c=>c.raised_by===r.card.raised_by&&d(c)===f).length;if(h>=l.pendingPerAgent){let c=f?"retro cards":"cards";return{ok:!1,error:`${r.card.raised_by} already has ${h} ${c} waiting; wait for decisions before raising more`}}return{ok:!0,card:oe(e,r.card)}}function be(e,t,n,r={}){let i=_(e,t);if(!i)return{ok:!1,error:`no card "${t}"`};if(i.status!=="pending")return{ok:!1,error:`card "${t}" is already ${i.status}`};let o=E(i,n,r);if(!o.ok)return o;let s=a(r.note).slice(0,l.note),d={...i,status:"decided",verdict:n,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.suggested?{choice_suggested:!0}:{},...o.text?{text:o.text}:{}};return x(e,d),{ok:!0,card:d}}var ue=new Set([void 0,"reminder"]);function $e(e,t,n){let r=_(e,t);if(!r)return{ok:!1,status:404,error:`no card "${t}"`};if(r.raised_by!==n.by||(r.node??"")!==(n.node??""))return{ok:!1,status:403,error:`card "${t}" was raised by another agent`};if(!ue.has(r.origin?.kind))return{ok:!1,status:409,error:`card "${t}" is answered by the operator only`};if(r.status!=="pending")return{ok:!1,status:409,error:`card "${t}" is already ${r.status}`};let i=a(n.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(n.now??Date.now()).toISOString(),s={...r,status:"resolved",decided_by:n.by,decided_at:o,resolution:i.slice(0,l.resolution),agent_notified_at:o};return x(e,s),{ok:!0,card:s}}function Ce(e,t=Date.now()){let n=[];for(let r of y(e,"pending")){if(Date.parse(r.expires)>t)continue;let i={...r,status:"expired",outcome:r.if_silent,decided_by:"expiry",decided_at:new Date(t).toISOString()};x(e,i),n.push(i)}return n}function Se(e){return y(e).filter(t=>t.status!=="pending"&&!t.agent_notified_at)}function De(e,t,n=Date.now()){let r=_(e,t);!r||r.agent_notified_at||x(e,{...r,agent_notified_at:new Date(n).toISOString()})}var de="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function Ie(e){let t=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?t&&!C(e)?`The operator picked "${S}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,r=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!t&&!i&&r.push(...T(e)),e.note&&r.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!t&&!i&&r.push(de),e.source&&r.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&r.push(...P(e.origin,e.status==="decided"&&e.verdict==="yes")),t||i){let o=f=>f.replace(/\s+/g," ").trim(),s=R(e.draft,e.choice),d=e.text&&o(e.text)!==o(s)?e.text:void 0;r.push(...t?F(t,e,d):q(i,e,d))}return e.reply&&r.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&r.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),r.push("Act on this result now. Do not raise the same card again."),r.join(`
5
+ `)}export{L as a,N as b,C as c,S as d,B as e,K as f,ge as g,fe as h,pe as i,V as j,l as k,m as l,G as m,_ as n,y as o,_e as p,be as q,$e as r,Ce as s,Se as t,De as u,Ie as v};
6
+ //# sourceMappingURL=chunk-LQS27HSV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts","../src/approvals/screen-gate.ts"],"sourcesContent":["import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, draftFor, resolveAnswer, type CardChoices } from \"./choices\"\nimport { isRetroOrigin, originLines, RETRO_NONE, retroApproved, retroCheckLines, retroLines, type CardOrigin } from \"./origin\"\nimport { cardRuleBreak, FOLLOWUP_KINDS, followupBudgetRefusal, type FollowupKind } from \"./screen-gate\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\n// \"resolved\": closed by the agent that raised it, because the owner gave the\n// same answer somewhere else (in chat, #909) and the agent already acted on\n// it. Not a verdict: nothing is approved or rejected by it.\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\" | \"resolved\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** Set when `choice` came from a plain yes taking the suggested option\n * (#1064), not from the operator picking it. */\n choice_suggested?: boolean\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** Why the raising agent closed it (status \"resolved\"). */\n resolution?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n /** A follow-up card (#394): counted in the daily screen budget. */\n followup?: FollowupKind\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n resolution: 300,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6).padEnd(4, \"0\")}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\n/**\n * Save a card that is new. Its id is random, so two cards with the same\n * title on the same day can draw the same one: then the id gets \"-2\", \"-3\"\n * and so on, and a card already on disk is never overwritten. The link\n * fails if the file exists, so this holds across processes too.\n */\nfunction saveNewCard(root: string, card: DecisionCard): DecisionCard {\n mkdirSync(approvalsDir(root), { recursive: true })\n for (let n = 1; ; n++) {\n const saved = n === 1 ? card : { ...card, id: `${card.id}-${n}` }\n const path = fileFor(root, saved.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(saved, null, 2) + \"\\n\")\n try {\n linkSync(tmp, path)\n return saved\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e\n } finally {\n unlinkSync(tmp)\n }\n }\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n followup?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n const followup = oneLine(input.followup).toLowerCase()\n if (followup && !(FOLLOWUP_KINDS as readonly string[]).includes(followup)) {\n return { ok: false, error: `followup must be one of ${FOLLOWUP_KINDS.join(\", \")}` }\n }\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n ...(followup ? { followup: followup as FollowupKind } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** A pending card the same agent, on the same node, raised on the same\n * source. None when the new card has no source or the daemon raised it. */\nfunction sameSourcePending(pending: DecisionCard[], card: DecisionCard): DecisionCard | undefined {\n if (!card.source || card.origin) return undefined\n return pending.find((c) =>\n !c.origin &&\n c.source === card.source &&\n c.raised_by === card.raised_by &&\n (c.node ?? \"\") === (card.node ?? \"\"))\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // The screen gate (#394): refused here, the reason goes back to the author.\n const broken = cardRuleBreak(built.card)\n if (broken) return { ok: false, error: broken }\n if (built.card.followup) {\n const full = followupBudgetRefusal(listCards(root), built.card.followup, opts.now ?? Date.now())\n if (full) return { ok: false, error: full }\n }\n const pending = listCards(root, \"pending\")\n // One open question per source: the same question raised twice comes\n // back after it was answered. Only for cards an agent raised; cards the\n // daemon raises (origin set) keep their own rules, such as a merge card\n // per pushed commit on the same PR link.\n const twin = sameSourcePending(pending, built.card)\n if (twin) {\n return { ok: false, error: `a card from you on this source is still pending: ${twin.id}. Wait for its answer, or resolve it first and then raise the new one.` }\n }\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => isRetroOrigin(c.origin)\n const retro = isRetro(built.card)\n const open = pending.filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n return { ok: true, card: saveNewCard(root, built.card) }\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.suggested ? { choice_suggested: true } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Cards whose answer the daemon acts on itself (a workflow run, a plan\n * step, a retro): only the operator closes those. A reminder card is the\n * agent's own to act on, so it may close it like one it raised. */\nconst AGENT_RESOLVABLE_ORIGINS = new Set<string | undefined>([undefined, \"reminder\"])\n\n/**\n * The raising agent closes its own pending card: the owner gave the same\n * answer outside the card (in chat) and the agent has acted on it (#909).\n * The card leaves the inbox, so no check-in or popup asks again. It is not\n * a verdict, and the agent is not sent a result for it: it already knows.\n */\nexport function resolveCard(\n root: string,\n id: string,\n opts: { by: string; reason?: unknown; node?: string; now?: number },\n): { ok: true; card: DecisionCard } | { ok: false; status: 400 | 403 | 404 | 409; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, status: 404, error: `no card \"${id}\"` }\n if (card.raised_by !== opts.by || (card.node ?? \"\") !== (opts.node ?? \"\")) {\n return { ok: false, status: 403, error: `card \"${id}\" was raised by another agent` }\n }\n if (!AGENT_RESOLVABLE_ORIGINS.has(card.origin?.kind)) {\n return { ok: false, status: 409, error: `card \"${id}\" is answered by the operator only` }\n }\n if (card.status !== \"pending\") return { ok: false, status: 409, error: `card \"${id}\" is already ${card.status}` }\n const reason = oneLine(opts.reason)\n if (!reason) return { ok: false, status: 400, error: \"reason is required: say where the owner answered and what you did\" }\n const at = new Date(opts.now ?? Date.now()).toISOString()\n const resolved: DecisionCard = {\n ...card,\n status: \"resolved\",\n decided_by: opts.by,\n decided_at: at,\n resolution: reason.slice(0, CARD_LIMITS.resolution),\n agent_notified_at: at,\n }\n saveCard(root, resolved)\n return { ok: true, card: resolved }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\nexport const NO_UNDO_LINE =\n \"A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.\"\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n const check = card.origin?.kind === \"retro-check\" ? card.origin : undefined\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro && !check) lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n // A late no on something the owner already approved in chat must not\n // quietly undo work that is done (#909).\n if (card.status === \"decided\" && card.verdict === \"no\" && !retro && !check) lines.push(NO_UNDO_LINE)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (retro || check) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...(retro ? retroLines(retro, card, edited) : retroCheckLines(check!, card, edited)))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\n/** A monthly review of a check a retro added (src/retro/checks.ts): a\n * guard rule tagged `retro:<taskId>` that fires often on runs that went\n * well. The answer goes back to the agent that built it, which keeps,\n * loosens or removes it for a second review. */\nexport interface RetroCheckOrigin {\n kind: \"retro-check\"\n /** The guard rule's id. */\n ruleId: string\n /** The run whose retro asked for the rule. */\n taskId: string\n /** The policy file that holds the rule, relative to the daemon's folder. */\n file: string\n}\n\n/** A step of a workflow run asks the owner (src/workflows, #788): an\n * owner.ask step, a person.message to approve, or a run's approval at\n * start. The answer resumes the run; the agent that started it is not\n * told separately, the run is. */\nexport interface WorkflowOrigin {\n kind: \"workflow\"\n runId: string\n nodeId: string\n}\n\n/** An agent proposed a reusable workflow (#788). Yes turns it on. */\nexport interface WorkflowProposalOrigin {\n kind: \"workflow-proposal\"\n workflowId: string\n}\n\n/** A step of a tracked plan the owner approves when the plan is made\n * (src/requests/plan-sweep.ts, #788). The plan check reads the answer\n * and acts on it; the agent is not sent a result turn. */\nexport interface PlanStepOrigin {\n kind: \"plan-step\"\n requestId: string\n step: number\n}\n\n/** A pull request that changes core paths waits for the owner (merge\n * policy, #1047). YES approves that one commit; the policy reads the\n * answer and updates the PR's status. No agent is sent a result turn. */\nexport interface MergePolicyOrigin {\n kind: \"merge-policy\"\n repo: string\n pr: number\n sha: string\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin | RetroOrigin | RetroCheckOrigin | PlanStepOrigin | WorkflowOrigin | WorkflowProposalOrigin | MergePolicyOrigin\n\n/** Retro cards of either kind: raised for an agent, not by it. */\nexport function isRetroOrigin(origin: CardOrigin | undefined): origin is RetroOrigin | RetroCheckOrigin {\n return origin?.kind === \"retro\" || origin?.kind === \"retro-check\"\n}\n\n/** The choices on a check review card, in this order. */\nexport const CHECK_CHOICES = { keep: \"Keep it\", loosen: \"Loosen it\", remove: \"Remove it\" } as const\n\n/** Lines for the agent told the result of a check review card. Keep, NO\n * and silence all leave the rule as it is. */\nexport function retroCheckLines(\n origin: RetroCheckOrigin,\n card: { status: string; verdict?: string; choice?: string; choice_suggested?: boolean },\n edited?: string,\n): string[] {\n const rule = `guard rule \\`${origin.ruleId}\\` in \\`${origin.file}\\``\n const lines = [`This was a monthly review of ${rule}, added by the retro on run ${origin.taskId}. It fires often on runs that went well.`]\n const yes = card.status === \"decided\" && card.verdict === \"yes\"\n if (!yes || card.choice === CHECK_CHOICES.keep || !card.choice) {\n lines.push(\"Change nothing: the rule stays as it is.\")\n return lines\n }\n lines.push(card.choice === CHECK_CHOICES.remove\n ? `The operator chose to remove it. Delete ${rule} as a pull request.`\n : `The operator chose to loosen it. Narrow ${rule} (a tighter match, or \\`applies_to\\`) so it stops firing on good work, keep its \\`retro:${origin.taskId}\\` tag, and open it as a pull request.`)\n if (card.choice_suggested) lines.push(SUGGESTED_NOTE)\n if (edited) lines.push(\"The operator's note:\", edited)\n lines.push(\"Do not change the live policy directly: the operator reviews the pull request first.\")\n return lines\n}\n\n/** Told to the agent when the choice came from a plain yes (#1064): the\n * operator accepted the suggestion rather than picking it by hand. */\nconst SUGGESTED_NOTE = \"(The operator gave a plain yes, taken as the suggested option.)\"\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[]; choice_suggested?: boolean },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n if (card.choice_suggested) lines.push(SUGGESTED_NOTE)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n","// --- The screen gatekeeper (#394, plan section 1b) ---\n//\n// What the fleet puts on the owner's screen passes one check, by script,\n// no model:\n// - one question per card; a title and an ask short enough to read in\n// about ten seconds (title 120, ask 300 characters);\n// - at most 3 ready-made answers (a plain card has Yes, No, Not now);\n// - follow-up cards (resurface, bring-back, weekly, clean-up) share a\n// budget of 5 a day, at most 3 of them resurface cards;\n// - a title says what it is in words: a bare reference (\"#402\", a hash,\n// a request id) means nothing to someone glancing at a screen.\n// A card that fails is returned to its author with the reason: refused\n// when it is written, or not shown and told when the popup comes to it.\n// Nothing here rewrites, removes or answers a card. The call and Focus\n// hold is notify/hold.ts; the popup window takes no focus (card-window.ts).\n\nexport const SCREEN_LIMITS = { title: 120, ask: 300, answers: 3 } as const\n\nexport const FOLLOWUP_KINDS = [\"resurface\", \"bring-back\", \"weekly\", \"cleanup\"] as const\nexport type FollowupKind = (typeof FOLLOWUP_KINDS)[number]\n\nexport const SCREEN_BUDGET = { perDay: 5, resurface: 3 } as const\n\n// References an agent reads easily and the owner does not: links, issue\n// and merge request numbers (with or without their project), ULID-like\n// ids, request, delegation and send ids, and commit hashes. A hex run\n// needs a digit and a letter a-f, so neither a word made of a-f letters\n// nor a plain long number (a phone number, an amount) is taken for one.\nconst REFERENCES: RegExp[] = [\n /\\bhttps?:\\/\\/\\S+/gi,\n /(?:[\\w.-]+\\/)*[\\w.-]+[#!]\\d+\\b/g,\n /[#!]\\d+\\b/g,\n /\\b[0-9A-HJKMNP-TV-Z]{26}\\b/gi,\n /\\b(?:req|dlg|snd)-[\\w-]+/gi,\n /\\b(?=[0-9a-f]*\\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\\b/gi,\n]\n\n/** The title with every reference taken out. */\nexport function stripReferences(text: string): string {\n return REFERENCES.reduce((t, re) => t.replace(re, \" \"), text)\n}\n\n/** Why a title that is only a reference may not go on screen, or null.\n * A title with a reference must keep at least 2 words of letters once\n * the references are out; a title with none is left to the other rules. */\nexport function referenceOnlyTitle(title: string): string | null {\n const rest = stripReferences(title)\n if (rest === title) return null\n const words = rest.split(/\\s+/).filter((w) => /\\p{L}/u.test(w))\n if (words.length >= 2) return null\n return `title is only a reference (\"${title.trim()}\"); say what it is in plain words, and put the link in the body or source`\n}\n\n/** Why this card may not go on the owner's screen, or null. */\nexport function cardRuleBreak(card: { title?: string; ask?: string; choices?: string[]; origin?: { kind: string } }): string | null {\n // A card file written by hand or by an older build may miss either:\n // returned to its author, never a crash of the popup.\n const title = typeof card.title === \"string\" ? card.title : \"\"\n const ask = typeof card.ask === \"string\" ? card.ask : \"\"\n if (!title.trim()) return \"title is missing: say what it is in plain words\"\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n // A request's card is held to the rule too (#1126): it is titled with\n // its headline, which its agent can write (agentx_request describe).\n const bare = referenceOnlyTitle(title)\n if (bare) return bare\n if (!ask.trim()) return \"ask is missing: one card asks one thing\"\n if (ask.length > SCREEN_LIMITS.ask) return `ask is longer than ${SCREEN_LIMITS.ask} characters`\n if ((ask.match(/\\?/g) ?? []).length > 1) return \"ask holds more than one question: one card asks one thing\"\n if ((card.choices?.length ?? 0) > SCREEN_LIMITS.answers) return `more than ${SCREEN_LIMITS.answers} choices`\n return null\n}\n\n/** Why an agent's `agentx notify` may not go on the owner's screen, or\n * null: the same ten-second rule, title 120 and message 300 (the message\n * as shown, with its \"To do:\" line), and a title in words. */\nexport function noticeRuleBreak(title: string, message: string): string | null {\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n const bare = referenceOnlyTitle(title)\n if (bare) return bare\n if (message.length > SCREEN_LIMITS.ask) return `message is longer than ${SCREEN_LIMITS.ask} characters`\n return null\n}\n\n/** An agent's notice as the owner reads it: the message, then the\n * \"To do:\" line. With nothing to do, it says so, so the owner never has\n * to guess whether a notice wants something. Last, so a banner that\n * shows only the first line still shows the message. */\nexport function withTodo(message: string, todo?: string): string {\n const what = todo?.trim().replace(/\\s+/g, \" \") || \"nothing, FYI\"\n return `${message}\\nTo do: ${what}`\n}\n\n/** Local midnight before `now`: the budget's day. */\nfunction dayStart(now: number): number {\n const d = new Date(now)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/** Why a follow-up card of this kind cannot be raised today, or null.\n * `cards` is every card, of any status: an answered one was on screen too. */\nexport function followupBudgetRefusal(\n cards: Array<{ followup?: FollowupKind; created_at: string }>,\n kind: FollowupKind,\n now: number,\n): string | null {\n const from = dayStart(now)\n const today = cards.filter((c) => c.followup && Date.parse(c.created_at) >= from)\n if (today.length >= SCREEN_BUDGET.perDay) {\n return `the follow-up screen budget is used up today (${SCREEN_BUDGET.perDay} cards): raise it again tomorrow`\n }\n if (kind === \"resurface\" && today.filter((c) => c.followup === \"resurface\").length >= SCREEN_BUDGET.resurface) {\n return `${SCREEN_BUDGET.resurface} resurface cards were already raised today: raise it again tomorrow`\n }\n return null\n}\n\n/** What the author hears when the popup does not show its card. */\nexport function returnedText(card: { id: string; title?: string; origin?: { kind: string } }, reason: string): string {\n const title = card.title?.trim()\n if (card.origin?.kind === \"request\") {\n return [\n `[screen gate] Request ${card.id}${title ? ` (\"${title}\")` : \"\"} was not shown to the owner: ${reason}.`,\n `It is still on his list. Say what it is: agentx_request {action:\"describe\", id:\"${card.id}\", headline:\"<a few plain words>\", need:\"<what you need from him>\"}.`,\n ].join(\" \")\n }\n return [\n `[screen gate] Your card ${card.id}${title ? ` (\"${title}\")` : \"\"} was not shown to the owner: ${reason}.`,\n \"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:\",\n `one question, title up to ${SCREEN_LIMITS.title} characters, ask up to ${SCREEN_LIMITS.ask}, at most ${SCREEN_LIMITS.answers} choices.`,\n ].join(\" \")\n}\n"],"mappings":"6DAAA,OAAS,cAAAA,EAAY,YAAAC,EAAU,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,GAAY,cAAAC,GAAY,iBAAAC,MAAqB,KAClH,OAAS,WAAAC,MAAe,OCwFjB,SAASC,EAAcC,EAA0E,CACtG,OAAOA,GAAQ,OAAS,SAAWA,GAAQ,OAAS,aACtD,CAGO,IAAMC,EAAgB,CAAE,KAAM,UAAW,OAAQ,YAAa,OAAQ,WAAY,EAIlF,SAASC,EACdF,EACAG,EACAC,EACU,CACV,IAAMC,EAAO,gBAAgBL,EAAO,iBAAiBA,EAAO,SACtDM,EAAQ,CAAC,gCAAgCD,gCAAmCL,EAAO,gDAAgD,EAEzI,MAAI,EADQG,EAAK,SAAW,WAAaA,EAAK,UAAY,Q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AaA,EAAK,UAAY,OAAS,CAACwD,GAAS,CAACuB,GAAOD,EAAM,KAAK,GAAGE,EAAYhF,CAAI,CAAC,EACxGA,EAAK,MAAM8E,EAAM,KAAK,kBAAkB9E,EAAK,MAAM,EAGnDA,EAAK,SAAW,WAAaA,EAAK,UAAY,MAAQ,CAACwD,GAAS,CAACuB,GAAOD,EAAM,KAAKL,EAAY,EAC/FzE,EAAK,QAAQ8E,EAAM,KAAK,WAAW9E,EAAK,QAAQ,EAChDA,EAAK,QAAQ,OAAS,YAAY8E,EAAM,KAAK,GAAGG,EAAYjF,EAAK,OAAQA,EAAK,SAAW,WAAaA,EAAK,UAAY,KAAK,CAAC,EAC7HwD,GAASuB,EAAO,CAGlB,IAAMG,EAAUC,GAAcA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACpDC,EAAQC,EAASrF,EAAK,MAAOA,EAAK,MAAM,EACxCsF,EAAStF,EAAK,MAAQkF,EAAOlF,EAAK,IAAI,IAAMkF,EAAOE,CAAK,EAAIpF,EAAK,KAAO,OAC9E8E,EAAM,KAAK,GAAItB,EAAQ+B,EAAW/B,EAAOxD,EAAMsF,CAAM,EAAIE,EAAgBT,EAAQ/E,EAAMsF,CAAM,CAAE,EAEjG,OAAItF,EAAK,OAAO8E,EAAM,KAAK,sBAAsB9E,EAAK,MAAM,gBAAgBA,EAAK,MAAM,mDAAmD,EACtIA,EAAK,MAAM8E,EAAM,KAAK,4EAA4E9E,EAAK,OAAO,EAClH8E,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","linkSync","mkdirSync","readdirSync","readFileSync","renameSync","unlinkSync","writeFileSync","resolve","isRetroOrigin","origin","CHECK_CHOICES","retroCheckLines","card","edited","rule","lines","SUGGESTED_NOTE","retroApproved","RETRO_NONE","retroLines","spec","originLines","approved","where","SCREEN_LIMITS","FOLLOWUP_KINDS","SCREEN_BUDGET","REFERENCES","stripReferences","text","re","referenceOnlyTitle","title","rest","w","cardRuleBreak","card","ask","bare","noticeRuleBreak","message","withTodo","todo","what","dayStart","now","d","followupBudgetRefusal","cards","kind","from","today","c","returnedText","reason","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","saveNewCard","saved","linkSync","e","unlinkSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","followup","FOLLOWUP_KINDS","reply","r","sameSourcePending","pending","createCard","built","broken","cardRuleBreak","full","followupBudgetRefusal","twin","isRetro","isRetroOrigin","retro","open","what","decideCard","verdict","answer","resolveAnswer","note","decided","AGENT_RESOLVABLE_ORIGINS","resolveCard","reason","resolved","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","NO_UNDO_LINE","verdictMessage","result","retroApproved","RETRO_NONE","lines","check","answerLines","originLines","squash","s","draft","draftFor","edited","retroLines","retroCheckLines"]}
@@ -1,4 +1,4 @@
1
- import{a as Re}from"./chunk-GTJIKXDB.js";import{A as Zt,H as rn,j as B}from"./chunk-MOCDP7Q3.js";import{a as w}from"./chunk-7LN4VKDU.js";import{f as en,i as tn,k as Ae,l as _e,n as q,o as M,q as nn}from"./chunk-24QMHUU2.js";import{t as Jt,u as Yt}from"./chunk-3LU2ZQZJ.js";import{d as Gt,e as Kt}from"./chunk-AQASR6KR.js";import{b as Qt}from"./chunk-YMX3QCV7.js";import{a as qt,b as Ht,d as zt,e as Xt}from"./chunk-MNG2AMKZ.js";import{g as Ft,h as Wt,i as Vt,k as Ut,l as Bt}from"./chunk-ZQONMM3B.js";import{a as Mt,c as jt}from"./chunk-KP7KDLZ2.js";import{X as Ot,Z as ne,_ as ve,aa as $e,b as xe}from"./chunk-S5FRIHWM.js";import{q as Lt}from"./chunk-LH3GOBZP.js";import{a as Pt,b as Nt}from"./chunk-BFONYVOM.js";import{Ca as Se,Ka as Tt,La as Ct,Q as _t,R as Rt,S as It,T as Et,Ua as Dt,n as te,o as $t,p as At,q as ni}from"./chunk-5VPU5FHB.js";import{a as we,h as ri}from"./chunk-BRK6M6LA.js";import{f as ke,n as ii}from"./chunk-UIBUZ2N3.js";import{existsSync as si,readdirSync as oi,readFileSync as ai,statSync as li}from"fs";import{resolve as ci}from"path";function sn(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let a of e){let o=s.get(a.workflowId);o?o.push(a):s.set(a.workflowId,[a])}return t.map(a=>{let o=s.get(a.id)??[],l=o.filter(g=>n-g.at<=r),c=o.filter(g=>n-g.at>r&&n-g.at<=r*2),u=l.filter(g=>g.status==="failed").length,d=o.filter(g=>g.status==="paused").length,p=o.length?Math.max(...o.map(g=>g.at)):null,f=o.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:a.id,name:a.name||a.id,state:f,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((a,o)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[a.state]-l[o.state]||(o.lastRunAt??0)-(a.lastRunAt??0)})}var re=new Map;function Wa(t,e=1e3){if(!si(t))return[];let n=oi(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let a=ci(t,s);return{path:a,mtime:li(a).mtimeMs}}).sort((s,a)=>a.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:a}of n){let o=re.get(s);if(o&&o.mtime===a){o.summary&&r.push(o.summary);continue}let l=ui(s,a);re.set(s,{mtime:a,summary:l}),l&&r.push(l)}return r}function ui(t,e){try{let n=ai(t,"utf-8").split(`
1
+ import{a as Re}from"./chunk-GTJIKXDB.js";import{A as Zt,H as rn,j as B}from"./chunk-ZAH74SFX.js";import{a as w}from"./chunk-7LN4VKDU.js";import{f as en,i as tn,k as Ae,l as _e,n as q,o as M,q as nn}from"./chunk-LQS27HSV.js";import{t as Jt,u as Yt}from"./chunk-3LU2ZQZJ.js";import{d as Gt,e as Kt}from"./chunk-AQASR6KR.js";import{b as Qt}from"./chunk-YMX3QCV7.js";import{a as qt,b as Ht,d as zt,e as Xt}from"./chunk-MNG2AMKZ.js";import{g as Ft,h as Wt,i as Vt,k as Ut,l as Bt}from"./chunk-ZQONMM3B.js";import{a as Mt,c as jt}from"./chunk-KP7KDLZ2.js";import{X as Ot,Z as ne,_ as ve,aa as $e,b as xe}from"./chunk-S5FRIHWM.js";import{q as Lt}from"./chunk-LH3GOBZP.js";import{a as Pt,b as Nt}from"./chunk-BFONYVOM.js";import{Ca as Se,Ka as Tt,La as Ct,Q as _t,R as Rt,S as It,T as Et,Ua as Dt,n as te,o as $t,p as At,q as ni}from"./chunk-5VPU5FHB.js";import{a as we,h as ri}from"./chunk-BRK6M6LA.js";import{f as ke,n as ii}from"./chunk-UIBUZ2N3.js";import{existsSync as si,readdirSync as oi,readFileSync as ai,statSync as li}from"fs";import{resolve as ci}from"path";function sn(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let a of e){let o=s.get(a.workflowId);o?o.push(a):s.set(a.workflowId,[a])}return t.map(a=>{let o=s.get(a.id)??[],l=o.filter(g=>n-g.at<=r),c=o.filter(g=>n-g.at>r&&n-g.at<=r*2),u=l.filter(g=>g.status==="failed").length,d=o.filter(g=>g.status==="paused").length,p=o.length?Math.max(...o.map(g=>g.at)):null,f=o.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:a.id,name:a.name||a.id,state:f,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((a,o)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[a.state]-l[o.state]||(o.lastRunAt??0)-(a.lastRunAt??0)})}var re=new Map;function Wa(t,e=1e3){if(!si(t))return[];let n=oi(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let a=ci(t,s);return{path:a,mtime:li(a).mtimeMs}}).sort((s,a)=>a.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:a}of n){let o=re.get(s);if(o&&o.mtime===a){o.summary&&r.push(o.summary);continue}let l=ui(s,a);re.set(s,{mtime:a,summary:l}),l&&r.push(l)}return r}function ui(t,e){try{let n=ai(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let a=n.length-1;a>=0;a--){let o=JSON.parse(n[a]),l=o.status??o.run?.status;if(l){s=l;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var di={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},pi=(t,e,n)=>{try{return Lt(t,e,n)}catch{return null}},on=864e5;function qa(t){let e=t.now??Date.now(),n={...di,...t.thresholds},i=t.nextFire??pi,r=[];for(let o of t.crons){let l=t.cronRuns.get(o.id)??[],c=o.timezone||"UTC",u=l.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=l[0],p={id:`cron:${o.id}`,source:"cron",kind:"schedule",name:A(o.id,k.text),trigger:{schedule:A(o.schedule,k.text),timezone:c},agent:o.agent||null,enabled:o.enabled,state:o.enabled?"enabled":"disabled",nextRunAt:o.enabled?Ie(o.nextRun)??Ie(i(o.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:yi(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:an(u),sampledRuns:l.length,flags:[],attention:null};p.flags=ln(p,u,o.schedule,c,null,e,n,i),r.push(cn(p))}let s=new Map(sn(t.workflows.map(o=>({id:o.id,name:o.title})),t.workflowRuns,e).map(o=>[o.id,o])),a=new Map;for(let o of t.workflowRuns){let l=a.get(o.workflowId);l?l.push(o):a.set(o.workflowId,[o])}for(let o of t.workflows){let l=o.nodes.find(I=>I.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=o.state||"active",d=u==="active",p=(a.get(o.id)??[]).slice().sort((I,ye)=>ye.at-I.at),f=p.map(I=>({at:I.at,status:mi(I.status)})),g=f[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",O={id:`workflow:${o.id}`,source:"workflow",kind:h?"schedule":"event",name:A(o.title||o.id,k.text),trigger:h?{schedule:A(b,k.text),timezone:C}:{event:A(typeof c.event=="string"?c.event:"",k.text),filters:bi(c.filter,o)},agent:hi(o),enabled:d,state:u,nextRunAt:h&&d&&b?Ie(i(b,new Date(e),C)):null,lastRun:g?{at:new Date(g.at).toISOString(),status:g.status}:null,lastSuccessAt:(()=>{let I=f.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:an(f),sampledRuns:p.length,flags:[],attention:null},ee=Date.parse(o.updated||o.created||"");O.flags=h?ln(O,f,b,C,Number.isFinite(ee)?ee:null,e,n,i):fi(O,s.get(o.id)?.state==="dormant",Number.isFinite(ee)?ee:null,e,n),r.push(cn(O))}return r.sort(gi).slice(0,k.routines)}function an(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function ln(t,e,n,i,r,s,a,o){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=dn(c,r,s,a);return p&&l.push(p),l}if(t.consecutiveFailures>=a.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let p=0;p<a.missedFires&&(d=o(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+a.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${a.missedFires} scheduled fires missed`}),l}function fi(t,e,n,i,r){let s=[],a=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let o=dn(a,n,i,r);return o&&s.push(o),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),a===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function dn(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*on?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/on)} days`:"Disabled and never ran"}}function cn(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var un={critical:0,warning:1,info:2};function gi(t,e){let n=t.attention?un[t.attention]:3,i=e.attention?un[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function mi(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function hi(t){if(t.ownerAgent)return A(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?A(String(e.config.agentId),k.text):null}function bi(t,e){let n=[],i=e?.project;if(i&&n.push(A(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let a=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];a.length&&n.push(A(`${r}=${a.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Ie(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function A(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function yi(t,e){return t===void 0?void 0:A(t,e)}import{mkdirSync as wi,readFileSync as ki,renameSync as Si,writeFileSync as xi}from"fs";import{resolve as vi}from"path";function pn(t){return vi(_e(t),"_state.json")}function x(t){try{let e=JSON.parse(ki(pn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function H(t,e){wi(_e(t),{recursive:!0});let n=pn(t),i=`${n}.${process.pid}.tmp`;xi(i,JSON.stringify(e,null,2)+`
3
3
  `),Si(i,n)}function fn(t,e,n,i=Date.now()){let r=x(t),s={};for(let[a,o]of Object.entries(r.snoozed))Date.parse(o)>i&&(s[a]=o);s[e]=n.toISOString(),H(t,{...r,snoozed:s})}function Ka(t,e){H(t,{...x(t),lastDigest:e})}function Ee(t,e,n,i=Date.now()){let r=x(t),s=new Set(n),a={};for(let[l,c]of Object.entries(r.popped??{}))s.has(l)&&(a[l]=c);a[e]=new Date(i).toISOString();let o=(r.wanted??[]).filter(l=>l!==e&&s.has(l));H(t,{...r,popped:a,wanted:o})}function gn(t,e){let n=x(t);H(t,{...n,wanted:[...(n.wanted??[]).filter(i=>i!==e),e]})}function Ja(t,e=Date.now()){H(t,{...x(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as z,readdirSync as Fi,readFileSync as Wi}from"fs";import{resolve as _}from"path";import{randomBytes as bn}from"crypto";import{existsSync as Ai,mkdirSync as _i,readdirSync as Ri,readFileSync as Ii,renameSync as yn,unlinkSync as Ei,writeFileSync as Ti}from"fs";import{resolve as wn}from"path";function mn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var $i=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function hn(t,e,n,i=Re){let r=await i(t.bin,[...mn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${$i(r.stderr||r.stdout)}`}}async function Qa(t,e,n,i,r=Re){return(await r(t.bin,[...mn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var Ci=2e3,Di=t=>hn(t.wacli,t.to,t.text);function Te(t){return wn(t,".agentx","whatsapp-triage","drafts")}var Pi=t=>/^[a-z0-9-]{8,64}$/.test(t),ie=(t,e)=>wn(Te(t),`${e}.json`);function kn(t,e){_i(Te(t),{recursive:!0});let n=ie(t,e.id),i=`${n}.${process.pid}.tmp`;Ti(i,JSON.stringify(e,null,2)+`
@@ -530,4 +530,4 @@ Document the arguments, commands, or files the skill expects. Example:
530
530
  claude-code ${vt(t)} --arg value
531
531
  \`\`\`
532
532
  `}Dt();var Zr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Qr(t){return{...Zr,...t??{},regions:{...t?.regions??{}},buffer:{...Zr.buffer,...t?.buffer??{}}}}function wd(t){try{return Qr(Ct(t).screen)}catch{return Qr(void 0)}}var Ma=/^[a-z][\w-]*$/,ei=["window","screen","menubar","notifications"];function Q(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var be=(t,e)=>Q(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ti(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function kd(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=be(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=be(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=be(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Q(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Q(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,a]of Object.entries(e.regions)){if(!Ma.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);a===null?delete r[s]:r[s]=ti(a)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Q(r.seconds,"buffer.seconds",a=>a>0&&a<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Q(r.fps,"buffer.fps",a=>a>0&&a<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=be(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!ei.includes(i)&&!n.regions?.[i])try{ti(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...ei,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{sn as a,Wa as b,rt as c,to as d,no as e,Rc as f,Ic as g,Ec as h,dr as i,Cc as j,Pc as k,D as l,pr as m,k as n,qa as o,mr as p,Fc as q,Qa as r,Di as s,sl as t,xn as u,x as v,Ka as w,Ja as x,ll as y,oe as z,cl as A,An as B,ml as C,X as D,Cl as E,Dl as F,Cn as G,hr as H,Uc as I,Er as J,yu as K,wu as L,Au as M,ea as N,_u as O,Nl as P,Ll as Q,Ol as R,Ml as S,jl as T,Fl as U,Vl as V,Ul as W,Yl as X,Fe as Y,Zl as Z,Ql as _,G as $,K as aa,oa as ba,Lu as ca,Ou as da,Mu as ea,ju as fa,dt as ga,Fu as ha,Ue as ia,Be as ja,pe as ka,Ss as la,vs as ma,ic as na,He as oa,ze as pa,$s as qa,As as ra,Yn as sa,tr as ta,sc as ua,Is as va,oc as wa,Os as xa,Fs as ya,Xe as za,Vs as Aa,nr as Ba,P as Ca,Vr as Da,Ur as Ea,Br as Fa,Hu as Ga,ma as Ha,Hr as Ia,zr as Ja,nd as Ka,rd as La,Ca as Ma,id as Na,Gr as Oa,fe as Pa,yc as Qa,lr as Ra,Ge as Sa,tt as Ta,Ac as Ua,ld as Va,cd as Wa,ud as Xa,dd as Ya,pd as Za,fd as _a,gd as $a,md as ab,hd as bb,Zr as cb,Qr as db,wd as eb,ei as fb,kd as gb};
533
- //# sourceMappingURL=chunk-D6U37WO3.js.map
533
+ //# sourceMappingURL=chunk-VAK4LT62.js.map