agentix-cli 0.175.0 → 0.176.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-HRSFSBI5.js → App-43V7KUZU.js} +2 -2
- package/dist/{ChatApp-KZZ6YWVU.js → ChatApp-ZG2IXOB5.js} +2 -2
- package/dist/{absorb-eval-X7QPMUEZ.js → absorb-eval-4NMMBFH3.js} +2 -2
- package/dist/{adapter-EMCXJRO3.js → adapter-57X4HJEA.js} +2 -2
- package/dist/{agent-EYHO245T.js → agent-UZ5B5KHN.js} +2 -2
- package/dist/{board-dashboard-CTLHX6WG.js → board-dashboard-TGV3TPGV.js} +533 -351
- package/dist/board-dashboard-TGV3TPGV.js.map +1 -0
- package/dist/{chunk-KNEQTWMO.js → chunk-2BI43ZKI.js} +2 -2
- package/dist/{chunk-YJ2BOGSB.js → chunk-3VZNOJJK.js} +2 -2
- package/dist/{chunk-X3YH6GOI.js → chunk-3X2BFCOZ.js} +2 -2
- package/dist/{chunk-NZRZCDL5.js → chunk-5DJOGAS2.js} +3 -3
- package/dist/{chunk-NZZ3VMUX.js → chunk-6FNJ7GQ2.js} +2 -2
- package/dist/{chunk-UQYHAZGX.js → chunk-7NJLRLQN.js} +2 -2
- package/dist/{chunk-OUKZ4NHL.js → chunk-7WMZJFYD.js} +2 -2
- package/dist/{chunk-YJGTPW2U.js → chunk-BCDC7BOQ.js} +2 -2
- package/dist/{chunk-USKCGOC7.js → chunk-BU57BT5P.js} +2 -2
- package/dist/{chunk-LCFWZO4U.js → chunk-CVFQA3TH.js} +2 -2
- package/dist/{chunk-SDLVAU6H.js → chunk-DUWKRQKT.js} +2 -2
- package/dist/{chunk-KEEGZCNJ.js → chunk-FXMUUDSH.js} +2 -2
- package/dist/{chunk-46EB6D4T.js → chunk-FZMS4UFL.js} +2 -2
- package/dist/{chunk-UOJNEQF4.js → chunk-KPRWATQR.js} +2 -2
- package/dist/{chunk-YUNNLQBF.js → chunk-KUZATIJA.js} +2 -2
- package/dist/{chunk-LTMAJTP2.js → chunk-L7F226TX.js} +2 -2
- package/dist/{chunk-BGYR4EPU.js → chunk-M4BNVLGJ.js} +2 -2
- package/dist/{chunk-U6XMXIA7.js → chunk-N4TDTQOQ.js} +2 -2
- package/dist/{chunk-3VEEW7SP.js → chunk-OHPCZOOM.js} +2 -2
- package/dist/chunk-P7FSTC5E.js +95 -0
- package/dist/chunk-P7FSTC5E.js.map +1 -0
- package/dist/{chunk-3LZQWFGM.js → chunk-PHT6HTAW.js} +2 -2
- package/dist/{chunk-KNGGBS65.js → chunk-QJKQELHR.js} +2 -2
- package/dist/{chunk-56Y62EGM.js → chunk-RMSB6DKW.js} +2 -2
- package/dist/{chunk-7ZCDBVD3.js → chunk-S7VM573Z.js} +8 -8
- package/dist/{chunk-7ZCDBVD3.js.map → chunk-S7VM573Z.js.map} +1 -1
- package/dist/{chunk-CGZGH52Z.js → chunk-SRX5O2BY.js} +2 -2
- package/dist/{chunk-NHFRIGYP.js → chunk-T7E33M6T.js} +2 -2
- package/dist/{chunk-AZ7TDLKK.js → chunk-XWDZ37QZ.js} +5 -5
- package/dist/{chunk-IVT5UL6Z.js → chunk-YIR6FABW.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-U3YRLY5M.js → client-NJKGG5OP.js} +2 -2
- package/dist/{config-RUSWVRCC.js → config-HILBFLHC.js} +2 -2
- package/dist/{config-mutate-I7E6KLGG.js → config-mutate-SJYPUDP5.js} +2 -2
- package/dist/config-mutator-XGZRKKD4.js +2 -0
- package/dist/{contributions-EVS22MET.js → contributions-HN3JAPFB.js} +2 -2
- package/dist/{doctor-6NDWH2LP.js → doctor-6P5PYFMD.js} +2 -2
- package/dist/{follow-up-tool-RZNVRUQA.js → follow-up-tool-MXMT3GED.js} +2 -2
- package/dist/{hub-3JUD7I7H.js → hub-EBZO3VRY.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-UMCD7LFG.js → program-ODIIYCDI.js} +23 -23
- package/dist/{promote-VNWRVOWL.js → promote-M3GWICXS.js} +2 -2
- package/dist/{query-CMVHHWE2.js → query-XBRRKY6I.js} +2 -2
- package/dist/{query-settings-NHKHJTIK.js → query-settings-3UVI3UQF.js} +2 -2
- package/dist/{registry-PBGQYAEQ.js → registry-3MN45PGY.js} +2 -2
- package/dist/{request-planner-A5VKSQWQ.js → request-planner-45D32J2H.js} +2 -2
- package/dist/{review-candidates-FGBSO737.js → review-candidates-VOTQHP2K.js} +2 -2
- package/dist/{routing-FQILCGHI.js → routing-SPX5VDTG.js} +2 -2
- package/dist/schedule-tool-IUUGZFJ3.js +2 -0
- package/dist/{scheduler-LJCOVYSF.js → scheduler-OVYVZN6N.js} +2 -2
- package/dist/{seat-XXB3ERRK.js → seat-4VQ2X5PF.js} +2 -2
- package/dist/{select-PF4QRFWX.js → select-2QW6SYWW.js} +2 -2
- package/dist/{set-enabled-5X7MWSZH.js → set-enabled-API6VRUP.js} +2 -2
- package/dist/{sprint-tool-YZJRGNTI.js → sprint-tool-4PLRLWOU.js} +2 -2
- package/dist/{tool-BJ36R3BG.js → tool-CMOZJTA2.js} +2 -2
- package/dist/{tool-JWVTXZKH.js → tool-PVFI2DWN.js} +2 -2
- package/dist/{tool-ZTI26AAK.js → tool-XEGKIHUP.js} +2 -2
- package/dist/{wiki-TV5RG5OW.js → wiki-3MTKUBPS.js} +2 -2
- package/dist/wiki-enrich-DCTK64E4.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-CTLHX6WG.js.map +0 -1
- package/dist/chunk-V26F75GZ.js +0 -93
- package/dist/chunk-V26F75GZ.js.map +0 -1
- package/dist/config-mutator-DZRJHWF6.js +0 -2
- package/dist/schedule-tool-YB6XBEUJ.js +0 -2
- package/dist/wiki-enrich-5HSWVE3O.js +0 -2
- /package/dist/{App-HRSFSBI5.js.map → App-43V7KUZU.js.map} +0 -0
- /package/dist/{ChatApp-KZZ6YWVU.js.map → ChatApp-ZG2IXOB5.js.map} +0 -0
- /package/dist/{absorb-eval-X7QPMUEZ.js.map → absorb-eval-4NMMBFH3.js.map} +0 -0
- /package/dist/{adapter-EMCXJRO3.js.map → adapter-57X4HJEA.js.map} +0 -0
- /package/dist/{agent-EYHO245T.js.map → agent-UZ5B5KHN.js.map} +0 -0
- /package/dist/{chunk-KNEQTWMO.js.map → chunk-2BI43ZKI.js.map} +0 -0
- /package/dist/{chunk-YJ2BOGSB.js.map → chunk-3VZNOJJK.js.map} +0 -0
- /package/dist/{chunk-X3YH6GOI.js.map → chunk-3X2BFCOZ.js.map} +0 -0
- /package/dist/{chunk-NZRZCDL5.js.map → chunk-5DJOGAS2.js.map} +0 -0
- /package/dist/{chunk-NZZ3VMUX.js.map → chunk-6FNJ7GQ2.js.map} +0 -0
- /package/dist/{chunk-UQYHAZGX.js.map → chunk-7NJLRLQN.js.map} +0 -0
- /package/dist/{chunk-OUKZ4NHL.js.map → chunk-7WMZJFYD.js.map} +0 -0
- /package/dist/{chunk-YJGTPW2U.js.map → chunk-BCDC7BOQ.js.map} +0 -0
- /package/dist/{chunk-USKCGOC7.js.map → chunk-BU57BT5P.js.map} +0 -0
- /package/dist/{chunk-LCFWZO4U.js.map → chunk-CVFQA3TH.js.map} +0 -0
- /package/dist/{chunk-SDLVAU6H.js.map → chunk-DUWKRQKT.js.map} +0 -0
- /package/dist/{chunk-KEEGZCNJ.js.map → chunk-FXMUUDSH.js.map} +0 -0
- /package/dist/{chunk-46EB6D4T.js.map → chunk-FZMS4UFL.js.map} +0 -0
- /package/dist/{chunk-UOJNEQF4.js.map → chunk-KPRWATQR.js.map} +0 -0
- /package/dist/{chunk-YUNNLQBF.js.map → chunk-KUZATIJA.js.map} +0 -0
- /package/dist/{chunk-LTMAJTP2.js.map → chunk-L7F226TX.js.map} +0 -0
- /package/dist/{chunk-BGYR4EPU.js.map → chunk-M4BNVLGJ.js.map} +0 -0
- /package/dist/{chunk-U6XMXIA7.js.map → chunk-N4TDTQOQ.js.map} +0 -0
- /package/dist/{chunk-3VEEW7SP.js.map → chunk-OHPCZOOM.js.map} +0 -0
- /package/dist/{chunk-3LZQWFGM.js.map → chunk-PHT6HTAW.js.map} +0 -0
- /package/dist/{chunk-KNGGBS65.js.map → chunk-QJKQELHR.js.map} +0 -0
- /package/dist/{chunk-56Y62EGM.js.map → chunk-RMSB6DKW.js.map} +0 -0
- /package/dist/{chunk-CGZGH52Z.js.map → chunk-SRX5O2BY.js.map} +0 -0
- /package/dist/{chunk-NHFRIGYP.js.map → chunk-T7E33M6T.js.map} +0 -0
- /package/dist/{chunk-AZ7TDLKK.js.map → chunk-XWDZ37QZ.js.map} +0 -0
- /package/dist/{chunk-IVT5UL6Z.js.map → chunk-YIR6FABW.js.map} +0 -0
- /package/dist/{client-U3YRLY5M.js.map → client-NJKGG5OP.js.map} +0 -0
- /package/dist/{config-RUSWVRCC.js.map → config-HILBFLHC.js.map} +0 -0
- /package/dist/{config-mutate-I7E6KLGG.js.map → config-mutate-SJYPUDP5.js.map} +0 -0
- /package/dist/{config-mutator-DZRJHWF6.js.map → config-mutator-XGZRKKD4.js.map} +0 -0
- /package/dist/{contributions-EVS22MET.js.map → contributions-HN3JAPFB.js.map} +0 -0
- /package/dist/{doctor-6NDWH2LP.js.map → doctor-6P5PYFMD.js.map} +0 -0
- /package/dist/{follow-up-tool-RZNVRUQA.js.map → follow-up-tool-MXMT3GED.js.map} +0 -0
- /package/dist/{hub-3JUD7I7H.js.map → hub-EBZO3VRY.js.map} +0 -0
- /package/dist/{program-UMCD7LFG.js.map → program-ODIIYCDI.js.map} +0 -0
- /package/dist/{promote-VNWRVOWL.js.map → promote-M3GWICXS.js.map} +0 -0
- /package/dist/{query-CMVHHWE2.js.map → query-XBRRKY6I.js.map} +0 -0
- /package/dist/{query-settings-NHKHJTIK.js.map → query-settings-3UVI3UQF.js.map} +0 -0
- /package/dist/{registry-PBGQYAEQ.js.map → registry-3MN45PGY.js.map} +0 -0
- /package/dist/{request-planner-A5VKSQWQ.js.map → request-planner-45D32J2H.js.map} +0 -0
- /package/dist/{review-candidates-FGBSO737.js.map → review-candidates-VOTQHP2K.js.map} +0 -0
- /package/dist/{routing-FQILCGHI.js.map → routing-SPX5VDTG.js.map} +0 -0
- /package/dist/{schedule-tool-YB6XBEUJ.js.map → schedule-tool-IUUGZFJ3.js.map} +0 -0
- /package/dist/{scheduler-LJCOVYSF.js.map → scheduler-OVYVZN6N.js.map} +0 -0
- /package/dist/{seat-XXB3ERRK.js.map → seat-4VQ2X5PF.js.map} +0 -0
- /package/dist/{select-PF4QRFWX.js.map → select-2QW6SYWW.js.map} +0 -0
- /package/dist/{set-enabled-5X7MWSZH.js.map → set-enabled-API6VRUP.js.map} +0 -0
- /package/dist/{sprint-tool-YZJRGNTI.js.map → sprint-tool-4PLRLWOU.js.map} +0 -0
- /package/dist/{tool-BJ36R3BG.js.map → tool-CMOZJTA2.js.map} +0 -0
- /package/dist/{tool-JWVTXZKH.js.map → tool-PVFI2DWN.js.map} +0 -0
- /package/dist/{tool-ZTI26AAK.js.map → tool-XEGKIHUP.js.map} +0 -0
- /package/dist/{wiki-TV5RG5OW.js.map → wiki-3MTKUBPS.js.map} +0 -0
- /package/dist/{wiki-enrich-5HSWVE3O.js.map → wiki-enrich-DCTK64E4.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$a as er,A as Wp,Aa as La,B as Up,Ba as _f,C as Xt,Ca as Fa,D as Vs,Da as kt,E as Gp,Ea as Uf,F as Hp,Fa as Gf,G as Bp,H as Kp,I as zp,Ia as vt,Ib as Ga,J as Yp,Ja as Hf,Jb as Ha,K as Qp,Ka as Bf,L as Zp,La as qf,Lb as um,M as ef,Ma as Xf,N as tf,Na as Vf,O as nf,Oa as Jf,P as sf,Q as rf,Qa as ve,R as _a,Ra as Qs,Sa as Wa,Ta as Kf,U as of,Ua as On,Va as zf,W as af,Wa as Oe,Xa as Yf,Ya as Qf,Za as Zf,_a as Zs,a as mp,ab as em,b as $a,ba as zs,bb as tm,ca as vf,ea as Sf,f as Ia,fa as Oa,g as yp,gb as nm,h as wp,i as Ta,ia as $f,j as bp,k as Mn,ka as If,kb as sm,l as kp,m as vp,mb as tr,n as Sp,na as Tf,nb as Ua,o as Qe,oa as xf,ob as rm,p as $p,pa as Af,pb as im,q as Ip,qa as Da,qb as om,ra as Rf,rb as am,s as Tp,ta as Ef,tb as cm,u as xp,ua as Na,v as Ze,va as Cf,w as Aa,wa as et,x as Lp,xa as Pf,y as jp,ya as Ys,yb as dm,z as Fp,zb as lm}from"./chunk-
|
|
1
|
+
import{$a as er,A as Wp,Aa as La,B as Up,Ba as _f,C as Xt,Ca as Fa,D as Vs,Da as kt,E as Gp,Ea as Uf,F as Hp,Fa as Gf,G as Bp,H as Kp,I as zp,Ia as vt,Ib as Ga,J as Yp,Ja as Hf,Jb as Ha,K as Qp,Ka as Bf,L as Zp,La as qf,Lb as um,M as ef,Ma as Xf,N as tf,Na as Vf,O as nf,Oa as Jf,P as sf,Q as rf,Qa as ve,R as _a,Ra as Qs,Sa as Wa,Ta as Kf,U as of,Ua as On,Va as zf,W as af,Wa as Oe,Xa as Yf,Ya as Qf,Za as Zf,_a as Zs,a as mp,ab as em,b as $a,ba as zs,bb as tm,ca as vf,ea as Sf,f as Ia,fa as Oa,g as yp,gb as nm,h as wp,i as Ta,ia as $f,j as bp,k as Mn,ka as If,kb as sm,l as kp,m as vp,mb as tr,n as Sp,na as Tf,nb as Ua,o as Qe,oa as xf,ob as rm,p as $p,pa as Af,pb as im,q as Ip,qa as Da,qb as om,ra as Rf,rb as am,s as Tp,ta as Ef,tb as cm,u as xp,ua as Na,v as Ze,va as Cf,w as Aa,wa as et,x as Lp,xa as Pf,y as jp,ya as Ys,yb as dm,z as Fp,zb as lm}from"./chunk-FZMS4UFL.js";import{d as gp,g as pp,h as fp}from"./chunk-YIR6FABW.js";import{a as Ap}from"./chunk-ZVP6GB4G.js";import{A as Pp,B as _p,D as Bs,E as Ra,F as qs,G as qt,K as cf,c as Jg,d as Kg,f as zg,g as _n,h as Hs,i as ka,j as Yg,k as Ke,z as Cp}from"./chunk-6FNJ7GQ2.js";import{b as Mf,c as Of,d as ja,e as Df,f as Nf,g as Lf,h as jf,i as Ff}from"./chunk-EKJG63EJ.js";import{b as Wf}from"./chunk-N6VBEITO.js";import{d as Mp}from"./chunk-6V5JBHUN.js";import{g as Op}from"./chunk-LQE73AZR.js";import{b as Dp,c as Np}from"./chunk-2D3RYIDU.js";import{b as df}from"./chunk-MRIVENBY.js";import{i as lf,m as Ma,n as uf,p as hf,q as gf,r as pf,s as ff,t as mf,u as yf}from"./chunk-FRR6DRLY.js";import{e as Ea,k as Ca,l as qp,m as Js,n as bt,o as Vt,p as Me,r as Xp,s as Vp,t as Jp,u as Pa,v as Ks}from"./chunk-LQS27HSV.js";import{a as wf}from"./chunk-PPUN7YHA.js";import{a as bf,b as kf}from"./chunk-VZLIBDLH.js";import{a as Rp,b as Ep}from"./chunk-A5GYG56I.js";import{o as xa}from"./chunk-3X2BFCOZ.js";import{b as Xs}from"./chunk-UKUH662W.js";import{a as Ye}from"./chunk-MNG2AMKZ.js";import{c as rp,d as ip,f as op,g as ap,i as cp,k as dp,l as lp}from"./chunk-RX5O5637.js";import{b as up,c as hp}from"./chunk-X7UQY7CH.js";import{a as va,b as Qg,c as Zg}from"./chunk-QPABR72X.js";import{a as ep,b as ze,c as tp,d as np,e as sp}from"./chunk-AJ5HMDRW.js";import{c as Bt}from"./chunk-KP7KDLZ2.js";import{$ as wa,A as B,C as Ah,D as Rh,E as Eh,F as Ch,G as ge,H as _h,I as Mh,J as Oh,K as Dh,L as Bh,M as qh,N as Xh,O as Mg,P as Og,Q as Dg,R as Ng,S as Lg,T as jg,V as Pn,W as Fg,Z as ie,_ as Je,a as Yu,aa as Ut,b as ia,ba,c as Zu,ca as Us,d as ah,da as Gt,e as ch,ea as Ht,f as An,fa as me,ga as wt,h as aa,ha as oe,i as ca,ia as Wg,j as da,ja as Ug,k as la,l as dh,ma as Bg,s as uh,t as fh,u as mt,v as mh,w as yh,x as wh,xa as qg,y as Wt,z as vh}from"./chunk-XWDZ37QZ.js";import{$ as vg,Da as Hg,G as Gh,H as Hh,N as Vh,P as Jh,R as dg,S as lg,T as mg,U as yg,V as wg,W as bg,Y as ya,Z as Ws,_ as kg,a as hh,aa as Sg,ba as $g,c as bh,ca as Ig,d as kh,da as Tg,e as yt,ea as xg,f as _e,fa as Ag,h as Nh,ha as Rg,i as Lh,j as jh,k as ha,ka as Eg,l as Fh,m as Wh,p as Uh,pa as Cg,q as Ls,qa as Pg,ta as _g,xa as Gg}from"./chunk-M4BNVLGJ.js";import{a as ua,b as ph}from"./chunk-MEFPXHQJ.js";import{A as Xg,B as Gs,C as Vg,h as Gl,n as Hl,o as jo}from"./chunk-SRX5O2BY.js";import{b as Fl}from"./chunk-SFQUP3BP.js";import{a as Sa}from"./chunk-6TTGRTDO.js";import{a as Kh,b as ga,c as zh,d as Yh,e as Qh,i as Zh,j as eg}from"./chunk-VE3SSOQX.js";import{b as Ph}from"./chunk-W4YR2RO2.js";import{b as ng,c as sg,d as pa,f as js,g as rg,h as ig,i as og,j as Cn,k as Fs,m as fa,n as ag,o as cg}from"./chunk-VJVXEVZ7.js";import{b as he,d as Be,f as qe,g as Rn,i as fe,j as tg,k as Xe,l as Ve,m as gg,p as pg,r as fg,t as ma}from"./chunk-CVFQA3TH.js";import{a as ug,b as hg}from"./chunk-KUZATIJA.js";import{b as gh}from"./chunk-PE5V2LI7.js";import{d as Sh,e as $h,f as Ih,g as Th,h as xh,j as En}from"./chunk-X5C5W3E4.js";import{c as Ns}from"./chunk-OWNQ2FD4.js";import{c as lh}from"./chunk-LUOW2YHY.js";import{d as ql,e as eT,m as Vu,n as gT,q as Ju,v as Ku,x as ra,y as He,z as xn}from"./chunk-FXMUUDSH.js";import{a as Pe,b as Tn,f as Os}from"./chunk-72SZI2UW.js";import{a as Sn,b as Bl}from"./chunk-FCPTN6NF.js";import{c as zu}from"./chunk-MYVHVJWZ.js";import{f as Qu}from"./chunk-QUFIUXMQ.js";import{d as eh,e as th,f as oa,g as Ds,h as nh,i as sh,j as rh,k as ih,q as oh}from"./chunk-AV7T3SYT.js";import{o as Lo,p as ZI}from"./chunk-DCIYOPJF.js";import{a as Ts,b as QI}from"./chunk-7I7IEX4S.js";import{b as Wl,e as Ul}from"./chunk-JHCI6XCJ.js";import{e as ut}from"./chunk-DSYKYZMT.js";import{Aa as Lu,B as Bo,Ba as In,C as nu,Ca as ju,D as su,Da as Fu,E as $n,Ea as Wu,F as Cs,Fa as Uu,G as ru,Ga as Gu,H as iu,Ha as dT,I as mu,J as oT,K as yu,Ka as Hu,M as Jo,N as wu,Na as Bu,O as bu,Oa as qu,P as aT,Q as ku,R as cT,Sa as lT,T as pt,U as vu,Ua as na,W as Ko,Wa as uT,X as zo,Y as Ge,Z as Ft,_ as Su,aa as Yo,ba as Qo,ca as $u,da as Iu,f as jt,fa as Tu,g as Vl,ga as xu,h as Wo,ha as ft,i as tT,ia as Zo,j as xs,ja as Au,k as Uo,ka as Ru,l as As,la as Ps,ma as Eu,n as ht,na as _s,o as Go,oa as Cu,p as Jl,pa as Pu,pb as sa,q as nT,qa as _u,r as Rs,ra as Mu,rb as Xu,s as sT,sa as ea,t as Es,ta,u as Kl,v as rT,va as Ms,w as zl,wa as Ou,x as Yl,y as Ql,ya as Du,yb as hT,za as Nu}from"./chunk-P7FSTC5E.js";import{a as Zl,e as gt,f as eu,g as tu,h as Ho}from"./chunk-VJ5HC63R.js";import{a as ou,b as au,c as cu,e as du,f as lu,i as iT,j as qo,k as uu,l as hu,m as Xo,n as gu,o as pu,q as Vo,r as fu}from"./chunk-UEEB3UTU.js";import{b as Fo,e as Xl}from"./chunk-VQRY4IDI.js";import{d as Lt}from"./chunk-QIJLFPWE.js";import{existsSync as za,readFileSync as Ya}from"fs";Ql();var hm=["answer","narration","line"],gm=5e3;function pm(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function fm(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let d=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!d||!l||!hm.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${hm.join(" | ")}`}};if(d.length>gm)return{status:413,body:{error:`text is over ${gm} characters`}};let h=e(l);if(!h)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:f,done:y}=r.enqueue({voice:h,text:d,agentId:l,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:f}}:{status:200,body:{item:f,played:await y}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,o,a,c]=n.split("/");if(t!=="POST"||!o||c!==void 0)return{status:404,body:{error:"Not found"}};switch(a){case"skip":return r.skip(o)?{status:200,body:r.view()}:Ba(o);case"front":return r.front(o)?{status:200,body:r.view()}:Ba(o);case"replay":{let d=r.replay(o);return d?{status:202,body:{item:d}}:Ba(o)}default:return{status:404,body:{error:"Not found"}}}}function mm(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`,t=r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.";return[...r.floor?.held?[Yl(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
|
|
2
2
|
`)}var Ba=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});var pT=20,qa=120,fT=80,mT=new Set(["waiting_owner","needs_attention"]);function Xa(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function nr(r){return{total:r.length,items:r.slice(0,pT)}}var Va=r=>new Date(r).toISOString();function ym(r){return{id:r.id,agentId:r.agentId,kind:r.kind,text:Xa(r.text,fT),enqueuedAt:Va(r.enqueuedAt)}}function wm(r){let e=r.cards.filter(i=>i.status==="pending").sort((i,o)=>String(i.created_at??"").localeCompare(String(o.created_at??""))).map(i=>({id:i.id,title:Xa(i.title,qa),raised_by:i.raised_by,node:i.node??null,createdAt:i.created_at})),t=[...r.held].sort((i,o)=>i.at.localeCompare(o.at)).map(i=>({id:i.id,title:Xa(i.title,qa),from:i.from,at:i.at,heldBecause:i.heldBecause})),n=(r.requests??[]).filter(i=>mT.has(i.state)).sort((i,o)=>i.createdAt-o.createdAt).map(i=>({id:i.id,title:Ke(i,qa).headline,agentId:i.agentId,state:i.state,since:Va(i.stateChangedAt??i.updatedAt)})),s=r.voice;return{ts:Va(r.now),cards:nr(e),held:nr(t),voice:s?{paused:s.paused,reserved:s.reserved,playing:s.playing?ym(s.playing):null,waiting:nr(s.waiting.map(ym))}:null,requests:nr(n),errors:r.errors??[]}}function bm(r){let e=[],t=n=>n.total>n.items.length?[` \u2026 and ${n.total-n.items.length} more`]:[];e.push(`Decision cards waiting for an answer: ${r.cards.total}`);for(let n of r.cards.items)e.push(` - ${n.title} (by ${n.raised_by}${n.node?` on ${n.node}`:""}, ${n.createdAt}, ${n.id})`);e.push(...t(r.cards)),e.push(`Notices held by Focus or a call: ${r.held.total}`);for(let n of r.held.items)e.push(` - ${n.title} (from ${n.from}, ${n.at})`);if(e.push(...t(r.held)),r.voice){let n=r.voice.paused?", paused":r.voice.reserved?", the floor is held":"";e.push(`Speaking now: ${r.voice.playing?`${r.voice.playing.agentId??"the host"}: ${r.voice.playing.text}`:"nothing"}${n}`),e.push(`Lines waiting to be spoken: ${r.voice.waiting.total}`);for(let s of r.voice.waiting.items)e.push(` - ${s.agentId??"the host"} (${s.kind}): ${s.text}`);e.push(...t(r.voice.waiting))}e.push(`Open requests waiting on the owner: ${r.requests.total}`);for(let n of r.requests.items)e.push(` - ${n.title} (${n.agentId}, ${n.state.replace("_"," ")} since ${n.since}, ${n.id})`);e.push(...t(r.requests));for(let n of r.errors)e.push(`Could not read: ${n}`);return e.join(`
|
|
3
3
|
`)}import{resolve as Qa}from"path";uT();var yT={name:"agentx",version:"0.1.0"},wT=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],bT="2024-11-05";function kT(r){return typeof r=="string"&&wT.includes(r)?r:bT}var vT={tools:{},elicitation:{form:{}}},ST=0;async function km(r,e){let t=++ST;return St({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Nn.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Nn.has(`elicit-${t}`)&&(Nn.delete(`elicit-${t}`),n(null))},6e4)})}var Nn=new Map,$T="http://localhost:18800",Ja;function IT(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=Qa(process.cwd(),r);if(!za(e))continue;let t=JSON.parse(Ya(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return $T}function X(){return Ja===void 0&&(Ja=IT()),Ja}var Ka;function TT(r){try{let e=Qa(process.cwd(),".env");if(!za(e))return"";for(let t of Ya(e,"utf-8").split(`
|
|
4
4
|
`)){let n=t.trim().replace(/^export\s+/,"");if(!n.startsWith(`${r}=`))continue;let s=n.slice(r.length+1).trim();return/^(["']).*\1$/.test(s)?s.slice(1,-1):s}}catch{}return""}function xT(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=TT("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=Qa(process.cwd(),t);if(!za(n))continue;let s=JSON.parse(Ya(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function AT(){return Ka===void 0&&(Ka=xT()),Ka}var J=(r,e)=>{let t=AT();if(!t)return fetch(r,e);let n=new Headers(e?.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${t}`),fetch(r,{...e,headers:n})};function Dn(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function RT(){let r=process.env.AGENTX_AGENT_ID,e=Dn();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await J(`${X()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var ET=1e4,CT=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function PT(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&CT.has(n))return`Error: the AgentX daemon could not be reached (${n}); the message to ${r} was not sent.`;let s=t?.name==="TimeoutError"||t?.name==="AbortError"?"no answer in time":t?.message||String(e);return`Probably delivered to ${r}: the daemon did not confirm (${s}), but the request was sent and is most likely queued. Do not treat this as a failure. If unsure, send the same message again: within 10 minutes a repeat returns the existing task id instead of a second task, and delivers it if the first never arrived. A busy ${r} shows no trace until its turn starts; later, \`agentx trace list --agent ${r} --since 1h\` or the daemon log ("[send/agent]") shows it.`}var _T=/\x1B\[[0-9;]*[A-Za-z]/g;function Jt(r){return r.replace(_T,"")}async function MT(r,e,t){let n=await J(`${X()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:OT(i,!!s.hasMore)}]}}function OT(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
|
|
@@ -41,7 +41,7 @@ ${String(w.plan.text).split(`
|
|
|
41
41
|
`)}]}:{content:[{type:"text",text:"No stopped tasks."}]}}if(n!=="stop"&&n!=="resume")return{content:[{type:"text",text:"Error: action must be stop, resume or list."}]};let a=n==="stop"?{taskId:o(e.taskId),agentId:o(e.agentId),channel:o(e.channel),chatId:o(e.chatId),reason:o(e.reason),node:o(e.node),from:s}:{id:o(e.id),reason:o(e.reason),node:o(e.node),from:s},c=await J(`${X()}/api/signals/${n}`,{method:"POST",headers:{"Content-Type":"application/json",...i},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)}),d=await c.json().catch(()=>({}));return c.ok?{content:[{type:"text",text:n==="stop"?`Stopped task ${d.id} of ${d.agentId}. It is writing its resume plan; resume it with agentx_signal action=resume id=${d.id}.`:`Resumed task ${d.id} of ${d.agentId}. Its answer goes to ${d.delivery??"the chat it came from"}.`}]}:{content:[{type:"text",text:`Signal not sent: ${d.error||`HTTP ${c.status}`}`}]}}case"agentx_crons":{let s=await(await J(`${X()}/crons/health`)).json(),i=`Healthy: ${s.healthy}, Failing: ${s.failing}, Disabled: ${s.disabled}, Missed: ${s.missed}`,o=(s.jobs||[]).map(a=>` ${a.id}: ${a.status}${a.consecutiveErrors?` (${a.consecutiveErrors} errors)`:""}${a.lastError?` \u2014 ${a.lastError.slice(0,100)}`:""}`).join(`
|
|
42
42
|
`);return{content:[{type:"text",text:`${i}
|
|
43
43
|
|
|
44
|
-
${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-
|
|
44
|
+
${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-IUUGZFJ3.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await J(`${X()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let d=await c.json().catch(()=>({}));throw new Error(d?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-CMOZJTA2.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_content":{let{runContentTool:n}=await import("./tool-XEGKIHUP.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_note":{let{runNoteTool:n}=await import("./note-tool-ANQWBBZE.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-PVFI2DWN.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_sprint":{let{runSprintTool:n}=await import("./sprint-tool-4PLRLWOU.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-MXMT3GED.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-3MTKUBPS.js"),{agenticQuery:i,sharedQueryEnabled:o}=await import("./query-XBRRKY6I.js"),{loadQuerySettings:a,toolNoteSourceFor:c}=await import("./query-settings-3UVI3UQF.js"),{resolve:d}=await import("path"),l=e.wiki_dir||d(process.cwd(),".agentx/wiki"),u=new s(l,void 0,"graph"),h=e.agent||process.env.AGENTX_AGENT_ID||"";if(!h){let{existsSync:F}=await import("fs");for(let p of u.listAgents()){let m=d(u.getAgentWiki(p).baseDir,"_index.md");if(F(m)){h=p;break}}}let{QUERY_RUNS_FILE:f,recordQueryRun:y,timedQuery:g}=await import("./query-runs-VXS572PQ.js"),w=d(u.getBaseDir(),f);if(!h)return y(w,{at:new Date().toISOString(),agent:"",status:"no-catalog",source:"tool",wallMs:0}),{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let b=u.getAgentWiki(h),$=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,k=await RT(),x=await a(),E=await o()?u.sharedScope(h):void 0,A=await g(w,h,"tool",()=>i(n,b,h,{maxHops:$,shared:E,messagePath:k?.path,...k?.graphWeight!==void 0?{graphWeight:k.graphWeight}:{},method:x.method,summaries:x.summaries,notes:c(x,h)}));if(A.status!=="ok")return{content:[{type:"text",text:`Query returned status "${A.status}"${A.error?`: ${A.error}`:""}`}]};let T=A.citations.map(F=>` - ${F.title} [${F.type||"?"}] (${F.path})`).join(`
|
|
45
45
|
`),O=A.walked.length,D=A.live?.length?`
|
|
46
46
|
|
|
47
47
|
Read live at the source just now:
|
|
@@ -531,7 +531,7 @@ ${d}`)}let $={agentId:o,message:b,context:{channel:g,sender:y?"opencode":"openai
|
|
|
531
531
|
|
|
532
532
|
`)}}function Dy(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Ny(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
|
|
533
533
|
|
|
534
|
-
`)}function Ly(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);$c(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function $c(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Vn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Vn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Vn.levelOrder[e]<Vn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Xn=Vn;Lt(Xn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as UA,statSync as GA}from"fs";var tt={version:"0.
|
|
534
|
+
`)}function Ly(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);$c(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function $c(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Vn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Vn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Vn.levelOrder[e]<Vn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Xn=Vn;Lt(Xn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as UA,statSync as GA}from"fs";var tt={version:"0.176.0",commit:"2b53567",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function HA(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Fy(){let r=null;try{r=GA(UA(process.argv[1])).mtimeMs}catch{}let e=ay().version;return HA(tt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as BA}from"crypto";var Cr=class{constructor(e=new vh){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!qA.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};VA(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:BA(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=XA(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},qA=["run","task","signal","mesh","channel","status"];function XA(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function VA(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Wy(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Pr,timingSafeEqual as Uy}from"crypto";var _r=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let w={};for(let[b,$]of Object.entries(e.headers))(b.startsWith("x-hubspot")||b.startsWith("x-hub")||b.startsWith("x-github")||b.startsWith("x-gitlab")||b.startsWith("stripe")||b.startsWith("sentry")||b.startsWith("x-vercel")||b.startsWith("x-odoo")||b.startsWith("x-webhook")||b==="user-agent"||b==="content-type"||b==="host"||b==="x-forwarded-host"||b==="x-forwarded-proto"||b==="x-forwarded-for")&&(w[b]=$);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(d,c,e.headers),f=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===d),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(d,h,i,c),y&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${d}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:h,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${h??"\u2014"}] -> workflow=${y} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:h,workflow:y,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${d}/${h}/${y}]: ${w.message}`)}let g=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===d);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(w=>this.log(`Mesh-forwarded webhook [${d}] -> ${g.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${d}] -> ${g.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:d,response:w.content?.slice(0,500),error:w.error,duration:w.duration})}catch(w){this.sendJson(t,500,{error:w.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
|
|
535
535
|
`)[0]||"no message"} (${l.author?.name||""})`)}let d=t.object_attributes;if(d?.title&&(s.push(`Title: ${d.title}`),s.push(`State: ${d.state||""}`),s.push(`Action: ${d.action||""}`),d.source_branch&&s.push(`Branch: ${d.source_branch} -> ${d.target_branch}`),d.url&&s.push(`URL: ${d.url}`)),d?.iid&&!d?.source_branch&&(s.push(`Issue #${d.iid}: ${d.title||""}`),d.description&&s.push(`Description: ${d.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
|
|
536
536
|
`)[0]||""} (${u.author?.name||""})`);let d=t.pull_request;d&&(s.push(`PR #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${d.head?.ref} -> ${d.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let d of a.slice(0,3)){let l=d.subscriptionType??"?",u=d.objectId??"?",h=d.changeFlag??d.changeSource??"";s.push(` - ${l} (object ${u}${h?`, ${h}`:""})`)}}else{let d=t.subscriptionType??"event",l=t.objectId??"?";s.push(`Event: ${d} (object ${l})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
|
|
537
537
|
`)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(l=>l.enabled&&l.agentId===s&&l.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=l=>{let u=e[l.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let l=c("x-hub-signature-256");if(!l)return"missing X-Hub-Signature-256";let u="sha256="+Pr("sha256",a).update(t).digest("hex");return Zt(u,l)}if(n==="gitlab"){let l=c("x-gitlab-token");return l?Zt(a,l):"missing X-Gitlab-Token"}if(n==="stripe"){let l=c("stripe-signature");if(!l)return"missing Stripe-Signature";let u=Object.fromEntries(l.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=Pr("sha256",a).update(`${u.t}.${t}`).digest("hex");return Zt(h,u.v1)}if(n==="hubspot"){let l=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!l)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-h;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let y="POST",g=i||e["x-original-uri"]||e["x-forwarded-path"]||"",w=e["x-forwarded-host"],b=e.host,$=e["x-forwarded-proto"]||"https",k=new Set;w&&g&&k.add(`${$}://${w}${g}`),b&&g&&k.add(`https://${b}${g}`),b&&g&&k.add(`http://${b}${g}`),g&&k.add(g),k.add("");for(let x of k){let E=Pr("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(l.length===E.length&&Uy(Buffer.from(l),Buffer.from(E)))return null}return`signature mismatch (tried ${k.size} URI variants)`}if(n==="odoo"){let l=c("x-odoo-signature");if(l){let h=Pr("sha256",a).update(t).digest("hex"),f=l.startsWith("sha256=")?l.slice(7):l;return Zt(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Zt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let d=c("x-webhook-secret");return d?Zt(a,d):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function Zt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Uy(t,n)?null:"signature mismatch"}fu();Bl();du();iT();function JA(r){return{insertTaskHistory:r.prepare(`
|
|
@@ -1144,7 +1144,7 @@ ${l.map(u=>`${u.path}: ${u.message}`).join(`
|
|
|
1144
1144
|
`,c="";try{c=N0(s,"utf8")}catch{}return c!==a?(F0(s,i),{ok:!1,status:500,error:"agentx.json did not save as expected; the previous version was put back",errors:[]}):{ok:!0,path:s}}function F0(r,e){try{dD(r,e)}catch{}}function H0(r,e,t){let n=String(r?.agentId??""),s=e.agents[n];if(!s)return{error:`There is no agent "${n}"`};let i=r.voice??{},o=U0({agents:{[n]:i}},e).filter(u=>u.path!=="hotkeys");if(o.length)return{error:o.map(u=>u.message).join(`
|
|
1145
1145
|
`)};let a={...s.voice??{}};for(let[u,h]of Object.entries(i))Yi(h)?delete a[u]:a[u]=h;let c={...e.agents,[n]:{...s,voice:a}},d=s.name||n,l=String(r.text??"").trim().slice(0,300)||`Hello, this is ${d}. This is how I sound.`;return{voice:Oe(ve(n,c,e.voice,t)),text:l,agentId:n}}var hs=[["CwhRBWXzGAHq8TQ4Fs17","male"],["EXAVITQu4vr4xnSDxMaL","female"],["FGY2WhTYpPnrIDTdsKH5","female"],["IKne3meq5aSn9XLyUdCD","male"],["JBFqnCBsd6RMkjVDRZzb","male"],["N2lVS1w4EtoT3dr4eOWO","male"],["SAz9YHcvj6GT2YYXdXww","neutral"],["SOYHLrjzK2X1ezoPC6cr","male"],["TX3LPaxmHKxFdv7VOQHJ","male"],["Xb7hH8MSUJpSbSDYk0k2","female"],["XrExE9yKIg1WjnnlVkGX","female"],["bIHbv24MWmeRgasZH58o","male"],["cgSgspJ2msm6clMCkdW9","female"],["cjVigY5qzO86Huf0OWal","male"],["hpp4J3VqNfWAUOO0d1Us","female"],["iP95p4xoKVk53GoZ742B","male"],["nPczCjzI2devNBz1zQrb","male"],["onwK4e9ZLuTAKqWW03F9","male"],["pFZP5JQG7iQjIQuC4Bku","female"],["pNInz6obpgDQGcFmaJgB","male"],["pqHfZKP75CvOlQylNhV4","male"]].map(([r,e])=>({id:r,gender:e,premade:!0}));async function q0(r,e=fetch){if(!r)return hs;try{let t=await e("https://api.elevenlabs.io/v1/voices",{headers:{"xi-api-key":r},signal:AbortSignal.timeout(1e4)});if(!t.ok)return hs;let s=((await t.json()).voices??[]).filter(i=>i.category!=="cloned"&&i.category!=="generated").map(i=>({id:i.voice_id,gender:mD(i.labels?.gender),premade:i.category==="premade"}));return s.length?s:hs}catch{return hs}}var mD=r=>r==="female"||r==="male"||r==="neutral"?r:null;function gn(r){return/\b(she|her)\b/i.test(r)?"female":/\b(he|him|his)\b/i.test(r)?"male":null}function B0(r,e,t){let n=(a,c)=>a.id.localeCompare(c.id),s=[e.filter(a=>a.premade).sort(n),e.filter(a=>!a.premade).sort(n)],i=new Set(t),o=new Map;for(let a of[...r].sort((c,d)=>c.id.localeCompare(d.id))){let c=yD(a.id),d=u=>{for(let h of s)for(let f=0;f<h.length;f++){let y=h[(c+f)%h.length];if(!i.has(y.id)&&u(y))return y.id}},l=(a.gender?d(u=>u.gender===a.gender):void 0)??d(()=>!0)??(e.length?e[c%e.length].id:void 0);l&&(i.add(l),o.set(a.id,l))}return o}function yD(r){let e=2166136261;for(let t=0;t<r.length;t++)e=Math.imul(e^r.charCodeAt(t),16777619);return e>>>0}var Qi=r=>r.toLowerCase().replace(/^the\s+/,"").replace(/[-_\s]+agent$|\s+agent$/,"").replace(/[-_]+/g," ").trim(),Zi=class{constructor(e,t,n=()=>kt()){this.config=e;this.directory=t;this.installed=n}pool=hs;usePool(e){this.pool=e}list(){let e=this.config().agents,t=new Map;for(let n of this.all()){if(e[n.id])continue;let s=t.get(n.id);s&&(s.healthy||!n.healthy)||t.set(n.id,n)}return[...t.values()]}get(e){return this.list().find(t=>t.id===e)}on(e,t){return this.all().find(n=>n.peer===e&&n.id===t)}voice(e){let t=this.get(e);return this.build(e,t,t?this.cfgFor(t):this.config().meshVoices?.[e])}voiceOn(e,t){let n=this.on(e,t);if(n)return this.get(t)?.peer===e?this.voice(t):this.build(`${e}/${t}`,n,this.cfgFor(n))}speaker(e,t){let n=this.get(e);if(n)return this.persona(n,this.voice(e),t)}speakerOn(e,t,n){let s=this.on(e,t),i=s&&this.voiceOn(e,t);return s&&i?this.persona(s,i,n):void 0}all(){let e=[];for(let t of this.directory())for(let n of t.skills)e.push({id:n.id,name:n.name||n.id,description:n.description??"",tags:n.tags??[],peer:t.peer,healthy:t.healthy});return e}shadowed(){let e=new Map(this.list().map(t=>[t.id,t.peer]));return this.all().filter(t=>e.get(t.id)!==t.peer).map(t=>({...t,key:`${t.peer}/${t.id}`}))}cfgFor(e){let t=this.config().meshVoices??{};return t[`${e.peer}/${e.id}`]??t[e.id]}build(e,t,n){let s=t?.id??e,i=n?.name||t?.name||s,o=this.config().voice??{},a=this.systemCast().get(e)??null;return{agentId:s,name:i,provider:n?.provider??o.provider??"system",elevenlabsVoiceId:n?.elevenlabsVoiceId||this.assigned().get(e)||null,systemVoice:a?.id??null,systemVoiceName:a?Qs(a):null,systemByLanguage:Kf(s,n?.system,n?.gender??gn(t?.description??""),o,this.installed()),fallback:(o.fallback??"system")==="system",gender:n?.gender??gn(t?.description??"")??null,style:n?.style||null,intro:n?.intro||Qf(i,t?.description)}}persona(e,t,n){return{agentId:e.id,name:t.name,voice:Oe(t),persona:e.description||`You are ${t.name}.`,introLine:Zs(t,n)}}systemCast(){let{agents:e,meshVoices:t={},voice:n={}}=this.config(),s=this.installed(),i=new Set([...zf(e,n,s).values()].flatMap(l=>l?[l.name]:[])),o=this.list().sort((l,u)=>l.id.localeCompare(u.id)).map(l=>{let u=this.cfgFor(l);return{id:l.id,system:u?.system,gender:u?.gender??gn(l.description),fallbacks:u?.fallbacks}}),a=Wa(o,n,s,i),c=this.shadowed();if(!c.length)return a;for(let l of a.values())l&&i.add(l.name);let d=c.sort((l,u)=>l.key.localeCompare(u.key)).map(l=>{let u=this.cfgFor(l);return{id:l.key,system:u?.system,gender:u?.gender??gn(l.description),fallbacks:u?.fallbacks}});for(let[l,u]of Wa(d,n,s,i))a.set(l,u);return a}assigned(){let{agents:e,meshVoices:t={}}=this.config(),n=new Set([Yf(null,null)]);for(let c of Object.values(e))c.voice?.elevenlabsVoiceId&&n.add(c.voice.elevenlabsVoiceId);for(let c of Object.values(t))c.elevenlabsVoiceId&&n.add(c.elevenlabsVoiceId);let s=this.list().filter(c=>!this.cfgFor(c)?.elevenlabsVoiceId).map(c=>({id:c.id,gender:this.cfgFor(c)?.gender??gn(c.description)})),i=B0(s,this.pool,n),o=this.shadowed().filter(c=>!this.cfgFor(c)?.elevenlabsVoiceId);if(!o.length)return i;for(let c of i.values())n.add(c);let a=o.map(c=>({id:c.key,gender:this.cfgFor(c)?.gender??gn(c.description)}));for(let[c,d]of B0(a,this.pool,n))i.set(c,d);return i}resolve(e){let t=Qi(e);if(!t)return;let{agents:n,meshVoices:s={}}=this.config();for(let[i,o]of Object.entries(n))if(Qi(i)===t||o.name&&Qi(o.name)===t)return i;for(let i of this.list())if([i.id,i.name,s[i.id]?.name??"",...i.tags].some(a=>a&&Qi(a.replace(/^@/,""))===t))return i.id}},wD=/^(?:(?:ok(?:ay)?|hey|please|so)[,\s]+)?(?:(?:can i|could i|let me|i want to|i'd like to)\s+)?(?:talk|speak) (?:to|with)\s+(.+?)[\s.!?]*$|^(?:(?:ok(?:ay)?|please)[,\s]+)?(?:switch to|put me through to|connect me (?:to|with)|(?:go |switch )?back to)\s+(.+?)[\s.!?]*$/i;function X0(r){let e=wD.exec(r.trim());return e?(e[1]??e[2]).trim():null}var bD=500,kD=10*60*1e3,eo=class{constructor(e,t,n=()=>{}){this.config=e;this.mesh=t;this.log=n;this.voices=new Zi(e,()=>this.mesh()?.directory()??[])}voices;targets=new Map;async loadPool(){let e=await q0(vt());this.voices.usePool(e),this.log(`[voice] ${e.length} voices available for mesh agents`)}target(e,t){return this.targets.get(e)??t}switchTo(e,t,n){let s=X0(t),i=s?this.voices.resolve(s):void 0;return i?(this.targets.delete(e),i!==n&&(this.targets.set(e,i),this.targets.size>bD&&this.targets.delete(this.targets.keys().next().value)),i):null}isRemote(e){return!!this.voices.get(e)}known(){return{local:Object.keys(this.config().agents),mesh:this.voices.list().map(e=>e.id)}}async ask(e,t,n,s){let i=this.voices.get(e),o=this.mesh();if(!i||!o)return{content:"",error:`Unknown agent: "${e}"`,duration:0,peer:""};let a=Date.now();try{let c=await o.sendTask(i.peer,t,e,{context:{channel:"voice",chatId:`voice:${this.config().node.id}`,sender:"Voice",voice:{introduce:s,intro:n.intro,style:n.style??void 0}},freshSession:!1,timeoutMs:kD}),d=Date.now()-a;return this.log(`[voice] ${e}@${i.peer} answered in ${d}ms`),{content:c,duration:d,peer:i.peer}}catch(c){let d=Date.now()-a;return this.log(`[voice] ${e}@${i.peer} failed after ${d}ms: ${c?.message??c}`),{content:"",error:String(c?.message??c),duration:d,peer:i.peer}}}};var el=/([.!?…]+["')\]]*\s+|\n+)/g,to=class{buf="";push(e){this.buf+=e;let t=[],n=0;el.lastIndex=0;for(let s=el.exec(this.buf);s;s=el.exec(this.buf)){let i=this.buf.slice(n,s.index+s[1].length).trim();i&&t.push(i),n=s.index+s[1].length}return this.buf=this.buf.slice(n),t}flush(){let e=this.buf.trim();return this.buf="",e?[e]:[]}};function at(r){return r.replace(/```[\s\S]*?```/g," ").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/https?:\/\/\S+/g,"").replace(/[*_`#>]+/g,"").replace(/\p{Extended_Pictographic}️?/gu,"").replace(/\s+/g," ").trim()}var no=/\bDONE\b\.?/g,V0=new Set(["stop","cancel","enough","quit","end"]),vD=new Set("ok okay alright please now wait no hey so oh well just yes yeah thanks you can it that that's thats this the there here right already talking talk lesson narration".split(" "));function gs(r){let e=r.toLowerCase().replace(/\u2019/g,"'").match(/[a-z']+/g)??[];return e.length<=6&&e.some(t=>V0.has(t))&&e.every(t=>V0.has(t)||vD.has(t))}var ps="the user";function SD(r,e){return[r.persona,"",`[TALK MODE] This is a spoken conversation, not a task. Talk like a colleague in the same office: usually one or two short sentences, never more than three, in plain spoken words \u2014 no markdown, lists, URLs, emoji or stage directions. Go longer only when something truly needs explaining. You have no tools here and take no actions; if something should be done, say who will do it after the talk. Never invent status, numbers or facts you were not told; say you would have to check. When ${e} speaks, answer ${e} first and follow that lead. When the topic is settled, say one short closing line and end with the word DONE.`].join(`
|
|
1146
1146
|
`)}var so=class{constructor(e){this.opts=e;this.listener=e.listener??ps,this.models=e.speakers.map(n=>e.model(n,SD(n,this.listener)));let t=n=>[`You are talking out loud with ${e.speakers[1-n].name} while ${this.listener} listens. Topic: ${e.topic}`,e.context?`Context: ${e.context}`:"",e.speakers[n].introLine??""].filter(Boolean).join(`
|
|
1147
|
-
`);this.inbox[0].push(t(0),"You open."),this.inbox[1].push(t(1))}id=`talk-${Date.now().toString(36)}`;startedAt=Date.now();state="running";transcript=[];gaps=[];listener;models;inbox=[[],[]];ac=new AbortController;doorQueue=[];wake=null;lastEndAt=0;doorAt=0;playing=null;listeners=[];on(e){this.listeners.push(e)}door(e){if(this.state!=="ended"){if(gs(e))return this.stop("stopped by the listener");this.silence(),this.doorQueue.push(e.trim()),this.doorAt=Date.now(),this.state="running",this.emit({type:"door",text:e}),this.poke()}}hush(){this.state==="running"&&(this.silence(),this.state="held",this.emit({type:"hush"}),this.poke())}stop(e="stopped"){if(this.state!=="ended"){this.state="ended",this.silence();for(let t of this.models)t.close();this.emit({type:"end",reason:e}),this.poke()}}async run(){let e=this.opts.maxTurns??10,t=0,n=0;try{let s=this.generate(t,n++,n>=e);for(;!this.is("ended");){let i=await s;if(this.is("ended"))break;if(i.aborted||this.is("held")||this.doorQueue.length){if(t=await this.afterInterruption(i),this.is("ended"))break;s=this.generate(t,n++,n>=e);continue}let o=no.test(i.text)||n>=e;if(no.lastIndex=0,o){if(await Promise.all(i.plays),this.is("running")&&!this.doorQueue.length)this.stop(n>=e?"turn limit":"settled");else if(!this.is("ended")){s=Promise.resolve(Object.assign(i,{aborted:!0}));continue}break}if(await Promise.race([i.started,this.poked()]),!this.is("running")||this.doorQueue.length){s=Promise.resolve(Object.assign(i,{aborted:!0}));continue}t=1-t,s=this.generate(t,n++,n>=e)}}catch(s){this.emit({type:"error",error:String(s?.message??s)}),this.stop("error")}}async generate(e,t,n){let s=this.opts.speakers[e],i=this.ac.signal,o,a={n:t,who:e,text:"",heard:[],plays:[],started:new Promise(h=>{o=h}),aborted:!1},c=h=>{let f=at(h.replace(no,""));if(!f||i.aborted)return;let y=!a.plays.length,g=this.opts.speech.say({voice:s.voice,text:f,agentId:s.agentId,kind:"talk",onStart:y?()=>this.turnStarted(a,o):void 0});a.plays.push(g.then(w=>(w&&(a.heard.push(f),this.lastEndAt=Date.now()),w)))};n&&this.inbox[e].push("This is the last turn: wrap up in a sentence or two and end with DONE.");let d=this.inbox[e].join(`
|
|
1147
|
+
`);this.inbox[0].push(t(0),"You open."),this.inbox[1].push(t(1))}id=`talk-${Date.now().toString(36)}`;startedAt=Date.now();state="running";transcript=[];gaps=[];listener;models;inbox=[[],[]];ac=new AbortController;doorQueue=[];wake=null;lastEndAt=0;doorAt=0;playing=null;listeners=[];get topic(){return this.opts.topic}get speakerIds(){return this.opts.speakers.map(e=>e.agentId)}on(e){this.listeners.push(e)}door(e){if(this.state!=="ended"){if(gs(e))return this.stop("stopped by the listener");this.silence(),this.doorQueue.push(e.trim()),this.doorAt=Date.now(),this.state="running",this.emit({type:"door",text:e}),this.poke()}}hush(){this.state==="running"&&(this.silence(),this.state="held",this.emit({type:"hush"}),this.poke())}stop(e="stopped"){if(this.state!=="ended"){this.state="ended",this.silence();for(let t of this.models)t.close();this.emit({type:"end",reason:e}),this.poke()}}async run(){let e=this.opts.maxTurns??10,t=0,n=0;try{let s=this.generate(t,n++,n>=e);for(;!this.is("ended");){let i=await s;if(this.is("ended"))break;if(i.aborted||this.is("held")||this.doorQueue.length){if(t=await this.afterInterruption(i),this.is("ended"))break;s=this.generate(t,n++,n>=e);continue}let o=no.test(i.text)||n>=e;if(no.lastIndex=0,o){if(await Promise.all(i.plays),this.is("running")&&!this.doorQueue.length)this.stop(n>=e?"turn limit":"settled");else if(!this.is("ended")){s=Promise.resolve(Object.assign(i,{aborted:!0}));continue}break}if(await Promise.race([i.started,this.poked()]),!this.is("running")||this.doorQueue.length){s=Promise.resolve(Object.assign(i,{aborted:!0}));continue}t=1-t,s=this.generate(t,n++,n>=e)}}catch(s){this.emit({type:"error",error:String(s?.message??s)}),this.stop("error")}}async generate(e,t,n){let s=this.opts.speakers[e],i=this.ac.signal,o,a={n:t,who:e,text:"",heard:[],plays:[],started:new Promise(h=>{o=h}),aborted:!1},c=h=>{let f=at(h.replace(no,""));if(!f||i.aborted)return;let y=!a.plays.length,g=this.opts.speech.say({voice:s.voice,text:f,agentId:s.agentId,kind:"talk",onStart:y?()=>this.turnStarted(a,o):void 0});a.plays.push(g.then(w=>(w&&(a.heard.push(f),this.lastEndAt=Date.now()),w)))};n&&this.inbox[e].push("This is the last turn: wrap up in a sentence or two and end with DONE.");let d=this.inbox[e].join(`
|
|
1148
1148
|
`);this.inbox[e]=[];let l=new to;for await(let h of this.models[e].reply(d,i)){a.text+=h;for(let f of l.push(h))c(f)}if(i.aborted)return a.aborted=!0,o(),a;for(let h of l.flush())c(h);a.plays.length||o();let u=at(a.text.replace(no,""));return a.entry={name:s.name,text:u},a.relayed=`${s.name} said: ${u}`,this.transcript.push(a.entry),this.inbox[1-e].push(a.relayed),this.emit({type:"line",turn:t,agentId:s.agentId,name:s.name,text:u}),a}turnStarted(e,t){if(this.doorAt)this.emit({type:"answered",turn:e.n,ms:Date.now()-this.doorAt}),this.doorAt=0;else if(this.lastEndAt&&e.n>0){let n=Date.now()-this.lastEndAt;this.gaps.push(n),this.emit({type:"gap",turn:e.n,ms:n})}this.playing=e,t()}async afterInterruption(e){let t=Date.now()+(this.opts.holdMs??2e4);for(;this.state==="held"&&Date.now()<t;)await Promise.race([this.poked(),new Promise(a=>setTimeout(a,t-Date.now()))]);if(this.state==="ended")return e.who;this.state="running",this.lastEndAt=0;let n=this.playing??e,s=[];for(let a of new Set([n,e])){await Promise.allSettled(a.plays);let c=this.opts.speakers[a.who].name,d=a.heard.join(" ");a.relayed&&(this.inbox[1-a.who]=this.inbox[1-a.who].filter(l=>l!==a.relayed)),a.entry&&(d?a.entry.text=`${d} \u2014`:this.transcript.includes(a.entry)&&this.transcript.splice(this.transcript.indexOf(a.entry),1)),d&&a.heard.length<a.plays.length?s.push(`(${c} was cut off after saying: "${d}")`):!d&&(a.text||a.aborted)&&s.push(`(${c}'s last line was not heard.)`)}this.playing=null;let i=this.doorQueue.splice(0).join(" / ");s.push(i?`${this.listener} just said: "${i}". Answer ${this.listener} first.`:"(There was a pause. Carry on.)"),this.inbox[0].push(...s),this.inbox[1].push(...s);let o=this.opts.speakers.findIndex(a=>i&&new RegExp(`\\b${$D(a.name)}\\b`,"i").test(i));return o>=0?o:n.who}silence(){this.opts.speech.cancel("talk"),this.ac.abort(),this.ac=new AbortController}is(e){return this.state===e}poke(){let e=this.wake;this.wake=null,e?.()}poked(){return new Promise(e=>{this.wake=e})}emit(e){for(let t of this.listeners)try{t(e)}catch{}}},$D=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var J0="You turn an AI agent's real tool steps into one short spoken sentence, in the first person, as that agent. Say what it is doing now in plain words, lively but brief (under 20 words). Mention only what the steps show; never invent progress or results. Never read out commands, file paths, code, ids, numbers, names of secrets or anything that looks like a key. If the steps show nothing worth saying, answer exactly SKIP.",ID=new Set(["voice","desktop"]);function TD(r,e){let t=e.replace(/[A-Za-z0-9_\-+/=]{24,}/g,"\u2026").replace(/(token|key|secret|password|passwd|auth)["']?\s*[:=]\s*["']?[^\s"',}]+/gi,"$1=\u2026").slice(0,200);return`${r}: ${t}`}var ro=class{constructor(e){this.opts=e;this.minGap=e.minGapMs??2e4,this.firstDelay=e.firstDelayMs??4e3}tasks=new Map;agentSwitch=new Map;taskSwitch=new Map;model=null;idleTimer;minGap;firstDelay;heldUntil=0;lastLine=null;set(e,t){let[n,s]=e.taskId?[this.taskSwitch,e.taskId]:[this.agentSwitch,e.agentId??""];s&&(t===null?n.delete(s):n.set(s,t))}hush(e=3e4,t=3e4){this.heldUntil=Date.now()+e;let n=this.lastLine;return n&&Date.now()-n.at<t?{taskId:n.taskId,agentId:n.agentId}:null}release(){this.heldUntil=0}status(){return{agents:Object.fromEntries(this.agentSwitch),tasks:Object.fromEntries(this.taskSwitch)}}enabled(e,t,n){let s=this.taskSwitch.get(n);if(s!==void 0)return s;if(ID.has(t))return!1;let i=this.agentSwitch.get(e),o=this.opts.voiceOf(e)?.narrate??"off";return(i??o!=="off")&&(t!=="cron"||o==="all")}attach(e){let t=i=>{i.taskId&&this.tasks.set(i.taskId,{agentId:i.agentId,channel:i.channel,steps:[],lastSpokeAt:0})},n=i=>this.onStep(i),s=i=>{let o=i.taskId?this.tasks.get(i.taskId):void 0;o?.timer&&clearTimeout(o.timer),i.taskId&&(this.tasks.delete(i.taskId),this.taskSwitch.delete(i.taskId))};return e.on("task:started",t),e.on("task:step",n),e.on("task:completed",s),()=>{e.off("task:started",t),e.off("task:step",n),e.off("task:completed",s),this.close()}}onStep(e){if(e.name!=="tool_use"||!e.action)return;let t=this.tasks.get(e.taskId);if(!t||!this.enabled(t.agentId,t.channel,e.taskId)||(t.steps.push(TD(e.action,e.inputSummary??"")),t.timer))return;let n=Date.now(),s=t.lastSpokeAt?t.lastSpokeAt+this.minGap:n+this.firstDelay;t.timer=setTimeout(()=>{t.timer=void 0,this.flush(e.taskId)},Math.max(0,s-n))}async flush(e){let t=this.tasks.get(e),n=t&&this.opts.voiceOf(t.agentId);if(!t||!n||!t.steps.length)return null;let s=t.steps.splice(0);if(t.lastSpokeAt=Date.now(),Date.now()<this.heldUntil||this.opts.speech.busy)return null;let i=[`You are ${n.name}${n.style?`; your manner: ${n.style}`:""}.`,"Your real steps since your last update:",...s.slice(-12).map(c=>`- ${c}`)].join(`
|
|
1149
1149
|
`),o="";try{for await(let c of this.useModel().reply(i))o+=c}catch{return this.closeModel(),null}let a=at(o);return!a||/^SKIP\b/i.test(a)||Date.now()<this.heldUntil?null:(this.lastLine={taskId:e,agentId:t.agentId,at:Date.now()},this.opts.speech.say({voice:n.voice,text:a,agentId:t.agentId,kind:"narration"}),a)}close(){for(let e of this.tasks.values())e.timer&&clearTimeout(e.timer);this.tasks.clear(),this.closeModel()}useModel(){return this.model??=this.opts.model(),this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>this.closeModel(),this.opts.idleMs??18e4),this.idleTimer.unref?.(),this.model}closeModel(){this.idleTimer&&clearTimeout(this.idleTimer),this.model?.close(),this.model=null}};import{unlinkSync as xD}from"fs";var AD=10,K0={high:0,normal:1,low:2},io=class{constructor(e=Hf(),t=Jf,n={},s=Bf,i=6e4){this.synth=e;this.play=t;this.events=n;this.limitMs=s;this.holdMs=i}waiting=[];current=null;playing=null;recent=[];held=!1;holdTimer=null;floor=null;run=0;seq=0;pronounce=e=>e;othersSpeaking;othersWaitMs=10*6e4;othersPollMs=500;get busy(){return!!this.current||this.waiting.length>0}get paused(){return this.held}say(e){return this.enqueue(e).done}enqueue(e,t=!1){let n=new AbortController,s={id:`s${Date.now().toString(36)}-${++this.seq}`,agentId:e.agentId??null,kind:e.kind??"line",text:e.text,voice:e.voice,enqueuedAt:Date.now()};if(s.kind==="narration"&&!this.allowed(e))return{item:s,done:Promise.resolve(!1)};let i,o=new Promise(l=>{i=l}),a={...e,text:this.pronounce(e.text)},c=this.synth(a,n.signal).then(l=>({f:l}),l=>({e:l})),d={item:s,u:e,said:a,audio:c,ac:n,started:!1,playingSince:0,done:i};if(t)this.waiting.unshift(d);else{let l=K0[e.voice.priority??"normal"],u=this.waiting.findIndex(h=>K0[h.u.voice.priority??"normal"]>l);u<0?this.waiting.push(d):this.waiting.splice(u,0,d)}return this.changed(),this.next(),{item:s,done:o}}view(){return{paused:this.held,reserved:this.floor!==null,playing:this.current?.item??null,waiting:this.waiting.map(e=>e.item),recent:[...this.recent]}}skip(e){if(this.current?.item.id===e)return this.drop(this.detach("skipped")),this.changed(),this.next(),!0;let t=this.waiting.findIndex(n=>n.item.id===e);return t<0?!1:(this.drop(this.waiting.splice(t,1)[0]),this.changed(),!0)}front(e){if(this.current?.item.id===e)return!0;let t=this.waiting.findIndex(n=>n.item.id===e);return t<0?!1:(this.waiting.unshift(...this.waiting.splice(t,1)),this.changed(),!0)}replay(e){let t=[this.current?.item,...this.waiting.map(n=>n.item),...this.recent].find(n=>n?.id===e);return t?this.enqueue({voice:t.voice,text:t.text,agentId:t.agentId??void 0,kind:t.kind},!0).item:null}pause(){if(this.holdTimer&&clearTimeout(this.holdTimer),this.holdTimer=setTimeout(()=>this.resume(),this.holdMs),this.holdTimer.unref?.(),this.held)return;this.held=!0;let e=this.detach("paused");e&&this.waiting.unshift(e),this.changed()}resume(){this.holdTimer&&clearTimeout(this.holdTimer),this.holdTimer=null,this.held&&(this.held=!1,this.changed(),this.next())}reserve(e){if(this.floor===e)return;this.floor=e,this.current&&!this.allowed(this.current.u)&&this.waiting.unshift(this.detach("floor"));let t=this.waiting.filter(n=>n.item.kind==="narration"&&!this.allowed(n.u));this.waiting=this.waiting.filter(n=>!t.includes(n));for(let n of t)this.drop(n);this.changed(),this.next()}release(e=!1){if(this.floor===null)return;let t=this.floor;if(this.floor=null,e){this.current?.u.floor===t&&this.drop(this.detach("stopped"));let n=this.waiting.filter(s=>s.u.floor===t);this.waiting=this.waiting.filter(s=>s.u.floor!==t);for(let s of n)this.drop(s)}this.changed(),this.next()}allowed(e){return this.floor===null||e.floor===this.floor}cancel(e){let t=!1;this.current?.item.kind===e&&(this.drop(this.detach("cancelled")),t=!0);for(let n of this.waiting.filter(s=>s.item.kind===e))this.drop(n),t=!0;this.waiting=this.waiting.filter(n=>n.item.kind!==e),t&&(this.changed(),this.next())}stop(){let e=[this.detach("stopped"),...this.waiting.splice(0)].filter(n=>!!n);for(let n of e)this.drop(n);this.holdTimer&&clearTimeout(this.holdTimer),this.holdTimer=null;let t=this.held;this.held=!1,(e.length||t)&&this.changed()}next(){if(this.held||this.current)return;let e=this.waiting.findIndex(s=>this.allowed(s.u));if(e<0)return;let t=this.waiting.splice(e,1)[0];this.current=t;let n=++this.run;this.changed(),t.audio.then(async s=>{if(n===this.run){if("e"in s)return this.finish(t,!1);await this.othersDone(n),n===this.run&&this.playOne(t,s.f,n)}})}async othersDone(e){if(!this.othersSpeaking)return;let t=Date.now()+this.othersWaitMs;for(;e===this.run&&Date.now()<t;){let n=null;try{n=await this.othersSpeaking()}catch{}if(!n){this.othersOutlasted=!1;return}if(this.othersOutlasted)return;await new Promise(s=>setTimeout(s,this.othersPollMs))}e===this.run&&(this.othersOutlasted=!0)}othersOutlasted=!1;playOne(e,t,n){let s=this.play(t,e.said);this.playing=s,e.playingSince=Date.now(),e.started||(e.started=!0,this.events.onStart?.(e.u,Date.now()),e.u.onStart?.());let i=!1,o=!1,a=setTimeout(()=>{i||(o=!0,s.kill())},this.limitMs(e.said.text)),c=d=>{i||(i=!0,clearTimeout(a),this.playing===s&&(this.playing=null),n===this.run&&(this.events.onEnd?.(e.u,Date.now(),d),this.stopped(e,d?"finished":o?"watchdog":"failed"),this.finish(e,d)))};s.on("error",()=>c(!1)),s.on("close",d=>c(d===0))}finish(e,t){this.detach(),t&&(this.recent=[e.item,...this.recent].slice(0,AD)),this.drop(e,t),this.changed(),this.next()}detach(e){let t=this.current;if(!t)return null;this.current=null,this.run++;let n=this.playing;return this.playing=null,n?.kill(),e&&this.stopped(t,e),t}stopped(e,t){if(!e.playingSince)return;let n=Date.now()-e.playingSince;e.playingSince=0;try{this.events.onStopped?.(e.u,t,n)}catch{}}drop(e,t=!1){e.ac.abort(),e.done(t),e.audio.then(n=>{if("f"in n&&n.f)try{xD(n.f)}catch{}})}changed(){try{this.events.onChange?.(this.view())}catch{}}};import{spawn as RD}from"child_process";import{createInterface as ED}from"readline";var z0="claude-haiku-4-5-20251001";function Y0(r){return(r.backend??(process.env.AGENTX_TALK_BACKEND==="api"?"api":"cli"))==="api"?new nl(r):new tl(r)}var tl=class{child;lines;queue=Promise.resolve();dead=null;seq=0;lastUsage;constructor(e,t="claude"){let n=Qu({...process.env});delete n.CLAUDECODE,n.MAX_THINKING_TOKENS="0",this.child=RD(t,["-p","--model",e.model??z0,"--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages","--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence","--system-prompt",e.system],{env:n,stdio:["pipe","pipe","pipe"]}),this.child.on("error",s=>{this.dead=s.message}),this.child.on("exit",s=>{this.dead??=`claude exited (${s})`}),this.child.stdin.on("error",()=>{}),this.child.stderr.resume(),this.lines=ED({input:this.child.stdout})[Symbol.asyncIterator]()}reply(e,t){let n=new sl,s=this.queue,i=(async()=>{if(await s,this.dead)throw new Error(this.dead);if(t?.aborted)return n.end();this.child.stdin.write(JSON.stringify({type:"user",message:{role:"user",content:e}})+`
|
|
1150
1150
|
`);let o=()=>this.child.stdin.write(JSON.stringify({type:"control_request",request_id:`interrupt-${++this.seq}`,request:{subtype:"interrupt"}})+`
|
|
@@ -1153,7 +1153,7 @@ ${l.map(u=>`${u.path}: ${u.message}`).join(`
|
|
|
1153
1153
|
`)}function Z0(r,e,t){let n=r.candidates.find(a=>a.id===e);if(!n)return null;let s=t.candidates.filter(a=>a.role===n.role&&a.label===n.label),i=r.rectOf(e);if(s.length<=1||!i)return s[0]?.id??null;let o=a=>{let c=t.rectOf(a.id);return c?Math.hypot(c.x-i.x,c.y-i.y):1/0};return s.reduce((a,c)=>o(c)<o(a)?c:a).id}var dl=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab(?!le)|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText|Image|ColorWell)/;function PD(r){let e=new Map(r.map(s=>[s.id,s])),t=new Set(r.filter(s=>s.role==="AXWebArea").map(s=>s.id)),n=new Set;if(t.size===0)return n;for(let s of r){let i=s;for(let o=0;i&&o<64;o++){if(t.has(i.id)){n.add(s.id);break}if(i.parent<0)break;i=e.get(i.parent)}}return n}function _D(r){let e=PD(r),t=r.filter(n=>e.has(n.id));return t.length<2?{page:r,browser:[]}:{page:t,browser:r.filter(n=>!e.has(n.id))}}function e$(r){return r?{AXCloseButton:"close window (red traffic light)",AXMinimizeButton:"minimise window (yellow traffic light)",AXZoomButton:"zoom window (green traffic light)",AXFullScreenButton:"full screen (green traffic light)"}[r]??"":""}function MD(r,e){if(r.role!=="AXImage")return!1;let t=Math.max(0,...e.filter(n=>n.role==="AXWebArea").map(n=>n.width*n.height));return t>0&&r.width*r.height>=t*.4}var OD=/^AX(Toolbar|TabGroup)$/;function DD(r){let e=new Set(["the","a","an","of","on","in","to","at","for","and","or","this","that","my","button","icon"]);return r.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(t=>t.length>1&&!e.has(t))}function ND(r,e){if(!e.length)return 0;let t=r.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);return e.filter(n=>t.some(s=>s===n||n.length>=4&&s.startsWith(n))).length}function n$(r,e=60,t={}){let n=k=>/^AX(TextField|TextArea|SearchField|ComboBox)/.test(k)?0:/^AX(Button|MenuItem|MenuButton|PopUpButton|CheckBox|RadioButton|Tab|Link|ColorWell)/.test(k)?1:/^AX(Row|Cell|Slider|Disclosure|Toolbar)/.test(k)?2:k==="AXImage"?3:4,s=k=>k.width>=1&&k.height>=1,i=_D(r),o=t$(i.page),a=t$(i.browser),c=a.length>0,d=new Set(o.filter(k=>MD(k,o)).map(k=>k.id)),l=k=>k.map((x,E)=>({e:x,i:E})).sort((x,E)=>(d.has(x.e.id)?1:n(x.e.role))-(d.has(E.e.id)?1:n(E.e.role))||x.i-E.i).map(({e:x})=>x),u=DD(t.request??""),h=(k,x)=>{if(k.length<=x||!u.length)return k.slice(0,x);let E=new Set(k.map((A,T)=>({e:A,i:T,hits:ND(`${e$(A.subrole)} ${A.label} ${A.value??""}`,u)})).sort((A,T)=>T.hits-A.hits||A.i-T.i).slice(0,x).map(({e:A})=>A.id));return k.filter(A=>E.has(A.id))},f=h(l(a.filter(k=>dl.test(k.role)&&!OD.test(k.role)&&s(k))),Math.min(20,Math.floor(e/4))),y=h(l(o.filter(k=>(dl.test(k.role)||d.has(k.id))&&s(k))),e-f.length),g=new Set(f.map(k=>k.id)),w=r.find(k=>k.role==="AXWindow")??null,b=[...y,...f],$=new Map;for(let k of b)$.set(Mt(k),($.get(Mt(k))??0)+1);return b.map((k,x)=>{let E=d.has(k.id)?"canvas":(k.label||k.value||"").trim()||`${k.role.replace(/^AX/,"")} ${x+1}`,A=Mt(k),T=d.has(k.id)?"canvas":e$(k.subrole)||A||FD(k,r)||WD(k,x);if(c&&!g.has(k.id)&&!d.has(k.id)&&(!A||($.get(A)??0)>1)){let O=UD(k,o);O&&(T=`${T} in "${O}"`)}return g.has(k.id)&&(T=`outside the page: ${T}`),{id:k.id,role:k.role,label:E,...T!==E?{shown:T}:{},value:k.value??null,enabled:k.enabled,...w?{where:GD(k,w)}:{},...g.has(k.id)?{area:"browser"}:{},...LD(k,c&&!g.has(k.id))?{closes:!0}:{}}})}function LD(r,e){if(r.subrole==="AXCloseButton")return!0;let t=Mt(r);return e?/^(close (tabs?|windows?|editors?|all|others?)|quit)\b/i.test(t)||jD.test(t):/^(close|quit)\b/i.test(t)}var jD=/(⌘\s*[⇧⌥]*\s*[wq]|\b(cmd|command)\s*\+\s*((shift|alt|option)\s*\+\s*)?[wq])\b/i;function ll(r){return/\b(closes?|closing|quit)\b(?!-up|\s+to\b)/i.test(r)}function s$(r,e){return r?.closes===!0&&!ll(e)}function t$(r){let e=new Set;return r.filter(t=>{if(t.role==="AXWebArea"||t.role==="AXWindow")return!0;let n=`${t.role}|${t.label}|${t.value??""}|${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)},${Math.round(t.height)}`;return e.has(n)?!1:(e.add(n),!0)})}function Mt(r){let e=t=>{let n=(t??"").trim();return n&&n!=="0"?n:""};return e(r.label)||e(r.value)}function FD(r,e){if(!/^AX(Row|Cell)$/.test(r.role))return"";let t=new Set([r.id]);for(let n of e)if(t.has(n.parent)&&(t.add(n.id),n.role==="AXStaticText"||n.role==="AXTextField")){let s=Mt(n);if(s)return s}return""}function WD(r,e){return r.role==="AXImage"?`unlabelled ${r.width>3*r.height?"chart or graphic":"icon or image"} ${e+1}`:`${r.role.replace(/^AX/,"")} ${e+1}`}function UD(r,e){let t=e.findIndex(a=>a.id===r.id);if(t<0)return"";let n=t,s=r.y,i=r.x+r.width;for(let a=t-1;a>=0&&t-a<=20;a--){let c=e[a];if(dl.test(c.role)){if(c.y>s+10||r.y-c.y>300||c.x>i+20)break;n=a,s=c.y,i=Math.max(i,c.x+c.width)}}let o=[];for(let a=n;a<t&&o.length<2;a++)e[a].role==="AXStaticText"&&Mt(e[a])&&o.push(Mt(e[a]).slice(0,40));return o.join(" ")}function GD(r,e){let t=(r.x+r.width/2-e.x)/Math.max(1,e.width),n=(r.y+r.height/2-e.y)/Math.max(1,e.height),s=t<1/3?"left":t>2/3?"right":"";return[n<1/3?"top":n>2/3?"bottom":"",s].filter(Boolean).join(" ")||"middle"}var oo=400,ct=class{constructor(e,t){this.opts=e;this.deps=t;this.listener=e.listener??ps}id=`teach-${Date.now().toString(36)}`;get agentId(){return this.opts.speaker.agentId??null}get mode(){return this.opts.mode}get goal(){return this.opts.goal}startedAt=new Date().toISOString();state="running";step=0;lastSay="";history=[];ac=new AbortController;doorQueue=[];speaking=Promise.resolve();wake=null;listeners=[];listener;took={readMs:0,planMs:0};on(e){this.listeners.push(e)}door(e){if(this.state!=="ended"){if(gs(e))return this.stop("stopped by the listener");this.silence(),this.doorQueue.push(e.trim()),this.state="running",this.emit({type:"door",text:e}),this.poke()}}hush(){this.state==="running"&&(this.silence(),this.state="held",this.poke())}stop(e="stopped"){this.state!=="ended"&&(this.state="ended",this.silence(),this.deps.presence.say(""),this.deps.presence.close(),this.deps.model.close(),this.emit({type:"end",reason:e}),this.poke())}async run(){let e=this.opts.maxSteps??12,t=0;this.deps.presence.say(`Looking at ${this.opts.app??"the screen"}\u2026`);try{for(;!this.is("ended")&&this.step<e&&(await this.waitOutHush(),!this.is("ended"));){let n=Date.now(),s=await this.onLessonApp();if(!s)continue;let i=Date.now(),o=await this.plan(s);if(!o)continue;this.took={readMs:i-n,planMs:Date.now()-i};let a=await this.recheck(o,s),c="stale"in a?a:await this.perform(++this.step,o,a);if(c==="done"||c==="stopped")break;if(c==="next"){t=0;continue}if(!this.replanned(c.stale,++t))break}await this.speaking,this.is("ended")||this.stop(this.step>=e?"step limit":"goal reached")}catch(n){this.emit({type:"error",error:String(n?.message??n)}),this.stop("error")}}async onLessonApp(){let e=!1,t=Date.now()+(this.opts.waitMs??45e3);for(;;){let n=await this.deps.readScreen();if(this.opts.app??=n.app,n.app.toLowerCase()===this.opts.app.toLowerCase())return n;if(!e){e=!0;let s=`Bring ${this.opts.app} to the front and I'll carry on.`;this.deps.presence.say(s),this.emit({type:"step",n:this.step,action:"wait_for_user",target:null,say:s}),await this.deps.speech.say({voice:this.opts.speaker.voice,text:s,agentId:this.opts.speaker.agentId,kind:"lesson"})}if(Date.now()>t)return this.stop(`${this.opts.app} never came to the front`),null;if(await Promise.race([this.sleep(this.opts.pollMs??oo),this.poked()]),!this.is("running"))return null}}async plan(e){let t=this.doorQueue.splice(0);t.length&&this.history.push(`${this.listener} said: "${t.join(" / ")}" \u2014 answer that first.`);let n={teach:`You lead: say the next step, show where, and ${this.listener} does it.`,watch:`${this.listener} is driving. Coach briefly: where things are and what to try next. Prefer wait_for_user.`,act:this.opts.actionsAllowed?`You do each step yourself (click, type or key), telling ${this.listener} what it is for and where: 'to fill it in, I'm clicking solid on the right'.`:`You may not click or type here; show where and let ${this.listener} do it.`}[this.opts.mode],s=[`Goal: ${this.opts.goal}`,`Mode: ${this.opts.mode}. ${n}`,`App: ${e.app}${e.window?` \u2014 window "${e.window}"`:""}`,"On screen:",...e.candidates.slice(0,80).map(a=>`${a.id} ${a.role} "${(a.shown??a.label).slice(0,60)}"${a.value?` = "${String(a.value).slice(0,40)}"`:""}`),this.history.length?`So far:
|
|
1154
1154
|
${this.history.slice(-8).join(`
|
|
1155
1155
|
`)}`:"This is the first step."].join(`
|
|
1156
|
-
`),i=this.ac.signal,o="";for await(let a of this.deps.model.reply(s,i))o+=a;return i.aborted?null:al(o,new Set(e.candidates.map(a=>a.id)))}async recheck(e,t){let n=await this.deps.readScreen();if(n.app!==t.app)return{stale:`${n.app} is in front now, not ${t.app}`};if((n.window??"")!==(t.window??""))return{stale:`the window changed from "${t.window??""}" to "${n.window??""}"`};if(e.target===null)return{screen:n,target:null};let s=Z0(t,e.target,n);return s!==null?{screen:n,target:s}:{stale:`"${t.candidates.find(o=>o.id===e.target)?.label??""}" is no longer on screen`}}replanned(e,t){return this.emit({type:"replanned",n:this.step,reason:e}),this.deps.presence.clear(),this.history.push(`The screen changed before you acted (${e}); plan again from what is there now.`),t<=(this.opts.maxReplans??3)?!0:(this.stop("the screen kept changing"),!1)}async perform(e,t,n){let{screen:s,target:i}=n,o=i!==null?s.rectOf(i):null,a=i!==null?s.candidates.find(w=>w.id===i)?.label??"":"",c=i!==null&&s$(s.candidates.find(w=>w.id===i),this.opts.goal),d=this.opts.mode==="act"&&this.opts.actionsAllowed&&!((t.action==="click"||t.action==="type")&&c);if(d&&t.action==="key"&&t.text&&il(t.text))return this.refuseToLeave(e,t.text,s.app);if(d&&t.action==="key"&&t.text&&ol(t.text)&&!ll(this.opts.goal))return this.refuseToClose(e,t.text);let l=t.action==="key"?d&&t.text?"key":o?"highlight":"wait_for_user":(t.action==="click"||t.action==="type")&&(!d||!o)?"highlight":t.action;this.emit({type:"step",n:e,action:l,target:a||null,say:t.say,...this.took});let{presence:u,speech:h}=this.deps;o&&u.moveTo(o,{highlight:l!=="point"}),u.say(Q0(o?a:null)),this.lastSay=t.say,await this.speaking;let f=t.say?h.say({voice:this.opts.speaker.voice,text:t.say,agentId:this.opts.speaker.agentId,kind:"lesson"}):Promise.resolve(!0);if(d&&(l==="key"?!!t.text:(l==="click"||l==="type")&&!!o)?this.speaking=f:await Promise.race([f,this.poked()]),!this.is("running")||this.doorQueue.length)return this.history.push(`Step ${e}: you started "${t.say}" and were cut off.`),this.is("ended")?"stopped":"next";if(l==="done")return"done";if(l==="key"&&t.text){let w=await this.recheck({...t,target:null},s);if("stale"in w)return w;let b=await this.deps.act({action:"key",keys:t.text});return this.emit({type:"acted",n:e,error:b.error}),this.history.push(b.error?`Step ${e}: you tried to press ${t.text} and it failed: ${b.error}`:`Step ${e}: you pressed ${t.text}.`),b.error||await this.settle(),"next"}if((l==="click"||l==="type")&&o){let w=await this.recheck({...t,target:i},s);if("stale"in w)return w;let b=w.target!==null?w.screen.rectOf(w.target):null;if(!b)return{stale:`"${a}" is no longer on screen`};let $=s.candidates.find(x=>x.id===i)?.role,k=await this.deps.act({action:l,rect:b,label:a,role:$,text:t.text??void 0});return this.emit({type:"acted",n:e,error:k.error}),this.history.push(k.error?`Step ${e}: you tried to ${l} "${a}" and it failed: ${k.error}`:`Step ${e}: you ${l==="click"?"clicked":`typed "${t.text}" into`} "${a}".`),k.error||await this.settle(),"next"}let g=await this.waitForChange();return u.say(""),u.park(),this.emit({type:"changed",n:e,changed:g}),this.history.push(`Step ${e}: you said "${t.say}"${a?` about "${a}"`:""}. `+(g?`${this.listener} did something; the screen changed.`:"Nothing changed on screen.")),"next"}async refuseToLeave(e,t,n){let s=`That would take me out of ${n}, so I'll stop here.`;return this.emit({type:"acted",n:e,error:`refused ${t}: it leaves ${n}`}),await this.speaking,this.deps.presence.say(s),await this.deps.speech.say({voice:this.opts.speaker.voice,text:s,agentId:this.opts.speaker.agentId,kind:"lesson"}),this.stop(`${t} would leave ${n}`),"stopped"}async refuseToClose(e,t){let n="That would close a tab or window you didn't ask to close, so I'll stop here.";return this.emit({type:"acted",n:e,error:`refused ${t}: it closes a tab or window`}),await this.speaking,this.deps.presence.say(n),await this.deps.speech.say({voice:this.opts.speaker.voice,text:n,agentId:this.opts.speaker.agentId,kind:"lesson"}),this.stop(`${t} would close a tab or window`),"stopped"}async waitForChange(){let e=await this.signature(),t=Date.now()+(this.opts.waitMs??45e3),n=null;for(;Date.now()<t&&this.is("running")&&!this.doorQueue.length;){if(await Promise.race([this.sleep(this.opts.pollMs??oo),this.poked()]),!this.is("running")||this.doorQueue.length)return!1;let s=await this.signature();if(s===null||s===e){n=null;continue}if(s===n)return!0;n=s}return!1}async settle(){let e=Date.now()+3e3,t=await this.signature();for(;Date.now()<e&&this.is("running");){await this.sleep(Math.min(oo,this.opts.pollMs??oo));let n=await this.signature();if(n===t)return;t=n}}async signature(){try{return cl(await this.deps.readScreen())}catch{return null}}async waitOutHush(){let e=Date.now()+(this.opts.holdMs??6e4);for(;this.is("held")&&Date.now()<e;)await Promise.race([this.poked(),this.sleep(e-Date.now())]);this.is("held")&&this.stop("no words after the hush")}silence(){this.deps.speech.cancel("lesson"),this.ac.abort(),this.ac=new AbortController}is(e){return this.state===e}sleep(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}poke(){let e=this.wake;this.wake=null,e?.()}poked(){return new Promise(e=>{this.wake=e})}emit(e){for(let t of this.listeners)try{t(e)}catch{}}};Ql();xn();import{execFile as tN}from"child_process";import{promisify as nN}from"util";Os();var ul="presence-mode";var i$={mode:Tn({talk:"Answer by voice only: a question, a status, a decision. Nothing on screen needs showing.",act:"The user asks the agent to do something on screen itself: click, fill in, operate an app for them.",teach:"The user wants to learn how to do something in an app, step by step, with the agent leading and showing where.",watch:"The user is driving and wants a coach: where a control is, what to do next, while they do it themselves.",quiet:"The agent should not appear on screen at all: a private matter, or the user is presenting or recording."},"How the agent should show up on screen for this turn."),persist:Pe("The agent's on-screen presence should stay after this turn, because the conversation is likely to continue on screen."),nextAction:Tn({speak:"Just say something.",point:"Move the agent's cursor to a control so the user sees where it is.",highlight:"Outline a control or area so the user sees what to look at.",click:"Press a control for the user.",type:"Type text into a field for the user.",wait_for_user:"Wait for the user to do something or say something first."},"The agent's first on-screen action this turn.")},r$=(r,e)=>r.length>e?`${r.slice(0,e)}\u2026`:r;function o$(r){return{agent:r.agent,request:r$(r.request,800),frontmostApp:r.app??null,window:r.window?r$(r.window,120):null,actionsAllowed:r.actionsAllowed,previousMode:r.previousMode??null}}var HD=.55,BD={mode:"talk",persist:!1,nextAction:"speak",chose:null,probability:0,override:"no-decision"},qD=/\b(show|teach|guide|walk|coach|watch)\s+(me|us)\b|\bhow\s+(do|can|would|should|to)\b|\bwhere\s+(is|are|do|can|'s)\b|\bwhere's\b|\bstep\s+by\s+step\b|\b(tutorial|lesson)\b|\b(montre|explique|guide)[- ]moi\b|\bcomment\s+(on|je|faire)\b|\bo[uù]\s+(est|sont|se\s+trouve)\b/i;function hl(r,e,t,n=HD){if(!r)return BD;let s=r.mode,i=r.nextAction,o=s.probabilities[s.choice]??0,a=r.persist.noul>=.5,c=s.choice;if(o<n)return{mode:"talk",persist:!1,nextAction:"speak",chose:c,probability:o,override:"low-confidence"};let d=s.choice,l=i.choice,u;return d==="act"&&!e&&(d="talk",u="actions-not-allowed"),(d==="teach"||d==="watch")&&!qD.test(t)&&(d="talk",u="not-asked-to-show"),(l==="click"||l==="type")&&d!=="act"&&(l="highlight"),(d==="talk"||d==="quiet")&&(l="speak"),{mode:d,persist:d!=="quiet"&&a,nextAction:l,chose:c,probability:o,...u?{override:u}:{}}}import{homedir as XD}from"node:os";import{execFile as VD}from"child_process";import{promisify as JD}from"util";import{existsSync as KD}from"fs";var a$=JD(VD),Ee=Pp(Cp(),XD(),process.env.AGENTX_MAC_HELPER),zD=6,YD=1e3;async function c$(r={}){if(!KD(Ee))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:e}=await a$(Ee,["read","--max",String(YD)],{maxBuffer:8*1024*1024}),t=JSON.parse(e),n=n$(t.elements,r.max??60,{request:r.request}),s=new Map;if(!(r.ocr!==!1&&n.length<zD))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:o}=await a$(Ee,["ocr"],{maxBuffer:8388608}),a=JSON.parse(o),c=Math.max(0,...t.elements.map(l=>l.id))+1,d=[];for(let l of a.hits){if(l.confidence<.5||l.text.length<2)continue;let u=c++;if(s.set(u,{x:l.x,y:l.y,width:l.width,height:l.height}),d.push({id:u,role:"OCRText",label:l.text,value:null,enabled:!0}),d.length>=(r.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...d],elements:t.elements,usedOCR:d.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function d$(r,e){let t=r.elements.find(n=>n.id===e);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:r.ocrRects.get(e)??null}import{execFile as QD}from"child_process";import{promisify as ZD}from"util";var eN=ZD(QD);async function l$(){let r=await c$({max:80});return{app:r.app,window:r.window,candidates:r.candidates.map(e=>({id:e.id,role:e.role,label:e.label,shown:e.shown,value:e.value,...e.closes?{closes:e.closes}:{}})),rectOf:e=>d$(r,e)}}async function ao(r){try{let{stdout:e}=await eN(Ee,r),t=JSON.parse(e||"{}");return t.ok===!1?String(t.error??"refused"):null}catch(e){try{return String(JSON.parse(e?.stdout||"{}").error??e?.message)}catch{return e?.message??"failed"}}}var u$=async r=>{if(r.action==="key"){let u=r.keys.toLowerCase().split("+").map(f=>f.trim()).filter(Boolean),h=u.pop();return h?{error:await ao(["key","--name",h,...u.length?["--mod",u.join("+")]:[]])}:{error:`no key in "${r.keys}"`}}let{action:e,rect:t,label:n,role:s,text:i}=r,a=s!=="AXImage"&&/\p{L}{2}/u.test(n)||!s?n.slice(0,40):s,c=["--x",String(t.x),"--y",String(t.y),"--w",String(t.width),"--h",String(t.height)],d=await ao(["point",...c,"--label",n.slice(0,40),"--hold","0.3"]);if(d)return{error:d};let l=await ao(["click","--settle","0.1",...a?["--expect",a]:[]]);return l||e==="click"?{error:l}:{error:await ao(["type","--text",i??""])}};var sN=nN(tN),h$=2500,rN=zd*1e3/3;async function iN(){try{let{stdout:r}=await sN(Ee,["focused"],{timeout:1500});return JSON.parse(r).app||null}catch{return null}}var co=class{constructor(e,t,n={}){this.agents=e;this.log=t;this.deps=n}slots=new Map;lastMode=new Map;async decide(e,t){let n=Ku(ul),s=we(e,this.agents()[e]);if(n==="off")return{...hl(null,s.allowActions,t),seat:n,app:null};let i=await(this.deps.frontmostApp??iN)(),o=new AbortController,a,c=await Promise.race([He(ul,o$({agent:e,request:t,app:i,actionsAllowed:s.allowActions,previousMode:this.lastMode.get(e)??null}),i$,{timeoutMs:h$,signal:o.signal,incumbent:{mode:"talk"},features:{agent:e,app:i??"none"}}),new Promise(l=>{a=setTimeout(()=>{o.abort(),l(null)},h$)})]).finally(()=>clearTimeout(a)),d=hl(c?.answers??null,s.allowActions,t);return this.lastMode.set(e,d.mode),this.log(`[presence] ${e} seat=${n} chose=${d.chose??"-"} p=${d.probability.toFixed(2)} \u2192 ${d.mode} next=${d.nextAction}${d.persist?" persist":""}${d.override?` (${d.override})`:""}`),{...d,seat:n,app:i}}lesson(e,t,n,s,i,o){let a=this.agents(),c=this.deps.voiceSettings?.(),d=er(e,a,!1,c),l=c?.listener??ps,u=we(e,a[e]);return new ct({goal:t,mode:n,speaker:d,actionsAllowed:u.allowActions,app:o,listener:l},{readScreen:this.deps.screen?.readScreen??l$,act:this.deps.screen?.act??u$,presence:c?.pointer===!1?R0:this.lessonPointer(e),speech:s,model:i(rl(d.persona,l))})}lessonPointer(e){let t=this.acquire(e);return{moveTo:(n,s)=>t.presence.moveTo(n,s),say:n=>t.presence.say(n),clear:()=>t.presence.clear(),park:()=>t.presence.park(),close:()=>{this.slots.get(e)===t&&this.hide(e)}}}hide(e){let t=this.slots.get(e);t&&(clearInterval(t.ping),t.presence.close(),this.slots.delete(e))}close(){for(let e of[...this.slots.keys()])this.hide(e)}get onScreen(){return[...this.slots.keys()]}reapOrphans(){let e=_0();e&&this.log(`[presence] ended ${e} leftover overlay${e===1?"":"s"}`)}acquire(e){let t=this.slots.get(e);if(t&&t.presence.alive===!1)this.hide(e);else if(t)return t;let n=this.overlay(we(e,this.agents()[e]),e),s=setInterval(()=>n.ping?.(),rN);s.unref?.();let i={presence:n,ping:s};return this.slots.set(e,i),i}overlay(e,t){return this.deps.overlay?.(e,t)??this.deps.character?.(t)??new zi(e,Ee,t)}};var lo=class{constructor(e,t,n=()=>{},s={}){this.agents=e;this.intros=t;this.log=n;this.speech=s.speech??new io,s.onQueue&&(this.speech.events.onChange=s.onQueue),this.speech.events.onStopped=(o,a,c)=>this.log(`[voice] ${o.kind??"line"}${o.agentId?` (${o.agentId})`:""} ${a} after ${(c/1e3).toFixed(1)}s, ${o.text.length} chars`),this.model=s.model??(o=>Y0({system:o})),this.remote=s.remote??(()=>{}),this.stopSpeakers=s.stopSpeakers??(()=>qf());let i=s.voiceSettings??(()=>({}));this.settings=i,this.floor=new zl({...s.floor,settings:()=>i().floor,busy:()=>this.live?`a ${this.kind(this.live)}`:null,onChange:(o,a)=>{let c=!!a&&a===this.floorId;this.floorId=a,a?this.speech.reserve(a):this.speech.release(o.ended==="owner"||o.ended==="expired"),c||(o.held?(this.log(`[floor] held by ${o.holder} until ${new Date(o.expiresAt).toISOString()}${o.sound?", plays sound":""}${o.hide?", character and bubbles hidden":""}`),this.guide.home()):this.log(`[floor] free (${o.ended})`)),s.onFloor?.(o)}}),this.presence=new co(e,n,{voiceSettings:i,character:o=>i().look==="character"&&this.guide.listening?new qi(this.guide,o):null,...s.presence}),this.narrator=new ro({speech:this.speech,model:()=>this.model(J0),voiceOf:o=>{let a=this.agents()[o];if(!a)return null;let c=ve(o,this.agents(),this.settings());return{name:c.name,voice:Oe(c),style:c.style,narrate:a.voice?.narrate??"off"}}})}speech;narrator;presence;guide=new Bi;floor;floorId=null;session=null;hushed=null;heldQueue=!1;model;remote;settings;stopSpeakers;handle(e,t,n){let s=this.live;switch(`${e} ${t}`){case"GET /talk":return{status:200,body:s?this.view(s):{active:!1}};case"POST /talk":return this.start(n);case"POST /teach/live":{let i=String(n.agent??n.agentId??""),o=String(n.goal??"").trim(),a=String(n.mode??"teach");return!o||!["teach","watch","act"].includes(a)?{status:400,body:{error:"Required: agent, goal, and mode teach | watch | act"}}:this.agents()[i]?this.startLesson(i,o,a,String(n.app??"").trim()||void 0):{status:404,body:{error:`Unknown agent: ${i}`}}}case"POST /talk/hush":case"POST /voice/hush":return this.hush();case"POST /voice/stop":{let i=this.live,o=this.hush();i?.stop("stopped"),this.speech.stop(),this.hushed=null,this.heldQueue=!1;let a=this.floor.revoke();return{status:o.status,body:{...o.body,active:!1,...a?{floorRevoked:!0}:{}}}}case"POST /talk/door":case"POST /voice/door":{let i=String(n.text??"").trim();return i?this.door(i):{status:400,body:{error:"Required: text"}}}case"POST /talk/stop":return s?.stop("stopped"),{status:200,body:{active:!1}};case"GET /narration":return{status:200,body:this.narrator.status()};case"POST /narration":{let i=n.on===null?null:n.on===!0?!0:n.on===!1?!1:void 0,o=n.agentId?String(n.agentId):void 0,a=n.taskId?String(n.taskId):void 0;return i===void 0||!o&&!a?{status:400,body:{error:"Required: agentId or taskId, and on: true | false | null"}}:o&&!this.agents()[o]?{status:404,body:{error:`Unknown agent: ${o}`}}:(this.narrator.set({agentId:o,taskId:a},i),{status:200,body:this.narrator.status()})}default:return{status:404,body:{error:"Not found"}}}}hush(){let e=this.live;e?.hush();let t=this.speech.view(),n=t.playing??t.waiting[0]??null;this.speech.pause(),this.heldQueue=!!n,this.stopSpeakers();let s=this.narrator.hush();this.hushed=e?null:s;let i=e?this.kind(e):s?"narration":n?"queue":null,o=e?this.agentOf(e):s?.agentId??n?.agentId??null;return this.log(`[door] hush \u2192 ${i?`${i}${o?` (${o})`:""}`:"nothing was speaking"}`),{status:200,body:{active:!!e&&e.state!=="ended",kind:i,agentId:o}}}door(e){let t=this.live,n=this.hushed,s=this.heldQueue;this.hushed=null,this.heldQueue=!1,this.narrator.release();let i=gs(e);i?this.speech.stop():this.speech.resume();let o=`"${e.slice(0,80)}"`;return t?(t.door(e),this.log(`[door] ${o} \u2192 ${this.kind(t)}${t.state==="ended"?" (ended)":""}`),{status:200,body:{active:t.state!=="ended",kind:this.kind(t),handled:!0}}):n&&i?(this.narrator.set({taskId:n.taskId},!1),this.log(`[door] ${o} \u2192 narration of ${n.taskId} off`),{status:200,body:{active:!1,kind:"narration",handled:!0}}):s&&i?(this.log(`[door] ${o} \u2192 speaking queue emptied`),{status:200,body:{active:!1,kind:"queue",handled:!0}}):(this.log(`[door] ${o} \u2192 nothing to take it; the client asks the agent`),{status:409,body:{active:!1,handled:!1,error:"No talk or lesson is running"}})}close(){this.session?.stop("daemon stopping"),this.floor.close(),this.narrator.close(),this.presence.close()}get live(){return this.session&&this.session.state!=="ended"?this.session:null}startLesson(e,t,n,s){if(this.live)return{status:409,body:{error:"A talk or lesson is already running",...this.view(this.live)}};let i=this.floorHeld();if(i)return i;let o=this.presence.lesson(e,t,n,this.speech,this.model,s),a=c=>this.log(`[teach] ${new Date().toISOString()} ${c}`);return o.on(c=>{if(c.type==="step"){let d=c.planMs===void 0?"":` (screen ${c.readMs} ms, plan ${c.planMs} ms)`;a(`${c.n}. ${c.action}${c.target?` "${c.target.slice(0,60)}"`:""}: ${c.say}${d}`)}else c.type==="acted"&&c.error?a(`action refused: ${c.error}`):c.type==="replanned"?a(`replanning: ${c.reason}`):c.type==="error"?a(`error: ${c.error}`):c.type==="end"&&a(`ended (${c.reason})`)}),this.session=o,o.run(),a(`${e} (${n}): ${t.slice(0,100)}`),{status:201,body:this.view(o)}}start(e){if(this.live)return{status:409,body:{error:"A talk or lesson is already running",...this.view(this.live)}};let t=this.floorHeld();if(t)return t;let n=Array.isArray(e.agents)?e.agents.map(String):[],s=String(e.topic??"").trim(),i=this.agents();if(n.length!==2||n[0]===n[1]||!s)return{status:400,body:{error:"Required: agents (two different ids) and topic"}};let o="talk",a=h=>{let f=this.intros.needsIntro(o,h);return i[h]?er(h,i,f,this.settings()):this.remote(h,f)},c=n.map(a),d=n.filter((h,f)=>!c[f]);if(d.length)return{status:404,body:{error:`Unknown agent: ${d.join(", ")}`}};let l=c,u=new so({topic:s,speakers:l,speech:this.speech,context:e.context?String(e.context):void 0,maxTurns:Math.max(2,Math.min(40,Number(e.maxTurns)||10)),listener:this.settings().listener,model:(h,f)=>this.model(f)});return u.on(h=>{h.type==="line"?(this.intros.spoke(o,h.agentId),this.log(`[talk] ${h.name}: ${h.text}`)):h.type==="gap"?this.log(`[talk] gap ${h.ms} ms`):h.type==="error"?this.log(`[talk] error: ${h.error}`):h.type==="end"&&this.log(`[talk] ended (${h.reason})`)}),this.session=u,u.run(),this.log(`[talk] ${l[0].name} and ${l[1].name} on "${s.slice(0,80)}"`),{status:201,body:this.view(u)}}floorHeld(){let e=this.floor.view();return e.held?{status:409,body:{error:`The floor is held by ${e.holder}`,floor:e}}:null}kind(e){return e instanceof ct?"lesson":"talk"}agentOf(e){return e instanceof ct?e.agentId:null}view(e){return e instanceof ct?{active:e.state!=="ended",kind:"lesson",id:e.id,state:e.state,step:e.step,saying:e.lastSay,agentId:e.agentId,mode:e.mode,goal:e.goal.slice(0,160),startedAt:e.startedAt}:{active:e.state!=="ended",kind:"talk",id:e.id,state:e.state,startedAt:e.startedAt,transcript:e.transcript,gaps:e.gaps}}};xn();Os();var g$="voice-narration",gl={calendar:"checking your calendar",email:"going through your email",messages:"reading your messages",files:"looking through your files",search:"searching for that",web:"looking it up online",code:"going through the code",git:"checking the repository",infrastructure:"checking the servers",writing:"writing that up",sending:"sending it",scheduling:"setting that up",data:"pulling the numbers together",waiting:"waiting on a slow response",other:"still on it"},p$={worthSaying:Pe("This step is worth interrupting the person to mention out loud.",{true:"It is slow, external, or a visible action with consequences \u2014 sending something, waiting on a service, a long search \u2014 so a person left in silence would wonder whether anything is happening.",false:"It is routine internal work: reading a file, a quick lookup, a check that takes a moment. Mentioning it is noise."}),doing:Tn(Object.fromEntries(Object.entries(gl).map(([r,e])=>[r,`The agent is ${e}.`])),"What kind of work is this step?")};function f$(r){return{tool:r.tool,detail:oN(r.detail,600),secondsWaiting:r.elapsedSeconds}}function m$(r,e=.6){let t=r.worthSaying.noul,s=r.doing.choice;return{say:t>=e?gl[s]??gl.other:null,category:s,worth:t}}function oN(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var v$=60*60*1e3,aN=5*60*1e3,cN=30*60*1e3,y$=16,w$=100,dN=24*v$,lN=2e3,uo=class{constructor(e){this.deps=e;this.now=e.now??Date.now}wakes=new Map;own=new Map;woken=new Map;held=new Map;now;handle(e){let t=[],n=this.deps.agents(),s=this.now(),i=this.deps.isLocal?this.deps.isLocal(e):!0;for(let[o,a]of Object.entries(n)){let c=Ih(a.subscriptions,"wake");if(c.length===0)continue;if(e.agentId===o){b$(this.own,o,e.rootId,s),c.some(h=>$h({...h,agents:void 0},e))&&t.push({agentId:o,eventId:e.id,woke:!1,reason:"own-event"});continue}let d=(a.subscriptions??[]).map((h,f)=>({s:h,index:f})).filter(({s:h})=>h.delivery==="wake"&&Sh(h,e,o)&&(i||(h.nodes?.includes(e.node)??!1)));if(d.length===0)continue;let{outcome:l,sub:u}=this.decide(o,e,d,s);if(t.push(l),!l.woke){this.deps.log(`[events] wake skipped for ${o}: ${l.reason} \u2014 ${En(e)} root=${e.rootId.slice(0,8)}`);continue}this.deps.log(`[events] waking ${o} \u2014 ${En(e)} root=${e.rootId.slice(0,8)}`),setImmediate(()=>this.run(o,e,u,0))}return t}pendingRetries(){return this.held.size}stop(){for(let e of this.held.values())clearTimeout(e);this.held.clear()}run(e,t,n,s){let i=o=>this.deps.log(`[events] wake of ${e} failed: ${o?.message??o}`);try{Promise.resolve(this.deps.dispatch(e,t,n)).then(o=>{let a=uN(o);a&&this.retry(e,t,n,s,a)},i)}catch(o){i(o)}}retry(e,t,n,s,i){let o=`${e}#${t.id}`,a=`${En(t)} root=${t.rootId.slice(0,8)}`;if(s>=y$){this.deps.log(`[events] wake of ${e} dropped after ${s} retries, still held: ${i} \u2014 ${a}`);return}if(!this.held.has(o)&&this.held.size>=w$){this.deps.log(`[events] wake of ${e} dropped, ${w$} held wakes already queued: ${i} \u2014 ${a}`);return}let c=Math.min(aN*2**s,cN);this.deps.log(`[events] wake of ${e} held: ${i} \u2014 retry ${s+1}/${y$} in ${Math.round(c/6e4)} min \u2014 ${a}`);let d=setTimeout(()=>{this.held.delete(o),this.run(e,t,n,s+1)},c);d.unref?.(),this.held.set(o,d)}decide(e,t,n,s){let i={agentId:e,eventId:t.id};if(k$(this.own,e,t.rootId,s))return{outcome:{...i,woke:!1,reason:"own-root"}};if(k$(this.woken,e,t.rootId,s))return{outcome:{...i,woke:!1,reason:"duplicate-root"}};for(let{s:o,index:a}of n){let c=`${e}#${a}`,d=(this.wakes.get(c)??[]).filter(l=>s-l<v$);if(d.length>=(o.maxPerHour??4)){this.wakes.set(c,d);continue}return d.push(s),this.wakes.set(c,d),b$(this.woken,e,t.rootId,s),{outcome:{...i,woke:!0},sub:o}}return{outcome:{...i,woke:!1,reason:"rate-limit"}}}attach(e){let t=e.subscribe(n=>{this.handle(n)});return()=>{t(),this.stop()}}};function b$(r,e,t,n){let s=r.get(e);s||(s=new Map,r.set(e,s)),s.delete(t),s.set(t,n),s.size>lN&&s.delete(s.keys().next().value)}function k$(r,e,t,n){let s=r.get(e)?.get(t);return s!==void 0&&n-s<dN}function uN(r){if(!r||typeof r!="object")return;let e=r.held;return typeof e=="string"&&e?e:void 0}function S$(r,e){let t=["[Event] A subscription of yours matched:",En(r),`Event: ${r.type} (kind ${r.kind}), emitted by ${r.agentId?`${r.agentId} on ${r.node}`:r.node}${r.ref?`, ref ${r.ref}`:""}.`,`Event id ${r.id}, root ${r.rootId}. Call agentx_events for the surrounding events.`];return e?.trim()?t.push(`When this event arrives: ${e.trim()}`):t.push("Act on it if it needs you; otherwise reply briefly that no action is needed."),t.join(`
|
|
1156
|
+
`),i=this.ac.signal,o="";for await(let a of this.deps.model.reply(s,i))o+=a;return i.aborted?null:al(o,new Set(e.candidates.map(a=>a.id)))}async recheck(e,t){let n=await this.deps.readScreen();if(n.app!==t.app)return{stale:`${n.app} is in front now, not ${t.app}`};if((n.window??"")!==(t.window??""))return{stale:`the window changed from "${t.window??""}" to "${n.window??""}"`};if(e.target===null)return{screen:n,target:null};let s=Z0(t,e.target,n);return s!==null?{screen:n,target:s}:{stale:`"${t.candidates.find(o=>o.id===e.target)?.label??""}" is no longer on screen`}}replanned(e,t){return this.emit({type:"replanned",n:this.step,reason:e}),this.deps.presence.clear(),this.history.push(`The screen changed before you acted (${e}); plan again from what is there now.`),t<=(this.opts.maxReplans??3)?!0:(this.stop("the screen kept changing"),!1)}async perform(e,t,n){let{screen:s,target:i}=n,o=i!==null?s.rectOf(i):null,a=i!==null?s.candidates.find(w=>w.id===i)?.label??"":"",c=i!==null&&s$(s.candidates.find(w=>w.id===i),this.opts.goal),d=this.opts.mode==="act"&&this.opts.actionsAllowed&&!((t.action==="click"||t.action==="type")&&c);if(d&&t.action==="key"&&t.text&&il(t.text))return this.refuseToLeave(e,t.text,s.app);if(d&&t.action==="key"&&t.text&&ol(t.text)&&!ll(this.opts.goal))return this.refuseToClose(e,t.text);let l=t.action==="key"?d&&t.text?"key":o?"highlight":"wait_for_user":(t.action==="click"||t.action==="type")&&(!d||!o)?"highlight":t.action;this.emit({type:"step",n:e,action:l,target:a||null,say:t.say,...this.took});let{presence:u,speech:h}=this.deps;o&&u.moveTo(o,{highlight:l!=="point"}),u.say(Q0(o?a:null)),this.lastSay=t.say,await this.speaking;let f=t.say?h.say({voice:this.opts.speaker.voice,text:t.say,agentId:this.opts.speaker.agentId,kind:"lesson"}):Promise.resolve(!0);if(d&&(l==="key"?!!t.text:(l==="click"||l==="type")&&!!o)?this.speaking=f:await Promise.race([f,this.poked()]),!this.is("running")||this.doorQueue.length)return this.history.push(`Step ${e}: you started "${t.say}" and were cut off.`),this.is("ended")?"stopped":"next";if(l==="done")return"done";if(l==="key"&&t.text){let w=await this.recheck({...t,target:null},s);if("stale"in w)return w;let b=await this.deps.act({action:"key",keys:t.text});return this.emit({type:"acted",n:e,error:b.error}),this.history.push(b.error?`Step ${e}: you tried to press ${t.text} and it failed: ${b.error}`:`Step ${e}: you pressed ${t.text}.`),b.error||await this.settle(),"next"}if((l==="click"||l==="type")&&o){let w=await this.recheck({...t,target:i},s);if("stale"in w)return w;let b=w.target!==null?w.screen.rectOf(w.target):null;if(!b)return{stale:`"${a}" is no longer on screen`};let $=s.candidates.find(x=>x.id===i)?.role,k=await this.deps.act({action:l,rect:b,label:a,role:$,text:t.text??void 0});return this.emit({type:"acted",n:e,error:k.error}),this.history.push(k.error?`Step ${e}: you tried to ${l} "${a}" and it failed: ${k.error}`:`Step ${e}: you ${l==="click"?"clicked":`typed "${t.text}" into`} "${a}".`),k.error||await this.settle(),"next"}let g=await this.waitForChange();return u.say(""),u.park(),this.emit({type:"changed",n:e,changed:g}),this.history.push(`Step ${e}: you said "${t.say}"${a?` about "${a}"`:""}. `+(g?`${this.listener} did something; the screen changed.`:"Nothing changed on screen.")),"next"}async refuseToLeave(e,t,n){let s=`That would take me out of ${n}, so I'll stop here.`;return this.emit({type:"acted",n:e,error:`refused ${t}: it leaves ${n}`}),await this.speaking,this.deps.presence.say(s),await this.deps.speech.say({voice:this.opts.speaker.voice,text:s,agentId:this.opts.speaker.agentId,kind:"lesson"}),this.stop(`${t} would leave ${n}`),"stopped"}async refuseToClose(e,t){let n="That would close a tab or window you didn't ask to close, so I'll stop here.";return this.emit({type:"acted",n:e,error:`refused ${t}: it closes a tab or window`}),await this.speaking,this.deps.presence.say(n),await this.deps.speech.say({voice:this.opts.speaker.voice,text:n,agentId:this.opts.speaker.agentId,kind:"lesson"}),this.stop(`${t} would close a tab or window`),"stopped"}async waitForChange(){let e=await this.signature(),t=Date.now()+(this.opts.waitMs??45e3),n=null;for(;Date.now()<t&&this.is("running")&&!this.doorQueue.length;){if(await Promise.race([this.sleep(this.opts.pollMs??oo),this.poked()]),!this.is("running")||this.doorQueue.length)return!1;let s=await this.signature();if(s===null||s===e){n=null;continue}if(s===n)return!0;n=s}return!1}async settle(){let e=Date.now()+3e3,t=await this.signature();for(;Date.now()<e&&this.is("running");){await this.sleep(Math.min(oo,this.opts.pollMs??oo));let n=await this.signature();if(n===t)return;t=n}}async signature(){try{return cl(await this.deps.readScreen())}catch{return null}}async waitOutHush(){let e=Date.now()+(this.opts.holdMs??6e4);for(;this.is("held")&&Date.now()<e;)await Promise.race([this.poked(),this.sleep(e-Date.now())]);this.is("held")&&this.stop("no words after the hush")}silence(){this.deps.speech.cancel("lesson"),this.ac.abort(),this.ac=new AbortController}is(e){return this.state===e}sleep(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}poke(){let e=this.wake;this.wake=null,e?.()}poked(){return new Promise(e=>{this.wake=e})}emit(e){for(let t of this.listeners)try{t(e)}catch{}}};Ql();xn();import{execFile as tN}from"child_process";import{promisify as nN}from"util";Os();var ul="presence-mode";var i$={mode:Tn({talk:"Answer by voice only: a question, a status, a decision. Nothing on screen needs showing.",act:"The user asks the agent to do something on screen itself: click, fill in, operate an app for them.",teach:"The user wants to learn how to do something in an app, step by step, with the agent leading and showing where.",watch:"The user is driving and wants a coach: where a control is, what to do next, while they do it themselves.",quiet:"The agent should not appear on screen at all: a private matter, or the user is presenting or recording."},"How the agent should show up on screen for this turn."),persist:Pe("The agent's on-screen presence should stay after this turn, because the conversation is likely to continue on screen."),nextAction:Tn({speak:"Just say something.",point:"Move the agent's cursor to a control so the user sees where it is.",highlight:"Outline a control or area so the user sees what to look at.",click:"Press a control for the user.",type:"Type text into a field for the user.",wait_for_user:"Wait for the user to do something or say something first."},"The agent's first on-screen action this turn.")},r$=(r,e)=>r.length>e?`${r.slice(0,e)}\u2026`:r;function o$(r){return{agent:r.agent,request:r$(r.request,800),frontmostApp:r.app??null,window:r.window?r$(r.window,120):null,actionsAllowed:r.actionsAllowed,previousMode:r.previousMode??null}}var HD=.55,BD={mode:"talk",persist:!1,nextAction:"speak",chose:null,probability:0,override:"no-decision"},qD=/\b(show|teach|guide|walk|coach|watch)\s+(me|us)\b|\bhow\s+(do|can|would|should|to)\b|\bwhere\s+(is|are|do|can|'s)\b|\bwhere's\b|\bstep\s+by\s+step\b|\b(tutorial|lesson)\b|\b(montre|explique|guide)[- ]moi\b|\bcomment\s+(on|je|faire)\b|\bo[uù]\s+(est|sont|se\s+trouve)\b/i;function hl(r,e,t,n=HD){if(!r)return BD;let s=r.mode,i=r.nextAction,o=s.probabilities[s.choice]??0,a=r.persist.noul>=.5,c=s.choice;if(o<n)return{mode:"talk",persist:!1,nextAction:"speak",chose:c,probability:o,override:"low-confidence"};let d=s.choice,l=i.choice,u;return d==="act"&&!e&&(d="talk",u="actions-not-allowed"),(d==="teach"||d==="watch")&&!qD.test(t)&&(d="talk",u="not-asked-to-show"),(l==="click"||l==="type")&&d!=="act"&&(l="highlight"),(d==="talk"||d==="quiet")&&(l="speak"),{mode:d,persist:d!=="quiet"&&a,nextAction:l,chose:c,probability:o,...u?{override:u}:{}}}import{homedir as XD}from"node:os";import{execFile as VD}from"child_process";import{promisify as JD}from"util";import{existsSync as KD}from"fs";var a$=JD(VD),Ee=Pp(Cp(),XD(),process.env.AGENTX_MAC_HELPER),zD=6,YD=1e3;async function c$(r={}){if(!KD(Ee))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:e}=await a$(Ee,["read","--max",String(YD)],{maxBuffer:8*1024*1024}),t=JSON.parse(e),n=n$(t.elements,r.max??60,{request:r.request}),s=new Map;if(!(r.ocr!==!1&&n.length<zD))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:o}=await a$(Ee,["ocr"],{maxBuffer:8388608}),a=JSON.parse(o),c=Math.max(0,...t.elements.map(l=>l.id))+1,d=[];for(let l of a.hits){if(l.confidence<.5||l.text.length<2)continue;let u=c++;if(s.set(u,{x:l.x,y:l.y,width:l.width,height:l.height}),d.push({id:u,role:"OCRText",label:l.text,value:null,enabled:!0}),d.length>=(r.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...d],elements:t.elements,usedOCR:d.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function d$(r,e){let t=r.elements.find(n=>n.id===e);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:r.ocrRects.get(e)??null}import{execFile as QD}from"child_process";import{promisify as ZD}from"util";var eN=ZD(QD);async function l$(){let r=await c$({max:80});return{app:r.app,window:r.window,candidates:r.candidates.map(e=>({id:e.id,role:e.role,label:e.label,shown:e.shown,value:e.value,...e.closes?{closes:e.closes}:{}})),rectOf:e=>d$(r,e)}}async function ao(r){try{let{stdout:e}=await eN(Ee,r),t=JSON.parse(e||"{}");return t.ok===!1?String(t.error??"refused"):null}catch(e){try{return String(JSON.parse(e?.stdout||"{}").error??e?.message)}catch{return e?.message??"failed"}}}var u$=async r=>{if(r.action==="key"){let u=r.keys.toLowerCase().split("+").map(f=>f.trim()).filter(Boolean),h=u.pop();return h?{error:await ao(["key","--name",h,...u.length?["--mod",u.join("+")]:[]])}:{error:`no key in "${r.keys}"`}}let{action:e,rect:t,label:n,role:s,text:i}=r,a=s!=="AXImage"&&/\p{L}{2}/u.test(n)||!s?n.slice(0,40):s,c=["--x",String(t.x),"--y",String(t.y),"--w",String(t.width),"--h",String(t.height)],d=await ao(["point",...c,"--label",n.slice(0,40),"--hold","0.3"]);if(d)return{error:d};let l=await ao(["click","--settle","0.1",...a?["--expect",a]:[]]);return l||e==="click"?{error:l}:{error:await ao(["type","--text",i??""])}};var sN=nN(tN),h$=2500,rN=zd*1e3/3;async function iN(){try{let{stdout:r}=await sN(Ee,["focused"],{timeout:1500});return JSON.parse(r).app||null}catch{return null}}var co=class{constructor(e,t,n={}){this.agents=e;this.log=t;this.deps=n}slots=new Map;lastMode=new Map;async decide(e,t){let n=Ku(ul),s=we(e,this.agents()[e]);if(n==="off")return{...hl(null,s.allowActions,t),seat:n,app:null};let i=await(this.deps.frontmostApp??iN)(),o=new AbortController,a,c=await Promise.race([He(ul,o$({agent:e,request:t,app:i,actionsAllowed:s.allowActions,previousMode:this.lastMode.get(e)??null}),i$,{timeoutMs:h$,signal:o.signal,incumbent:{mode:"talk"},features:{agent:e,app:i??"none"}}),new Promise(l=>{a=setTimeout(()=>{o.abort(),l(null)},h$)})]).finally(()=>clearTimeout(a)),d=hl(c?.answers??null,s.allowActions,t);return this.lastMode.set(e,d.mode),this.log(`[presence] ${e} seat=${n} chose=${d.chose??"-"} p=${d.probability.toFixed(2)} \u2192 ${d.mode} next=${d.nextAction}${d.persist?" persist":""}${d.override?` (${d.override})`:""}`),{...d,seat:n,app:i}}lesson(e,t,n,s,i,o){let a=this.agents(),c=this.deps.voiceSettings?.(),d=er(e,a,!1,c),l=c?.listener??ps,u=we(e,a[e]);return new ct({goal:t,mode:n,speaker:d,actionsAllowed:u.allowActions,app:o,listener:l},{readScreen:this.deps.screen?.readScreen??l$,act:this.deps.screen?.act??u$,presence:c?.pointer===!1?R0:this.lessonPointer(e),speech:s,model:i(rl(d.persona,l))})}lessonPointer(e){let t=this.acquire(e);return{moveTo:(n,s)=>t.presence.moveTo(n,s),say:n=>t.presence.say(n),clear:()=>t.presence.clear(),park:()=>t.presence.park(),close:()=>{this.slots.get(e)===t&&this.hide(e)}}}hide(e){let t=this.slots.get(e);t&&(clearInterval(t.ping),t.presence.close(),this.slots.delete(e))}close(){for(let e of[...this.slots.keys()])this.hide(e)}get onScreen(){return[...this.slots.keys()]}reapOrphans(){let e=_0();e&&this.log(`[presence] ended ${e} leftover overlay${e===1?"":"s"}`)}acquire(e){let t=this.slots.get(e);if(t&&t.presence.alive===!1)this.hide(e);else if(t)return t;let n=this.overlay(we(e,this.agents()[e]),e),s=setInterval(()=>n.ping?.(),rN);s.unref?.();let i={presence:n,ping:s};return this.slots.set(e,i),i}overlay(e,t){return this.deps.overlay?.(e,t)??this.deps.character?.(t)??new zi(e,Ee,t)}};var lo=class{constructor(e,t,n=()=>{},s={}){this.agents=e;this.intros=t;this.log=n;this.speech=s.speech??new io,s.onQueue&&(this.speech.events.onChange=s.onQueue),this.speech.events.onStopped=(o,a,c)=>this.log(`[voice] ${o.kind??"line"}${o.agentId?` (${o.agentId})`:""} ${a} after ${(c/1e3).toFixed(1)}s, ${o.text.length} chars`),this.model=s.model??(o=>Y0({system:o})),this.remote=s.remote??(()=>{}),this.stopSpeakers=s.stopSpeakers??(()=>qf());let i=s.voiceSettings??(()=>({}));this.settings=i,this.floor=new zl({...s.floor,settings:()=>i().floor,busy:()=>this.live?`a ${this.kind(this.live)}`:null,onChange:(o,a)=>{let c=!!a&&a===this.floorId;this.floorId=a,a?this.speech.reserve(a):this.speech.release(o.ended==="owner"||o.ended==="expired"),c||(o.held?(this.log(`[floor] held by ${o.holder} until ${new Date(o.expiresAt).toISOString()}${o.sound?", plays sound":""}${o.hide?", character and bubbles hidden":""}`),this.guide.home()):this.log(`[floor] free (${o.ended})`)),s.onFloor?.(o)}}),this.presence=new co(e,n,{voiceSettings:i,character:o=>i().look==="character"&&this.guide.listening?new qi(this.guide,o):null,...s.presence}),this.narrator=new ro({speech:this.speech,model:()=>this.model(J0),voiceOf:o=>{let a=this.agents()[o];if(!a)return null;let c=ve(o,this.agents(),this.settings());return{name:c.name,voice:Oe(c),style:c.style,narrate:a.voice?.narrate??"off"}}})}speech;narrator;presence;guide=new Bi;floor;floorId=null;session=null;hushed=null;heldQueue=!1;model;remote;settings;stopSpeakers;handle(e,t,n){let s=this.live;switch(`${e} ${t}`){case"GET /talk":return{status:200,body:s?this.view(s):{active:!1}};case"POST /talk":return this.start(n);case"POST /teach/live":{let i=String(n.agent??n.agentId??""),o=String(n.goal??"").trim(),a=String(n.mode??"teach");return!o||!["teach","watch","act"].includes(a)?{status:400,body:{error:"Required: agent, goal, and mode teach | watch | act"}}:this.agents()[i]?this.startLesson(i,o,a,String(n.app??"").trim()||void 0):{status:404,body:{error:`Unknown agent: ${i}`}}}case"POST /talk/hush":case"POST /voice/hush":return this.hush();case"POST /voice/stop":{let i=this.live,o=this.hush();i?.stop("stopped"),this.speech.stop(),this.hushed=null,this.heldQueue=!1;let a=this.floor.revoke();return{status:o.status,body:{...o.body,active:!1,...a?{floorRevoked:!0}:{}}}}case"POST /talk/door":case"POST /voice/door":{let i=String(n.text??"").trim();return i?this.door(i):{status:400,body:{error:"Required: text"}}}case"POST /talk/stop":return s?.stop("stopped"),{status:200,body:{active:!1}};case"GET /narration":return{status:200,body:this.narrator.status()};case"POST /narration":{let i=n.on===null?null:n.on===!0?!0:n.on===!1?!1:void 0,o=n.agentId?String(n.agentId):void 0,a=n.taskId?String(n.taskId):void 0;return i===void 0||!o&&!a?{status:400,body:{error:"Required: agentId or taskId, and on: true | false | null"}}:o&&!this.agents()[o]?{status:404,body:{error:`Unknown agent: ${o}`}}:(this.narrator.set({agentId:o,taskId:a},i),{status:200,body:this.narrator.status()})}default:return{status:404,body:{error:"Not found"}}}}hush(){let e=this.live;e?.hush();let t=this.speech.view(),n=t.playing??t.waiting[0]??null;this.speech.pause(),this.heldQueue=!!n,this.stopSpeakers();let s=this.narrator.hush();this.hushed=e?null:s;let i=e?this.kind(e):s?"narration":n?"queue":null,o=e?this.agentOf(e):s?.agentId??n?.agentId??null;return this.log(`[door] hush \u2192 ${i?`${i}${o?` (${o})`:""}`:"nothing was speaking"}`),{status:200,body:{active:!!e&&e.state!=="ended",kind:i,agentId:o}}}door(e){let t=this.live,n=this.hushed,s=this.heldQueue;this.hushed=null,this.heldQueue=!1,this.narrator.release();let i=gs(e);i?this.speech.stop():this.speech.resume();let o=`"${e.slice(0,80)}"`;return t?(t.door(e),this.log(`[door] ${o} \u2192 ${this.kind(t)}${t.state==="ended"?" (ended)":""}`),{status:200,body:{active:t.state!=="ended",kind:this.kind(t),handled:!0}}):n&&i?(this.narrator.set({taskId:n.taskId},!1),this.log(`[door] ${o} \u2192 narration of ${n.taskId} off`),{status:200,body:{active:!1,kind:"narration",handled:!0}}):s&&i?(this.log(`[door] ${o} \u2192 speaking queue emptied`),{status:200,body:{active:!1,kind:"queue",handled:!0}}):(this.log(`[door] ${o} \u2192 nothing to take it; the client asks the agent`),{status:409,body:{active:!1,handled:!1,error:"No talk or lesson is running"}})}close(){this.session?.stop("daemon stopping"),this.floor.close(),this.narrator.close(),this.presence.close()}get live(){return this.session&&this.session.state!=="ended"?this.session:null}startLesson(e,t,n,s){if(this.live)return{status:409,body:{error:"A talk or lesson is already running",...this.view(this.live)}};let i=this.floorHeld();if(i)return i;let o=this.presence.lesson(e,t,n,this.speech,this.model,s),a=c=>this.log(`[teach] ${new Date().toISOString()} ${c}`);return o.on(c=>{if(c.type==="step"){let d=c.planMs===void 0?"":` (screen ${c.readMs} ms, plan ${c.planMs} ms)`;a(`${c.n}. ${c.action}${c.target?` "${c.target.slice(0,60)}"`:""}: ${c.say}${d}`)}else c.type==="acted"&&c.error?a(`action refused: ${c.error}`):c.type==="replanned"?a(`replanning: ${c.reason}`):c.type==="error"?a(`error: ${c.error}`):c.type==="end"&&a(`ended (${c.reason})`)}),this.session=o,o.run(),a(`${e} (${n}): ${t.slice(0,100)}`),{status:201,body:this.view(o)}}start(e){if(this.live)return{status:409,body:{error:"A talk or lesson is already running",...this.view(this.live)}};let t=this.floorHeld();if(t)return t;let n=Array.isArray(e.agents)?e.agents.map(String):[],s=String(e.topic??"").trim(),i=this.agents();if(n.length!==2||n[0]===n[1]||!s)return{status:400,body:{error:"Required: agents (two different ids) and topic"}};let o="talk",a=h=>{let f=this.intros.needsIntro(o,h);return i[h]?er(h,i,f,this.settings()):this.remote(h,f)},c=n.map(a),d=n.filter((h,f)=>!c[f]);if(d.length)return{status:404,body:{error:`Unknown agent: ${d.join(", ")}`}};let l=c,u=new so({topic:s,speakers:l,speech:this.speech,context:e.context?String(e.context):void 0,maxTurns:Math.max(2,Math.min(40,Number(e.maxTurns)||10)),listener:this.settings().listener,model:(h,f)=>this.model(f)});return u.on(h=>{h.type==="line"?(this.intros.spoke(o,h.agentId),this.log(`[talk] ${h.name}: ${h.text}`)):h.type==="gap"?this.log(`[talk] gap ${h.ms} ms`):h.type==="error"?this.log(`[talk] error: ${h.error}`):h.type==="end"&&this.log(`[talk] ended (${h.reason})`)}),this.session=u,u.run(),this.log(`[talk] ${l[0].name} and ${l[1].name} on "${s.slice(0,80)}"`),{status:201,body:this.view(u)}}floorHeld(){let e=this.floor.view();return e.held?{status:409,body:{error:`The floor is held by ${e.holder}`,floor:e}}:null}kind(e){return e instanceof ct?"lesson":"talk"}agentOf(e){return e instanceof ct?e.agentId:null}view(e){if(e instanceof ct)return{active:e.state!=="ended",kind:"lesson",id:e.id,state:e.state,step:e.step,saying:e.lastSay,agentId:e.agentId,mode:e.mode,goal:e.goal.slice(0,160),startedAt:e.startedAt};let t=e;return{active:e.state!=="ended",kind:"talk",id:e.id,state:e.state,startedAt:e.startedAt,transcript:e.transcript,gaps:e.gaps,topic:String(t.topic??"").slice(0,200),agents:t.speakerIds??[]}}};xn();Os();var g$="voice-narration",gl={calendar:"checking your calendar",email:"going through your email",messages:"reading your messages",files:"looking through your files",search:"searching for that",web:"looking it up online",code:"going through the code",git:"checking the repository",infrastructure:"checking the servers",writing:"writing that up",sending:"sending it",scheduling:"setting that up",data:"pulling the numbers together",waiting:"waiting on a slow response",other:"still on it"},p$={worthSaying:Pe("This step is worth interrupting the person to mention out loud.",{true:"It is slow, external, or a visible action with consequences \u2014 sending something, waiting on a service, a long search \u2014 so a person left in silence would wonder whether anything is happening.",false:"It is routine internal work: reading a file, a quick lookup, a check that takes a moment. Mentioning it is noise."}),doing:Tn(Object.fromEntries(Object.entries(gl).map(([r,e])=>[r,`The agent is ${e}.`])),"What kind of work is this step?")};function f$(r){return{tool:r.tool,detail:oN(r.detail,600),secondsWaiting:r.elapsedSeconds}}function m$(r,e=.6){let t=r.worthSaying.noul,s=r.doing.choice;return{say:t>=e?gl[s]??gl.other:null,category:s,worth:t}}function oN(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var v$=60*60*1e3,aN=5*60*1e3,cN=30*60*1e3,y$=16,w$=100,dN=24*v$,lN=2e3,uo=class{constructor(e){this.deps=e;this.now=e.now??Date.now}wakes=new Map;own=new Map;woken=new Map;held=new Map;now;handle(e){let t=[],n=this.deps.agents(),s=this.now(),i=this.deps.isLocal?this.deps.isLocal(e):!0;for(let[o,a]of Object.entries(n)){let c=Ih(a.subscriptions,"wake");if(c.length===0)continue;if(e.agentId===o){b$(this.own,o,e.rootId,s),c.some(h=>$h({...h,agents:void 0},e))&&t.push({agentId:o,eventId:e.id,woke:!1,reason:"own-event"});continue}let d=(a.subscriptions??[]).map((h,f)=>({s:h,index:f})).filter(({s:h})=>h.delivery==="wake"&&Sh(h,e,o)&&(i||(h.nodes?.includes(e.node)??!1)));if(d.length===0)continue;let{outcome:l,sub:u}=this.decide(o,e,d,s);if(t.push(l),!l.woke){this.deps.log(`[events] wake skipped for ${o}: ${l.reason} \u2014 ${En(e)} root=${e.rootId.slice(0,8)}`);continue}this.deps.log(`[events] waking ${o} \u2014 ${En(e)} root=${e.rootId.slice(0,8)}`),setImmediate(()=>this.run(o,e,u,0))}return t}pendingRetries(){return this.held.size}stop(){for(let e of this.held.values())clearTimeout(e);this.held.clear()}run(e,t,n,s){let i=o=>this.deps.log(`[events] wake of ${e} failed: ${o?.message??o}`);try{Promise.resolve(this.deps.dispatch(e,t,n)).then(o=>{let a=uN(o);a&&this.retry(e,t,n,s,a)},i)}catch(o){i(o)}}retry(e,t,n,s,i){let o=`${e}#${t.id}`,a=`${En(t)} root=${t.rootId.slice(0,8)}`;if(s>=y$){this.deps.log(`[events] wake of ${e} dropped after ${s} retries, still held: ${i} \u2014 ${a}`);return}if(!this.held.has(o)&&this.held.size>=w$){this.deps.log(`[events] wake of ${e} dropped, ${w$} held wakes already queued: ${i} \u2014 ${a}`);return}let c=Math.min(aN*2**s,cN);this.deps.log(`[events] wake of ${e} held: ${i} \u2014 retry ${s+1}/${y$} in ${Math.round(c/6e4)} min \u2014 ${a}`);let d=setTimeout(()=>{this.held.delete(o),this.run(e,t,n,s+1)},c);d.unref?.(),this.held.set(o,d)}decide(e,t,n,s){let i={agentId:e,eventId:t.id};if(k$(this.own,e,t.rootId,s))return{outcome:{...i,woke:!1,reason:"own-root"}};if(k$(this.woken,e,t.rootId,s))return{outcome:{...i,woke:!1,reason:"duplicate-root"}};for(let{s:o,index:a}of n){let c=`${e}#${a}`,d=(this.wakes.get(c)??[]).filter(l=>s-l<v$);if(d.length>=(o.maxPerHour??4)){this.wakes.set(c,d);continue}return d.push(s),this.wakes.set(c,d),b$(this.woken,e,t.rootId,s),{outcome:{...i,woke:!0},sub:o}}return{outcome:{...i,woke:!1,reason:"rate-limit"}}}attach(e){let t=e.subscribe(n=>{this.handle(n)});return()=>{t(),this.stop()}}};function b$(r,e,t,n){let s=r.get(e);s||(s=new Map,r.set(e,s)),s.delete(t),s.set(t,n),s.size>lN&&s.delete(s.keys().next().value)}function k$(r,e,t,n){let s=r.get(e)?.get(t);return s!==void 0&&n-s<dN}function uN(r){if(!r||typeof r!="object")return;let e=r.held;return typeof e=="string"&&e?e:void 0}function S$(r,e){let t=["[Event] A subscription of yours matched:",En(r),`Event: ${r.type} (kind ${r.kind}), emitted by ${r.agentId?`${r.agentId} on ${r.node}`:r.node}${r.ref?`, ref ${r.ref}`:""}.`,`Event id ${r.id}, root ${r.rootId}. Call agentx_events for the surrounding events.`];return e?.trim()?t.push(`When this event arrives: ${e.trim()}`):t.push("Act on it if it needs you; otherwise reply briefly that no action is needed."),t.join(`
|
|
1157
1157
|
`)}function $$(r){let e=(r||"").split(",").map(t=>t.trim()).filter(Boolean);return e.length?e:void 0}function I$(r){return{origin:r.get("origin")==="local"?"local":void 0,kinds:$$(r.get("kind")),skipTypes:$$(r.get("skip")),agent:r.get("agent")||void 0}}function T$(r,e,t){return!(r.origin==="local"&&e.node!==t||r.kinds&&!r.kinds.includes(e.kind)||r.skipTypes&&r.skipTypes.includes(e.type)||r.agent&&e.agentId!==r.agent)}function x$(r,e){let t=e.get("since")||void 0,n=I$(e),s=parseInt(e.get("limit")||"",10),i=r.nodeName,o=r.recent({since:t}).filter(c=>T$(n,c,i));return Number.isFinite(s)&&s>0&&(o=o.slice(-s)),!!t&&Number.isNaN(Date.parse(t))&&!r.hasRecent(t)?{events:o,gap:!0}:{events:o}}var pl="x-agentx-feed",fl=15e3;function A$(r,e,t,n,s={}){let i=I$(n);t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",[pl]:"1"}),t.write(`: feed ${r.nodeName}
|
|
1158
1158
|
|
|
1159
1159
|
`);let o=r.subscribe(d=>{if(T$(i,d,r.nodeName))try{t.write(`event: envelope
|
|
@@ -1262,7 +1262,7 @@ ${o.slice(0,300)}`,record:!0,taskId:`cron-fail:${s.replace(/\//g,":")}:${Date.no
|
|
|
1262
1262
|
${s}`});return}await this.notifyOwner(n,s,"watchers")},onClosed:(n,s)=>{n.kind==="delegation"&&n.taskKey.startsWith("dlg-")&&this.status?.board.waitEnded(n.taskKey,s),s==="done"&&this.requests&&_u(this.requests.store,this.watchers?.store.get(n.id)??n,Date.now())},raise:(n,s)=>{let i=this.config.requests;if(!this.requests||!i.enabled||!Ps(i).watchers||this.config.watchers.owner.channel)return!1;let o=Cu(this.requests.store,n,s,Date.now());return o.raised||o.opened},doneHint:(n,s)=>`curl -s -X POST http://127.0.0.1:${t}/watchers/${n.id}/done -H 'Content-Type: application/json' -d '{"evidence":${Cs(s)}}'`,log:this.log})}attachReach(e,t){let n=uw({db:e,ledger:t,settings:()=>({...Lp,...this.config.notifications.reach}),told:()=>({...Ta,...this.config.notifications.told}),channels:{has:s=>this.router.getChannelNames().includes(s),health:s=>this.router.channelHealth(s),all:()=>this.router.channelsHealth()},send:async(s,i,o,a)=>{if(!await this.router.sendOutbound({channel:s,chatId:i,text:`${a.title}
|
|
1263
1263
|
${o}`,priority:5,agentId:a.from??void 0,told:{passed:!0}}))throw new Error(`the ${s} channel returned no message ID`)},notice:(s,i,o)=>{this.tellOwner({...o??{},title:`${s} is down`,message:`Sends to ${s} are refused until it is back: ${i}.
|
|
1264
1264
|
If it does not come back by itself, run \`agentx daemon restart\` once fixed.`,from:"reach",key:`channel-down:${s}`,kind:"nag"},{soft:!0}).catch(a=>this.log(`[reach] down notice for ${s} failed: ${a?.message??a}`))},defaultChannel:()=>Or(this.config),isOwnerTurn:s=>{let i=s.channel.toLowerCase().split("@")[0];return Ou(this.config.requests,s.channel,s.sender,s.operator===!0)||s.person?.role==="owner"&&!Ms.has(i)},request:s=>{let i=this.requests?.store,o=i?.get(s);return!i||!o?null:{channel:o.channel,chatId:o.chatId,cards:i.links(s).filter(a=>a.kind==="card").map(a=>a.ref)}},cardDecidedAt:s=>{let i=bt(process.cwd(),s);return i?.status==="decided"&&i.decided_at?Date.parse(i.decided_at):null},idleSeconds:this.native.idle?()=>this.native.idle.seconds():void 0,focus:async()=>await this.native.focus?.active()??null,inCall:()=>this.calls?.inCall()??null,log:this.log});return this.reachTimer=setInterval(()=>{n.tick()},6e4),this.reachTimer.unref?.(),n}startBudgets(){this.seedBudgets(),B().on("task:completed",e=>{for(let t of Wh(e.agentId,e.costUsd,void 0,ha(e.agentId,e.chatId)))this.log(`[budget] ${t.title}: ${t.message}`),this.notifyOwner(t.title,t.message,"budget",t.kind==="cap"?5:4,{key:`budget:${t.kind}:${t.scope}:${t.month}:${t.capUsd}`}).catch(n=>this.log(`[budget] couldn't tell the owner (${n?.message??n})`))})}seedBudgets(){if(this.db)try{let e=Nh();Fh(ag(this.db,e),void 0,Hh(cg(this.db,e),ha))}catch(e){this.log(` Budgets: couldn't read this month's spend (${e?.message??e}); counting from now`)}}async notifyOwner(e,t,n,s=4,i={}){await this.tellOwner({title:e,message:t,from:n,priority:s,...i})}async tellOwner(e,t={}){let n=e.urgent&&!e.channel?this.reach?.firstStop()??null:null,s=e.channel??n?.channel??Or(this.config),i=e.chatId??n?.chatId??"default",o={key:e.key,requestId:e.requestId,kind:e.kind,urgent:e.urgent,from:e.from,textKey:!0},a=this.ownerGate,c;if(a?.isOwnerAddress(s,i)){let l=a.decide({channel:s,chatId:i,title:e.title,text:e.message},o);if(l.verdict!=="send")return this.log(`[told] ${l.verdict==="repeat"?"already told":"kept for the digest"}: ${e.title.slice(0,80)}`),l.verdict;c=l.rowId}let d=await cw({title:e.title,message:e.message,from:e.from,priority:e.priority??4,urgent:e.urgent,channel:s,chatId:i},async l=>{try{await this.router.sendOutbound({channel:l.channel??s,chatId:l.chatId??i,text:`${l.title}
|
|
1265
|
-
${l.message}`,priority:l.priority,agentId:e.from,told:{...o,passed:!0}})}catch(u){if(c!==void 0&&a?.outcome(c,"failed"),this.log(`[told] push "${e.title.slice(0,80)}" from ${e.from} failed: ${u?.message??u}`),!this.native.banner&&!t.soft)throw u}},{alert:t.localAlert===!1?!1:this.ownerAlert()});return d.held&&c!==void 0&&a?.outcome(c,"held"),d.held?"held":"sent"}ownerAlert(){let e=qt(qs(this.config.notifications.local),{native:this.config.native});return async(t,n)=>{e(t,n).catch(s=>this.log(`[told] banner or sound failed: ${s?.message??s}`))}}workflowCardResult(e){if(e.origin?.kind==="workflow"){this.workflowDispatcher?.resumeFromCard(e).catch(n=>this.log(`[workflows] card ${e.id}: resume failed: ${n?.message??n}`));return}if(e.origin?.kind!=="workflow-proposal"||!this.workflowStore)return;let t=this.workflowStore.get(e.origin.workflowId);t&&(e.status==="decided"&&e.verdict==="yes"?(this.workflowStore.save({...t,status:"active",state:"active"}),this.log(`[workflows] ${t.id} kept as a reusable workflow (card ${e.id})`)):this.log(`[workflows] ${t.id} not kept (card ${e.id} ${e.status==="decided"?"no":"expired"}); it stays switched off`))}workflowRequestEnded(e){let t=e.meta?.requestId,n=this.requests?.store;if(!t||!n)return;let s=Date.now();try{e.status==="completed"?n.close(t,"done",Tg(e),s):n.needsAttention(t,`Workflow run ${e.id} ${e.status==="canceled"?"was stopped":"did not finish"}: ${e.history.at(-1)?.note??e.status}`,s)&&n.markNotified(t,s)}catch(i){this.log(`[workflows] request ${t} after run ${e.id}: ${i?.message??i}`)}}runCheckin(e){let t=this.native.tasks;if(!t)return Promise.resolve(null);let n={root:process.cwd(),settings:this.config.approvals.checkin,cardSettings:this.config.approvals,source:t,...this.config.reminders.enabled?{claimsPath:Ii(process.cwd())}:{},hasAgent:s=>!!this.registry.getAgent(s),ask:async(s,i,o)=>{let a=await this.registry.execute({agentId:s,message:i,timeoutMinutes:this.config.approvals.checkin.composeTimeoutSeconds/60,context:{channel:"reminder",chatId:`checkin:${o.id}`,sender:"approvals"}});if(a.error)throw new Error(a.error);return a.content??""},notify:async(s,i)=>{await this.tellOwner({title:s,message:i,from:this.config.approvals.checkin.agent??"approvals"},{soft:!0})},log:this.log};return wv(n,e)}stopReminders;startReminders(){let e=this.config.notifications?.destination;this.stopReminders=kv({settings:this.config.reminders,root:process.cwd(),execute:(t,n,s,i)=>this.registry.execute(t,n,s,i),hasAgent:t=>!!this.registry.getAgent(t),send:t=>this.router.sendOutbound(t),fallbackDestination:e?{channel:e.channel,chatId:e.chatId,accountId:e.accountId}:void 0,isStopping:()=>this.shuttingDown,log:this.log,native:this.config.native})}scheduleMidnightHook(){let e=()=>{let t=new Date,n=new Date(t);n.setDate(n.getDate()+1),n.setHours(0,0,5,0);let s=n.getTime()-t.getTime();this.log(` Cost tracking: next run in ${Math.round(s/6e4)}min`),this.midnightTimer=setTimeout(async()=>{await this.runDailyCostReport(),e()},Math.max(s,6e4))};e()}async runDailyCostReport(){let e=new Date(Date.now()-864e5).toISOString().slice(0,10),t=this.registry.getTokenTracker();if(t.hasTokenCostsEntry(e)){this.log(` Cost tracking: ${e} already logged, skipping`);return}let n=t.generateDailyReport(e);if(!n||n.totalTasks===0){this.log(` Cost tracking: no usage for ${e}, skipping`);return}t.appendToTokenCosts(n),this.log(` Cost tracking: ${e} \u2014 ${n.totalTasks} tasks, $${n.totalCost.toFixed(4)} (top: ${n.topAgent} $${n.topCost.toFixed(4)})`)}async startChannels(){if(this.config.channels.telegram.enabled){let t=this.config.channels.telegram.accounts;if(Object.keys(t).length>0){let n=this.config.channels.telegram.policy,s=new xt(t,{policy:{allowFrom:n?.allowFrom}},this.log);this.router.addChannel(s);let i=n?.allowFrom?.length??0,o=Object.entries(t).filter(([,c])=>!c.allowFrom&&i===0).length;o>0?this.log(` Telegram: enabled \u2014 WARNING: ${o} account(s) have no allowFrom (global or per-account). All incoming messages will be DROPPED.`):this.log(` Telegram: enabled \u2014 global allowFrom entries: ${i}`);let a=Object.entries(t).filter(([,c])=>(c.allowFrom??n?.allowFrom??[]).includes(dr)).map(([c])=>c);a.length>0&&this.log(` Telegram: public \u2014 anyone can message ${a.join(", ")} (allowFrom contains "${dr}")`)}}let e=this.config.channels.email;if(e.enabled&&Object.keys(e.accounts).length>0){let{EmailAdapter:t}=await import("./adapter-
|
|
1265
|
+
${l.message}`,priority:l.priority,agentId:e.from,told:{...o,passed:!0}})}catch(u){if(c!==void 0&&a?.outcome(c,"failed"),this.log(`[told] push "${e.title.slice(0,80)}" from ${e.from} failed: ${u?.message??u}`),!this.native.banner&&!t.soft)throw u}},{alert:t.localAlert===!1?!1:this.ownerAlert()});return d.held&&c!==void 0&&a?.outcome(c,"held"),d.held?"held":"sent"}ownerAlert(){let e=qt(qs(this.config.notifications.local),{native:this.config.native});return async(t,n)=>{e(t,n).catch(s=>this.log(`[told] banner or sound failed: ${s?.message??s}`))}}workflowCardResult(e){if(e.origin?.kind==="workflow"){this.workflowDispatcher?.resumeFromCard(e).catch(n=>this.log(`[workflows] card ${e.id}: resume failed: ${n?.message??n}`));return}if(e.origin?.kind!=="workflow-proposal"||!this.workflowStore)return;let t=this.workflowStore.get(e.origin.workflowId);t&&(e.status==="decided"&&e.verdict==="yes"?(this.workflowStore.save({...t,status:"active",state:"active"}),this.log(`[workflows] ${t.id} kept as a reusable workflow (card ${e.id})`)):this.log(`[workflows] ${t.id} not kept (card ${e.id} ${e.status==="decided"?"no":"expired"}); it stays switched off`))}workflowRequestEnded(e){let t=e.meta?.requestId,n=this.requests?.store;if(!t||!n)return;let s=Date.now();try{e.status==="completed"?n.close(t,"done",Tg(e),s):n.needsAttention(t,`Workflow run ${e.id} ${e.status==="canceled"?"was stopped":"did not finish"}: ${e.history.at(-1)?.note??e.status}`,s)&&n.markNotified(t,s)}catch(i){this.log(`[workflows] request ${t} after run ${e.id}: ${i?.message??i}`)}}runCheckin(e){let t=this.native.tasks;if(!t)return Promise.resolve(null);let n={root:process.cwd(),settings:this.config.approvals.checkin,cardSettings:this.config.approvals,source:t,...this.config.reminders.enabled?{claimsPath:Ii(process.cwd())}:{},hasAgent:s=>!!this.registry.getAgent(s),ask:async(s,i,o)=>{let a=await this.registry.execute({agentId:s,message:i,timeoutMinutes:this.config.approvals.checkin.composeTimeoutSeconds/60,context:{channel:"reminder",chatId:`checkin:${o.id}`,sender:"approvals"}});if(a.error)throw new Error(a.error);return a.content??""},notify:async(s,i)=>{await this.tellOwner({title:s,message:i,from:this.config.approvals.checkin.agent??"approvals"},{soft:!0})},log:this.log};return wv(n,e)}stopReminders;startReminders(){let e=this.config.notifications?.destination;this.stopReminders=kv({settings:this.config.reminders,root:process.cwd(),execute:(t,n,s,i)=>this.registry.execute(t,n,s,i),hasAgent:t=>!!this.registry.getAgent(t),send:t=>this.router.sendOutbound(t),fallbackDestination:e?{channel:e.channel,chatId:e.chatId,accountId:e.accountId}:void 0,isStopping:()=>this.shuttingDown,log:this.log,native:this.config.native})}scheduleMidnightHook(){let e=()=>{let t=new Date,n=new Date(t);n.setDate(n.getDate()+1),n.setHours(0,0,5,0);let s=n.getTime()-t.getTime();this.log(` Cost tracking: next run in ${Math.round(s/6e4)}min`),this.midnightTimer=setTimeout(async()=>{await this.runDailyCostReport(),e()},Math.max(s,6e4))};e()}async runDailyCostReport(){let e=new Date(Date.now()-864e5).toISOString().slice(0,10),t=this.registry.getTokenTracker();if(t.hasTokenCostsEntry(e)){this.log(` Cost tracking: ${e} already logged, skipping`);return}let n=t.generateDailyReport(e);if(!n||n.totalTasks===0){this.log(` Cost tracking: no usage for ${e}, skipping`);return}t.appendToTokenCosts(n),this.log(` Cost tracking: ${e} \u2014 ${n.totalTasks} tasks, $${n.totalCost.toFixed(4)} (top: ${n.topAgent} $${n.topCost.toFixed(4)})`)}async startChannels(){if(this.config.channels.telegram.enabled){let t=this.config.channels.telegram.accounts;if(Object.keys(t).length>0){let n=this.config.channels.telegram.policy,s=new xt(t,{policy:{allowFrom:n?.allowFrom}},this.log);this.router.addChannel(s);let i=n?.allowFrom?.length??0,o=Object.entries(t).filter(([,c])=>!c.allowFrom&&i===0).length;o>0?this.log(` Telegram: enabled \u2014 WARNING: ${o} account(s) have no allowFrom (global or per-account). All incoming messages will be DROPPED.`):this.log(` Telegram: enabled \u2014 global allowFrom entries: ${i}`);let a=Object.entries(t).filter(([,c])=>(c.allowFrom??n?.allowFrom??[]).includes(dr)).map(([c])=>c);a.length>0&&this.log(` Telegram: public \u2014 anyone can message ${a.join(", ")} (allowFrom contains "${dr}")`)}}let e=this.config.channels.email;if(e.enabled&&Object.keys(e.accounts).length>0){let{EmailAdapter:t}=await import("./adapter-57X4HJEA.js"),n=new t({accounts:e.accounts,root:process.cwd(),agentName:s=>this.config.agents[s]?.name||s,onDraft:s=>{this.tellOwner({title:`Email reply to ${s.to_name||s.to} waits for you`,message:`${s.agent} wrote a reply to "${s.subject}". Read it and send it in Approvals, or run: agentx approvals approve email:${s.id}`,from:s.agent,kind:"notice",key:`email-draft:${s.id}`}).catch(i=>this.log(`[email] draft notice failed: ${i?.message??i}`))}},this.log);this.router.addChannel(n),await n.start();for(let[s,i]of Object.entries(e.accounts)){let o=i.allowFrom?.length?i.allowFrom.includes("*")?"anyone may write":`${i.allowFrom.length} allowFrom entries`:"WARNING: no allowFrom, all mail is DROPPED";this.log(` Email: ${s} <${i.address}> \u2192 ${i.agent}, replies ${i.send==="auto"?"sent at once":"held for approval"}; ${o}`)}}if(this.config.channels.whatsapp.enabled){let{setWhatsAppQR:t,setWhatsAppStatus:n}=await import("./whatsapp-state-LB3R32BK.js"),s=new gr({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes,throttle:{minMsBetweenCalls:this.config.channels.whatsapp.ingest?.throttle?.minMsBetweenCalls,maxCallsPerMinute:this.config.channels.whatsapp.ingest?.throttle?.maxCallsPerMinute},onQR:t,onStatus:n,onGiveUp:o=>{this.notifyOwner("WhatsApp stopped reconnecting",`${o}
|
|
1266
1266
|
Run \`agentx daemon restart\` once fixed.`,"whatsapp",4,{kind:"nag",key:"channel-down:whatsapp"}).catch(a=>this.log(`[whatsapp] give-up notification failed: ${a?.message??a}`))}},this.log);this.router.addChannel(s);let i=this.config.channels.whatsapp.allowFrom??[];i.length===0?this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes) \u2014 WARNING: no allowFrom. All incoming messages will be DROPPED.`):i.some(o=>o.trim()==="*")?this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes) \u2014 WARNING: allowFrom contains "*". Every chat on the paired account is answered.`):this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes) \u2014 allowFrom entries: ${i.length}`)}if(this.config.channels.gitlab?.enabled&&this.config.channels.gitlab.token){let t=new zt({webhookPort:this.config.channels.gitlab.webhookPort,webhookSecret:this.config.channels.gitlab.webhookSecret,host:this.config.channels.gitlab.host,token:this.config.channels.gitlab.token,routes:this.config.channels.gitlab.routes,agentMappings:this.config.channels.gitlab.agentMappings,knownAgentIds:Object.keys(this.config.agents),agentUsernamePrefixes:this.config.channels.gitlab.agentUsernamePrefixes},this.log,this.hooks);t.setStatusComments(()=>this.config.requestStatus.channels.some(n=>n.toLowerCase()==="gitlab")),this.mesh&&(t.setMesh(this.mesh),t.setEditCommentForwarder(this.forwardCommentEdit("gitlab")),t.setReactForwarder(async(n,s,i,o,a,c,d)=>{let l=this.mesh.directory().find(h=>h.peer===n&&h.healthy);if(!l){this.log(`[gitlab] react forward: peer "${n}" not found or unhealthy`);return}let u=`${l.peerUrl}/gitlab/react`;try{let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(l.peer)},body:JSON.stringify({project:s,noteableType:i,noteableIid:o,noteId:a,agentId:c,name:d})}),f=await h.text().catch(()=>"");this.log(`[gitlab] react forward -> ${u} : ${h.status} ${f.slice(0,200)}`)}catch(h){this.log(`[gitlab] react forward FAILED -> ${u} : ${h.message}`)}}),t.setSendNoteForwarder(async(n,s,i,o,a,c)=>{let d=this.mesh.directory().find(f=>f.peer===n&&f.healthy);if(!d)throw new Error(`peer "${n}" not found or unhealthy`);let l=`${d.peerUrl}/gitlab/send-note`,u=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(d.peer)},body:JSON.stringify({project:s,noteableType:i,noteableIid:o,agentId:a,text:c})}),h=await u.json().catch(()=>({}));if(this.log(`[gitlab] send-note forward -> ${l} : ${u.status} noteId=${h.noteId||"?"}`),!u.ok||h.ok===!1||!h.noteId)throw new Error(`GitLab answered ${h.status??u.status}: ${h.error||"no note ID returned"}`);return h.noteId}),t.setLogTimeForwarder(async(n,s,i,o,a,c)=>{let d=this.mesh.directory().find(y=>y.peer===n&&y.healthy);if(!d)throw new Error(`peer "${n}" not found or unhealthy`);let l=`${d.peerUrl}/gitlab/log-time`,u=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(d.peer)},body:JSON.stringify({project:s,noteableType:i,noteableIid:o,agentId:a,durationMs:c})}),h=await u.text().catch(()=>"");this.log(`[gitlab] log-time forward -> ${l} : ${u.status} ${h.slice(0,160)}`);let f={};try{f=JSON.parse(h)}catch{}if(!u.ok||f.ok===!1)throw new Error(`GitLab answered ${f.status??u.status}: ${f.error||h.slice(0,200)||"no response body"}`)})),t.setProjectRules(this.projectRules),this.gitlabReviewGate=this.buildReviewGate(t),t.onMergeRequestEvent(n=>{this.gitlabReviewGate?.onPullRequest(n)}),this.router.addChannel(t),this.log(` GitLab: enabled (${this.config.channels.gitlab.routes.length} project routes, webhook :${this.config.channels.gitlab.webhookPort})`)}if(this.config.channels.github?.enabled){let t=this.config.channels.github;this.github=new wr({token:t.token,tokenFile:t.tokenFile,appId:t.appId,clientId:t.clientId,privateKeyFile:t.privateKeyFile,webhookSecret:t.webhookSecret,routes:t.routes,agentMappings:t.agentMappings,issueActions:t.issueActions,pullRequestActions:t.pullRequestActions,ignoreOwnChanges:t.ignoreOwnChanges,debounceSeconds:t.debounceSeconds},this.log),this.mesh&&(this.github.setEditCommentForwarder(this.forwardCommentEdit("github")),this.github.setSendCommentForwarder(async(s,i,o,a,c)=>{let d=this.mesh.directory().find(u=>u.peer===s&&u.healthy);if(!d)return this.log(`[github] send-comment forward: peer "${s}" not found or unhealthy`),"";let l=`${d.peerUrl}/github/send-comment`;try{let u=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(d.peer)},body:JSON.stringify({repo:i,issueNumber:o,agentId:a,text:c})}),h=await u.json().catch(()=>({}));return this.log(`[github] send-comment forward -> ${l} : ${u.status} commentId=${h.commentId||"?"}`),h.commentId||""}catch(u){return this.log(`[github] send-comment forward FAILED -> ${l} : ${u.message}`),""}})),this.mesh&&this.github.setPeerPostingLogins(()=>this.mesh.directory().flatMap(s=>s.githubLogins)),this.github.setProjectRules(this.projectRules),this.reviewGate=this.buildReviewGate(this.github),this.mergePolicy=this.buildMergePolicy(this.github),this.github.onPullRequestEvent(s=>{this.reviewGate?.onPullRequest(s),this.mergePolicy?.onPullRequest(s)}),this.github.onPullRequestReviewEvent(s=>{this.mergePolicy?.onReview(s)});let n=new Date(Date.now()-864e5).toISOString();this.mergePolicy.recheck(Vt(process.cwd(),"decided").filter(s=>s.origin?.kind==="merge-policy"&&s.verdict==="yes"&&(s.decided_at??"")>=n).map(s=>({repo:s.origin.repo,pr:s.origin.pr}))),this.router.addChannel(this.github),this.log(` GitHub: enabled (${t.routes.length} repo routes)`)}if(this.config.channels.ntfy?.enabled){let t=this.config.channels.ntfy;if(!t.topic)this.log(" ntfy: enabled but channels.ntfy.topic is unset \u2014 skipping");else{let{NtfyAdapter:n}=await import("./ntfy-Q4YHFKWW.js"),s=new n({server:t.server,topic:t.topic,token:t.token,defaultPriority:t.defaultPriority,defaultTitle:t.defaultTitle},this.log);this.router.addChannel(s),await s.start(),this.log(` ntfy: enabled (${t.server})`)}}if(this.config.channels.push?.enabled){let t=this.config.channels.push;if(t.relayTo){let{PushRelayAdapter:n}=await import("./push-PRFZMCIK.js"),{pushOrigin:s,PushRosterSync:i,ROSTER_CHECK_MS:o,relayTokenProblem:a}=await import("./push-bridge-NR7SLHGX.js"),c=t.relayTo,d=s(this.config.node.name),l=a(c,this.config.mesh.peers,process.env.MESH_TOKEN);l&&this.log(` push: ${l}`);let u=new n(c,(y,g)=>this.postToPushHost(y,"/channel/send",g),this.log,d);this.router.addChannel(u),await u.start();let h=new Xs,f=new i({active:()=>h.activePhoneIds(),send:y=>this.postToPushHost(c,"/push/app",{op:"roster",origin:d,active:y}),log:this.log});this.pushRosterTimer=setInterval(()=>{f.tick()},o),this.pushRosterTimer.unref?.()}else if(!t.subject)this.log(" push: enabled but channels.push.subject is unset \u2014 skipping");else{let n=qo();if(!n)this.log(" push: enabled but the SQLite database is unavailable \u2014 skipping");else{let{PushAdapter:s,isRemoteDevice:i}=await import("./push-PRFZMCIK.js"),{peerOrigins:o}=await import("./push-bridge-NR7SLHGX.js"),{PushStore:a}=await import("./push-store-L5QHMSST.js"),{pushKeysPath:c,readPushKeys:d}=await import("./push-keys-2DTD7YNQ.js"),{default:l}=await import("web-push"),u=new Xs,h=c(t.keysFile),f=new s({store:new a(n),keys:()=>d(h),subject:t.subject,ttlSeconds:t.ttlSeconds,keepRecent:t.keepRecent,deviceActive:b=>i(b)?o(this.config.mesh.peers).has(b.slice(0,b.indexOf(":"))):u.isActive(b),sender:(b,$,k)=>l.sendNotification(b,$,k),log:this.log});this.router.addChannel(f),await f.start();let y=new a(n);this.pushHost={store:()=>y,publicKey:()=>d(h)?.publicKey??null,keepRecent:t.keepRecent,allowedHosts:t.allowedHosts};let{attachAnnouncePush:g}=await import("./push-announce-PM5FZJRW.js"),{PushPrefs:w}=await import("./push-prefs-YOJNTOJF.js");g({bus:B(),store:new a(n),prefs:new w(n),send:b=>f.send(b),log:this.log})}}}if(this.config.channels.webrtc?.enabled){let t=this.config.channels.webrtc;if(this.webrtc=new Tp(this.config.node.name,t.allowedCallers,this.log),this.mesh&&this.webrtc.setForwarder(async(n,s)=>{try{return await this.mesh.sendSignal(n,s)}catch(i){return this.log(`[webrtc] forward to "${n}" failed: ${i.message}`),!1}}),t.ringNotify.length>0){let n=t.callUrlBase||`http://${this.config.node.bind}`;this.webrtc.setRingHandler(async s=>{let i=Ip(s,n);for(let o of t.ringNotify)try{await this.router.sendOutbound({channel:o.channel,chatId:o.chatId,text:i,parseMode:"plain",...o.accountId?{accountId:o.accountId}:{}})}catch(a){this.log(`[webrtc] ring notify via ${o.channel}:${o.chatId} failed: ${a.message}`)}})}if(t.bot.enabled){let n=t.bot,s=[...t.stunServers.map(i=>({urls:i})),...t.turnServers];this.botManager=new xr({broker:this.webrtc,iceServers:s,whisperBackend:n.whisperBackend,whisperModel:n.whisperModel,whisperLanguage:n.whisperLanguage,mlxBinary:n.mlxBinary,maxCallMinutes:n.maxCallMinutes,log:this.log,onTranscript:async({invite:i,text:o,durationMs:a})=>{let c=n.transcriptChannel;if(!c)return;let d=`[${new Date().toLocaleTimeString()} \u2022 ${(a/1e3).toFixed(1)}s \u2022 ${i.target}]`;try{await this.router.sendOutbound({channel:c.channel,chatId:c.chatId,text:`${d}
|
|
1267
1267
|
${o}`,parseMode:"plain",...c.accountId?{accountId:c.accountId}:{}})}catch(l){this.log(`[bot-manager] transcript send via ${c.channel}:${c.chatId} failed: ${l.message}`)}}}),this.log(` WebRTC bot: enabled (whisper=${n.whisperBackend}, default-agent=${n.defaultAgentId||"(none)"}, transcript=${n.transcriptChannel?`${n.transcriptChannel.channel}:${n.transcriptChannel.chatId}`:"(none)"})`)}this.cameraWatch=this.createCameraWatch(),this.log(` WebRTC signaling: enabled (stun=${t.stunServers.length}, turn=${t.turnServers.length}, allowedCallers=${t.allowedCallers.length||"all"}, ringNotify=${t.ringNotify.length}, bot=${t.bot.enabled?"on":"off"}, camera-bot frames=${t.camera.bot.frameIntervalSeconds?`every ${t.camera.bot.frameIntervalSeconds}s`:"on demand"})`)}await this.bootWorkflowEngine(),this.registry.getSessionStore().setAdapterResolver(t=>this.router.getChannel(t)),await this.router.startAll(),this.delegations.recover().then(t=>{t&&this.log(`[delegation] ${t} delegation(s) lost in the restart were reported to their callers`)}).catch(t=>this.log(`[delegation] recovery failed: ${t?.message??t}`))}async bootWorkflowEngine(){let e=this.config.workflows;if(!e?.enabled){this.log(" Workflows: disabled (set workflows.enabled to turn the engine on)");return}let t=new Vh({baseDir:te(process.cwd(),e.dir)}),n=new Jh({baseDir:te(process.cwd(),e.dir),nodeId:this.config.node.id}),s={};for(let b of this.router.getChannelNames()){let $=this.router.getChannel(b);$&&(s[b]=$)}let i={execute:async b=>{let $=Date.now();try{let k=b.workflowRunId?`workflow:${b.workflowRunId}`:"workflow:adhoc",x,E=await this.registry.execute({agentId:b.agentId,message:b.message,workflowRunId:b.workflowRunId,timeoutMinutes:b.timeoutMinutes,autonomy:b.autonomy,context:{channel:"workflow",chatId:k,sender:"workflow"},onStart:A=>{x=A}});return{content:E.content??"",error:E.error,errorKind:E.errorKind,autonomyBlocks:E.autonomyBlocks,taskId:`wf-${b.workflowRunId??"na"}-${$.toString(36)}`,...x?{runTaskId:x}:{},durationMs:Date.now()-$}}catch(k){return{content:"",error:k.message}}}},o=this.mesh?{forwardTransition:async(b,$)=>{let k=this.mesh.directory().find(E=>E.peer===b&&E.healthy);if(!k){this.log(`[workflows] forward to "${b}" skipped \u2014 peer not found or unhealthy`);return}let x=`${k.peerUrl}/workflow/event`;try{let E=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(k.peer)},body:JSON.stringify({payload:$})});E.ok||this.log(`[workflows] forward ${x} -> ${E.status}`)}catch(E){this.log(`[workflows] forward ${x} failed: ${E.message}`)}},broadcastTrigger:async b=>{let $=this.mesh.directory().filter(x=>x.healthy);if($.length===0)return;let k=this.config.node.id;this.log(`[workflows/mesh] broadcasting trigger source="${b.trigger.source}" chat="${b.trigger.chat??"*"}" -> ${$.length} peer(s): ${$.map(x=>x.peer).join(", ")}`),await Promise.allSettled($.map(async x=>{let E=`${x.peerUrl}/workflow/event`;try{let A=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(x.peer)},body:JSON.stringify({kind:"trigger",fromPeer:k,payload:b}),signal:AbortSignal.timeout(5e3)});A.ok||this.log(`[workflows/mesh] broadcastTrigger ${x.peer} -> ${A.status}`)}catch(A){this.log(`[workflows/mesh] broadcastTrigger ${x.peer} failed: ${A.message}`)}}))},forwardChannelSend:async b=>{let $=this.mesh.directory().filter(T=>T.healthy&&T.channels?.includes(b.channel));if($.length===0)throw new Error(`no healthy mesh peer hosts channel "${b.channel}"`);let k=$[0],x=`${k.peerUrl}/channel/send`,E=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(k.peer)},body:JSON.stringify(b),signal:AbortSignal.timeout(15e3)});if(!E.ok){let T=await E.text().catch(()=>"");throw new Error(`peer ${k.peer} /channel/send -> ${E.status} ${T.slice(0,200)}`)}return{messageId:(await E.json().catch(()=>({}))).messageId??null}}}:void 0,{TimerService:a}=await import("./timers-KK7GF77Y.js"),c=new a({baseDir:e.dir?te(process.cwd(),e.dir):void 0,log:b=>this.log(b)}),d={notify:(b,$)=>this.notifyOwner($.meta?.title?`Workflow: ${$.meta.title}`.slice(0,120):"Workflow",b,$.meta?.startedBy??"workflow",3),ask:async(b,$,k)=>{let x=Me(process.cwd(),{...b,if_silent:"discard",raised_by:$.meta?.startedBy??t.get($.workflowId)?.ownerAgent??"workflow"},{settings:this.config.approvals,origin:{kind:"workflow",runId:$.id,nodeId:k}});if(!x.ok)throw new Error(x.error);return this.log(`[workflows] run ${$.id}: card ${x.card.id} for step "${k}"`),{cardId:x.card.id}}},l=new dg({store:t,runs:n,nodeId:this.config.node.id,channels:s,agents:i,forwarder:o,timers:c,events:this.events,log:b=>this.log(b),owner:d,followUp:()=>this.config.workflows.followUp,onRunEnded:async(b,$)=>{let{title:k,message:x}=Ig(b,$);await this.notifyOwner(k,x,b.meta?.startedBy??"workflow",b.status==="completed"?3:4),this.workflowRequestEnded(b)},onBlocked:async(b,$,k,x)=>{let{title:E,message:A}=xg(b,$,k,x);await this.notifyOwner(E,A,b.meta?.startedBy??"workflow",4);let T=b.meta?.requestId;T&&this.requests?.store.needsAttention(T,`Workflow step "${k}" is blocked: ${x}`,Date.now())&&this.requests.store.markNotified(T,Date.now())}});c.start();let u=lg(l);for(let[b,$]of Object.entries(u))$&&this.hooks.registerHandler(b,`workflows:${b}`,$,50);this.workflowDispatcher=l,this.workflowStore=t,this.workflowRuns=n,this.registry.setWorkflowRunStore(n);try{let b=n.moveTaskRuns();b&&this.log(` Workflows: moved ${b} task run(s) to their own folder`)}catch(b){this.log(` Workflows: moving task runs failed (non-fatal): ${b?.message||b}`)}try{let b=_g(n);b&&this.log(` Workflows: closed ${b} task run(s) cut off by the last stop`)}catch(b){this.log(` Workflows: closing cut-off task runs failed (non-fatal): ${b?.message||b}`)}let h=()=>{try{let b=n.pruneTaskRuns(this.config.workflows.required?.retentionDays??30);b&&this.log(` Workflows: removed ${b} task run(s) past workflows.required.retentionDays`)}catch(b){this.log(` Workflows: pruning task runs failed (non-fatal): ${b?.message||b}`)}};h(),this.taskRunPrune&&clearInterval(this.taskRunPrune),this.taskRunPrune=setInterval(h,6*60*60*1e3),this.taskRunPrune.unref?.(),this.webhooks.setWorkflowDispatcher(l),this.registry.setWorkflowAutoRunner(async({workflowId:b,agentId:$,channel:k,chatId:x,message:E,payload:A,follow:T})=>{let O=t.get(b);if(!O)throw new Error(`auto-run target workflow not found: ${b}`);let D=bg(O,{chatId:x,channel:k,message:typeof A.message=="string"?A.message:void 0,agentId:typeof A.agentId=="string"?A.agentId:void 0,senderId:typeof A.senderId=="string"?A.senderId:void 0,senderUsername:typeof A.senderUsername=="string"?A.senderUsername:void 0});if(D.missing.length>0)throw new Error(`inputSchema requires ${D.missing.join(", ")} \u2014 chatId+defaults filled [chatId: ${D.filledFrom.chatId.join(",")||"\u2014"} | defaults: ${D.filledFrom.defaults.join(",")||"\u2014"}]; auto-run skipped (operator can fill manually or extend the inputSchema).`);if(this.log(`[workflows] auto-run input resolution for ${b}: passthrough=[${D.filledFrom.passthrough.join(",")}] chatId=[${D.filledFrom.chatId.join(",")}] defaults=[${D.filledFrom.defaults.join(",")}]`),T){let p=await l.startRun({workflowId:b,inputs:{...D.inputs,requestedBy:$,channel:k,chatId:x},meta:{title:E.replace(/\s+/g," ").trim().slice(0,80)||O.title,tags:[`agent:${$}`],startedBy:$}});if(!p.run)throw new Error(p.error??`could not start ${b}`);return{runId:p.run.id,title:O.title}}let P={backend:"manual",id:x||`auto-${Date.now().toString(36)}`},j=`auto:${b}:${x}:${Date.now()}`;return{runId:(await l.dispatchWorkflow({workflowId:b,entityRef:P,event:{id:j,payload:D.inputs},trigger:{source:"manual"}})).run?.id}});let{cronTimers:f,hookSubscribers:y}=mg({store:t,dispatcher:l,hooks:this.hooks,log:b=>this.log(b),forgeUsernames:b=>[...wt(this.config.channels.gitlab?.agentMappings,"gitlabUsernames",b),...wt(this.config.channels.github?.agentMappings,"githubUsernames",b)]});this.workflowPolls=new yg({store:t,dispatcher:l,log:b=>this.log(b)});let g=this.workflowPolls.start(),w=t.list().length;this.log(` Workflows: enabled (${w} definition${w===1?"":"s"} loaded from ${e.dir}, editor=${e.editor}, cron=${f}, hook=${y}, poll=${g})`);try{let{detectConflicts:b}=await import("./conflict-detector-KS7OSS45.js"),$=b(t.list(),this.config);if($.length>0){this.log(` Workflows: ${$.length} dispatch conflict(s) detected`);for(let k of $)this.log(` [${k.severity}] ${k.workflowId}: ${k.summary}`),this.log(` \u2192 ${k.suggestion}`)}}catch(b){this.log(` Workflows: conflict-detector failed: ${b.message}`)}}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=LL(async(s,i)=>{if(La(s.headers)==="foreign"&&_f(s.method)){this.log(`[auth] \u2717 refused ${s.method} ${(s.url||"").split("?")[0]} from a page on another origin (${s.headers.origin||s.headers["sec-fetch-site"]})`),this.json(i,403,{error:"Forbidden: request from a page on another origin"});return}if(this.shuttingDown&&Ff(s.method,(s.url||"/").split("?")[0])){i.setHeader("Retry-After","30"),this.json(i,503,{error:"daemon is restarting; retry shortly"});return}if(s.method==="OPTIONS"){i.writeHead(204),i.end();return}await this.handleHttp(s,i)}),this.httpServer.on("error",s=>{s.code==="EADDRINUSE"?(this.log(` ERROR: Port ${n} is already in use. Retrying in 5s...`),setTimeout(()=>{this.httpServer?.close(),this.httpServer?.listen(n,e||"0.0.0.0")},5e3)):this.log(` HTTP error: ${s.message}`)}),this.httpServer.listen(n,e||"0.0.0.0",()=>{this.log(` HTTP API: http://${e||"0.0.0.0"}:${n}`);let s=_v(this.config,i=>!!this.registry.getAgent(i));for(let i of s)this.log(` [mesh-relay] \u26A0 inbox "${i.name}" names agent "${i.agent}", which is not on this node \u2014 it will refuse messages`)}),this.attachSweep=setInterval(()=>{try{let s=ge();s.sweep(),s.prune()}catch{}},1e3),this.attachSweep.unref?.()}async sendToAgent(e,t,n){if(!n.agentId||!n.text){this.json(t,400,{error:"Required: agentId, text"});return}let s=String(n.agentId),i=String(n.text),o=n.senderAgentId?String(n.senderAgentId):void 0,a=Pn(n),c=n.async===!1,d=z$(o,s,i),l=c?null:this.sendAgentDedupe.get(d);if(l){this.log(`[send/agent] duplicate of ${String(l.taskId)} from ${o||"?"} \u2192 ${s}; not sent again`),this.json(t,202,Q$(l));return}let u=mn(fn(e,n),this.registry);if(!c&&this.config.mesh.delegation.callbackSends){let k=u?this.delegations.replyTarget({agentId:u.agentId,chatId:String(u.context.chatId??"")},s):null;if(k){this.delegations.relayReply(k,i);let x=H$(k.id,s);this.sendAgentDedupe.put(d,x),this.json(t,202,x);return}}let h=this.delegationGate(e,n,{callee:s,message:i,...a?{calleeContext:{taskType:a}}:{}},{send:!0});if(!("track"in h)){let k=mo(h);k.status===202&&this.sendAgentDedupe.put(d,k.body),this.json(t,k.status,k.body);return}let f=u?on(u.context)+1:0;if(this.registry.getAgent(s)){let k=h.track,x=(A,T)=>{let O={channel:"a2a",sender:o?`agent:${o}`:"agent",chatId:o||"a2a",...a?{taskType:a}:{},...f?{sendDepth:f}:{},...Wt(n)?{home:Wt(n)}:{}},D=this.recordInboundDispatch(s,{...O,chatId:`a2a:${o||"?"}:${s}`,...k.root?{initiator:k.root}:{}},i,o);return this.registry.execute({agentId:s,message:i,context:O,intentRef:D,onStart:A?k.onStart:T,...A?{}:{slotWaitMs:K$}}).finally(()=>{A&&k.end()})};if(c){try{let A=await x(!0);this.json(t,A.error?500:200,{ok:!A.error,content:A.content,error:A.error})}catch(A){this.json(t,500,{error:A.message})}return}let E=wl({agent:s,log:A=>this.log(A),run:async A=>{let T=await x(!1,O=>this.log(`[send/agent] ${A} \u2192 ${s} started as run ${O}`));return{ok:!T.error,...T.error?{detail:T.error.slice(0,200)}:{}}}});this.sendAgentDedupe.put(d,E),this.json(t,202,E);return}if(!this.mesh){this.json(t,400,{error:`Unknown agent "${s}" \u2014 mesh disabled, no remote lookup possible`});return}let g=this.mesh,w=g.directory(),b=w.find(k=>k.healthy&&k.skills.some(x=>x.id===s));if(!b){let k=[...Object.keys(this.config.agents),...w.flatMap(x=>x.skills.map(E=>E.id))];this.json(t,404,{error:`Unknown agent "${s}"`,known:k});return}if(c){try{let k=await g.sendTask(b.peer,i,s,{senderAgentId:o,taskType:a,...f?{sendDepth:f}:{}});this.json(t,200,{ok:!0,messageId:k,peer:b.peer})}catch(k){this.json(t,500,{error:k.message,peer:b.peer})}return}let $=wl({agent:s,peer:b.peer,log:k=>this.log(k),run:async()=>(await g.sendTask(b.peer,i,s,{senderAgentId:o,taskType:a,...f?{sendDepth:f}:{}}),{ok:!0})});this.sendAgentDedupe.put(d,$),this.json(t,202,$)}delegationGate(e,t,n,s={}){let i=fn(e,t),o=mn(i,this.registry),a=yl(n.callee,o,this.registry,this.syncWaits);if(a)return{refused:a};if(!n.peer&&this.registry.getAgent(n.callee)){let l=j$(n.callee,i,o,this.registry,this.syncWaits);if(l)return{refused:l}}let c=s.callback===!1?null:this.startCallback(t,o,n,{send:s.send===!0});if(c)return{accepted:c};let d;return{track:{...o?{root:gt(o.context,o.agentId)}:{},onStart:l=>{d=l,o?.taskId&&this.syncWaits.begin(o.taskId,l,ml(o,this.syncWaits))},end:()=>{d&&this.syncWaits.end(d)}}}}startCallback(e,t,n,s={}){let i=e.async===!0?!0:e.async===!1?!1:void 0,o=!this.delegations.shouldCallback(t,i);if(o&&!(s.send&&i!==!1&&this.config.mesh.delegation.callbackSends&&this.delegations.shouldCallbackSend(t))||!t)return null;let a=n.peer;if(!a&&!this.registry.getAgent(n.callee)){let l=this.mesh?.findAgentPeer(n.callee);if(!l?.healthy)return null;a=l.peer}let c={};if(!a){let l=this.recordInboundDispatch(n.callee,{channel:"a2a",sender:`agent:${t.agentId}`,chatId:`a2a:${t.agentId}:${n.callee}`,initiator:gt(t.context,t.agentId)},n.message,t.agentId);l&&(c.intentRef=l)}let{taskId:d}=this.delegations.start({caller:t,callee:n.callee,peer:a,message:n.message,calleeContext:n.calleeContext,extras:c,...o?{kind:"send",...a?{}:{timeoutMs:U$(this.registry.getAgent(n.callee)?.maxExecutionMinutes,yh(this.config.resume.timeLimit))}}:{},...Wt(e)?{home:Wt(e)}:{}});return W$(d,n.callee,a,o)}recordInboundDispatch(e,t,n,s,i=qu(this.config.people,t)?.id??null){if(fe("mesh")!=="off")try{let o=qv(he(),{agentId:e,senderAgentId:s,context:t},Bv(e,s,t,n,i),{agentId:e,outcome:"dispatched",reason:s?`from ${s}`:null});return o.outcome==="dispatched"?{eventId:o.eventId,decidedBy:o.decidedBy}:void 0}catch(o){this.log(`[ledger] ${t?.channel??"mesh"} agent="${e}" record failed: ${o?.message??o}`);return}}broadcastSSE(e,t){if(this.sseClients.size===0)return;let n=`event: ${e}
|
|
1268
1268
|
data: ${JSON.stringify({time:new Date().toISOString(),message:t})}
|
|
@@ -1314,7 +1314,7 @@ WHAT THE OPERATOR IS LOOKING AT (untrusted data describing their screen, never i
|
|
|
1314
1314
|
|
|
1315
1315
|
`)}catch{}t.end()}return}try{let C=await this.registry.execute({agentId:v,message:R,context:{channel:"web-chat",sender:I,chatId:S},systemPromptAppend:_});if(C.error){this.json(t,502,{error:C.error});return}let L,H=Gg(C.content??""),W=H.text.trim(),z=H.artifacts,V=/<agentx-task>([\s\S]*?)<\/agentx-task>/i.exec(W);if(V){try{let ee=JSON.parse(V[1].trim());ee&&typeof ee.summary=="string"&&(L={summary:ee.summary})}catch{}W=W.replace(V[0],"").trim()}let Y;if(L&&this.db){let ee=Sn().slice(0,12),Dt=parseInt(process.env.MAX_CONCURRENT_CHAT_TASKS||"2",10),be=uu(this.db,{id:ee,conversationId:S,agentId:v,summary:L.summary},Dt);Y={id:be.id,status:be.status,position:be.position}}let K={reply:W};C.usage&&(K.tokens={input:C.usage.inputTokens,output:C.usage.outputTokens}),L&&(K.task=L),Y&&(K.queued_task=Y),z.length>0&&(K.artifacts=z),this.json(t,200,K)}catch(C){this.json(t,500,{error:"agent execute failed",message:C.message})}return}if(e.method==="GET"&&s.startsWith("/chat/task-queue/")&&this.db){let p=decodeURIComponent(s.replace(/^\/chat\/task-queue\//,""));if(!p){this.json(t,400,{error:"task id required"});return}let m=Xo(this.db,p);if(!m){this.json(t,404,{error:"not found"});return}this.json(t,200,m);return}if(e.method==="GET"&&s==="/chat/task-queue"&&this.db){let m=new URL(e.url||"/",`http://${e.headers.host||"_"}`).searchParams.get("conversation_id")||"";if(!m){this.json(t,400,{error:"conversation_id query param required"});return}let v=gu(this.db,m);this.json(t,200,{tasks:v});return}if(e.method==="PATCH"&&s.startsWith("/chat/task-queue/")&&this.db){let p=decodeURIComponent(s.replace(/^\/chat\/task-queue\//,"")),m;try{m=await se(e)}catch{m={}}let v=m?.status==="error"?"error":"done";hu(this.db,p,v);let S=Xo(this.db,p);this.json(t,S?200:404,S??{error:"not found"});return}let l=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/workspace\/(.+)$/);if(l){let p=process.env.AGENTX_CHAT_SECRET||process.env.TELEGRAM_BOT_API_SECRET;if(p){let C=e.headers.authorization||"";if((C.startsWith("Bearer ")?C.slice(7).trim():"")!==p){this.json(t,401,{error:"unauthorized"});return}}let m=l[1],v=decodeURIComponent(l[2]),S=this.registry.getAgent(m);if(!S){this.json(t,404,{error:`agent "${m}" not found`});return}let I=te(process.cwd(),S.workspace),R=te(I,v);if(!R.startsWith(I+GL)&&R!==I){this.json(t,403,{error:"path traversal denied"});return}if(!kn(R)){this.json(t,404,{error:"file not found"});return}let _=UL(R).toLowerCase(),N={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".csv":"text/csv",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".html":"text/html",".mp4":"video/mp4",".webm":"video/webm"}[_]??"application/octet-stream";t.writeHead(200,{"Content-Type":N,"Cache-Control":"private, max-age=3600"}),jL(R).pipe(t);return}if(e.method==="POST"&&s.startsWith("/api/workflows/signal/")&&this.workflowDispatcher){let p=decodeURIComponent(s.replace(/^\/api\/workflows\/signal\//,""));if(!p){this.json(t,400,{error:"signal name required"});return}let m;try{m=await se(e)}catch(S){this.json(t,400,{error:"invalid JSON body",message:S.message});return}let v=this.workflowDispatcher.emitSignal({name:p,scope:m?.scope,workflowId:m?.workflowId,payload:m?.payload});this.json(t,200,{ok:!0,emission:v});return}if(e.method==="GET"&&s==="/processes"){let{renderProcessesPage:p}=await import("./processes-EWARF6ZW.js");t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(p({}));return}if(e.method==="GET"&&s==="/call"){this.serveCallPage(t);return}let u=e.method==="POST"&&s.match(fS);if(u){await mS(e,t,u[1],{cron:this.cron,workflows:this.workflowDispatcher&&this.workflowStore?{get:p=>this.workflowStore.get(p),dispatchWorkflow:p=>this.workflowDispatcher.dispatchWorkflow(p)}:void 0,meshTokens:Ys(this.config),log:p=>this.log(p)});return}let h=e.method==="POST"&&s.match(/^\/webhook\/n8n\/([A-Za-z0-9._:-]{1,64})$/);if(h){if(!this.checkMeshAuth(e,t,s))return;let p;try{p=await se(e)}catch{p={}}let m=h[1];try{await this.hooks.execute("on:n8n",{topic:m,payload:p,source:"n8n"}),this.json(t,200,{ok:!0,topic:m});return}catch(v){this.json(t,500,{error:"hook failed",message:String(v?.message||v)});return}}let f=e.method==="POST"?GI[s]:void 0;if(f){await HI(f,e,t,{config:()=>this.config.trackers,dispatcher:this.trackers(),log:p=>this.log(p)});return}if(e.method==="POST"&&s===i0){await o0(e,t,{config:()=>this.config.whatsappTriage,service:()=>this.waTriage,log:p=>this.log(p)});return}if(e.method==="POST"&&s.startsWith("/webhook/")){if(this.github&&e.headers["x-github-event"]){let p=await new Promise(v=>{let S="";e.on("data",I=>S+=I.toString()),e.on("end",()=>v(S)),e.on("error",()=>v(""))}),m=fy(p,String(e.headers["content-type"]||""));this.log(`[github] webhook body keys: ${Object.keys(m).slice(0,5).join(", ")} | repo: ${m.repository?.full_name||"MISSING"}`),t.writeHead(202,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channel:"github",status:"accepted"})),this.github.handleWebhook(e.headers,m,p).catch(v=>this.log(`[github] webhook handler error: ${v.message}`));return}await Rn(()=>this.webhooks.handle(e,t,s));return}let y=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks\/([^/]+)\/stream$/);if(y){this.handleTaskStream(e,t,y[1],y[2]);return}let g=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks$/);if(g){let p=Math.max(1,Math.min(500,parseInt(n.searchParams.get("limit")||"50",10)||50));this.json(t,200,this.registry.listTaskHistory(g[1],p));return}let w=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks\/([^/]+)$/);if(w){let p=this.registry.getTaskRecord(w[1],w[2]);if(!p){this.json(t,404,{error:"not found"});return}this.json(t,200,p);return}let b=e.method==="GET"&&s.match(/^\/agents\/([^/]+)$/);if(b){let p=b[1],m=this.config.agents[p];if(!m){this.json(t,404,{error:"agent not found"});return}let v=dh(m);this.json(t,200,{id:p,name:m.name,tier:m.tier,model:m.model??null,workspace:m.workspace,mentions:m.mentions??[],maxConcurrent:m.maxConcurrent,maxExecutionMinutes:m.maxExecutionMinutes,permission:v,persistentProcess:!!m.persistentProcess,toolUseRequired:m.toolUseRequired??[]});return}if(e.method==="GET"&&s==="/analytics/mesh"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=(m,v)=>{let S=parseInt(n.searchParams.get(m)||"",10);return Number.isFinite(S)?S:v};this.json(t,200,Lv(this.db,{days:p("days",30),tzOffsetMinutes:p("tzOffset",0),limit:p("limit",60)}));return}if(e.method==="GET"&&s==="/analytics/thread"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=n.searchParams.get("agent"),m=n.searchParams.get("channel"),v=n.searchParams.get("chat");if(!p||!m||!v){this.json(t,400,{error:"agent, channel and chat query params required"});return}let S=parseInt(n.searchParams.get("limit")||"120",10);this.json(t,200,{runs:Fv(this.db,{agent:p,channel:m,chatId:v,limit:S})});return}if(e.method==="GET"&&s==="/analytics/job"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=n.searchParams.get("kind"),m=n.searchParams.get("key");if(p!=="cron"&&p!=="workflow"||!m){this.json(t,400,{error:"kind=cron|workflow and key query params required"});return}let v=parseInt(n.searchParams.get("limit")||"120",10);this.json(t,200,{runs:Wv(this.db,{kind:p,key:m,limit:v})});return}if(e.method==="GET"&&s==="/analytics/day"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=n.searchParams.get("day")||"";if(!/^\d{4}-\d{2}-\d{2}$/.test(p)){this.json(t,400,{error:"day=YYYY-MM-DD query param required"});return}let m=parseInt(n.searchParams.get("tzOffset")||"0",10),v=parseInt(n.searchParams.get("limit")||"40",10);this.json(t,200,Gv(this.db,{day:p,tzOffsetMinutes:Number.isFinite(m)?m:0,limit:v}));return}if(e.method==="GET"&&s==="/analytics/conversation"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=n.searchParams.get("agent"),m=n.searchParams.get("channel"),v=n.searchParams.get("chat");if(!p||!m||!v){this.json(t,400,{error:"agent, channel and chat query params required"});return}let S=parseInt(n.searchParams.get("tzOffset")||"0",10),I=Hv(this.db,{agent:p,channel:m,chatId:v,tzOffsetMinutes:Number.isFinite(S)?S:0});this.json(t,I.found?200:404,I);return}let $=e.method==="GET"&&s.match(/^\/analytics\/run\/([^/]+)$/);if($){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=Uv(this.db,$[1]);this.json(t,p.found?200:404,p);return}if(e.method==="GET"&&s==="/traces"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=v=>{let S=n.searchParams.get(v);if(S===null||S==="")return;let I=parseInt(S,10);return Number.isFinite(I)?I:void 0},m=Fs(this.db,{agentId:n.searchParams.get("agentId")||void 0,channel:n.searchParams.get("channel")||void 0,chatId:n.searchParams.get("chatId")||void 0,workflowRunId:n.searchParams.get("workflowRunId")||void 0,status:n.searchParams.get("status")||void 0,since:p("since"),until:p("until"),limit:p("limit")});this.json(t,200,{traces:m});return}let x=e.method==="GET"&&s.match(/^\/traces\/([^/]+)$/);if(x){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let p=js(this.db,x[1]);if(!p){this.json(t,404,{error:"not found"});return}this.json(t,200,p);return}let E=e.method==="POST"&&s.match(/^\/agents\/([^/]+)\/selftest$/);if(E){let p=E[1],v=(await U(e).catch(()=>({}))).message,S=typeof v=="string"&&v.trim()?v:"Reply with the single word: OK",I=Date.now(),R=await this.registry.execute({agentId:p,message:S,freshSession:!0,context:{channel:"selftest",chatId:`selftest:${I.toString(36)}`,sender:"selftest"}},()=>{}),_=Date.now()-I;if(R.error){this.json(t,200,{ok:!1,agentId:p,error:R.error,errorKind:R.errorKind,durationMs:_,usage:R.usage,tokens:R.usage?{in:R.usage.inputTokens,out:R.usage.outputTokens}:void 0});return}this.json(t,200,{ok:!0,agentId:p,content:R.content,durationMs:_,usage:R.usage,tokens:R.usage?{in:R.usage.inputTokens,out:R.usage.outputTokens}:void 0,billedModel:R.billedModel});return}if(e.method==="GET"&&s==="/api/processes"){if(!this.processRegistry){this.json(t,503,{error:"process registry not enabled"});return}this.json(t,200,{processes:this.processRegistry.list()});return}if(e.method==="GET"&&s==="/api/actions/builtin"){this.json(t,200,{actions:ga()});return}let A=e.method==="POST"&&s.match(/^\/api\/actions\/builtin\/([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*)$/);if(A){let p=A[1];if(!Kh(p)){this.json(t,404,{error:`unknown built-in: ${p}`});return}try{let m=await se(e),v=await zh(p,m);this.json(t,200,{output:v})}catch(m){m?.name==="ZodError"?this.json(t,400,{error:m.message}):this.json(t,500,{error:m?.message||String(m)})}return}if(XI(s)){if(e.method==="GET"&&s==="/api/review-gate/reviews"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(VI(this.reviewLedger,n.searchParams)));return}if(e.method==="POST"&&s==="/api/review-gate/replay"){let p=KI(await se(e).catch(()=>({}))),m="error"in p?void 0:p.forge==="gitlab"?this.gitlabReviewGate:this.reviewGate;if("error"in p||!m){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"error"in p?p.error:`the ${p.forge==="gitlab"?"GitLab":"GitHub"} channel is off on this node`}));return}t.writeHead(200,{"Content-Type":"application/x-ndjson"});let v=setInterval(()=>t.write(`
|
|
1316
1316
|
`),3e4);try{await JI(m,p.repo,p.prs,S=>t.write(JSON.stringify(S)+`
|
|
1317
|
-
`))}finally{clearInterval(v),t.end()}return}t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"method not allowed"}));return}if(Xw(s)){let p=e.method==="POST"?await se(e).catch(()=>({})):{},m=this.callerProof(e),v=typeof p.from=="string"?p.from:void 0,S=null;if(m.taskId){let M=this.registry.runningTaskOwner(m.taskId);S=M?{agentId:M.agentId,channel:M.channel}:null}else v&&m.channel&&m.chatId&&(S=this.provenTurn(v,m)?{agentId:v,channel:m.channel}:null);let I=e.headers.authorization,R=qw({proofGiven:!!(m.taskId||m.channel&&m.chatId),provenTurn:S,via:p.via,tokenPeer:Vr(Array.isArray(I)?I[0]:I,this.config.mesh.peers??[],process.env.MESH_TOKEN)}),_=await Vw(e.method||"GET",s,n.searchParams,p,{service:this.signals,selfNode:this.config.node.name||this.config.node.id||"local",sender:R,peers:()=>(this.mesh?.directory()??[]).filter(M=>M.healthy).map(M=>M.peer),forward:(M,N,C,L,H)=>this.signalsForward(M,N,C,L,H),reporter:this.stopAllReporter});this.json(t,_.status,_.body);return}if(e.method==="POST"&&s==="/api/processes/kill"){if(!this.processRegistry){this.json(t,503,{error:"process registry not enabled"});return}try{let p=await se(e),{agentId:m,channel:v,chatId:S,reason:I}=p;if(!m||!v||!S){this.json(t,400,{error:"agentId, channel, chatId required"});return}await this.processRegistry.kill({agentId:m,channel:v,chatId:S},I||"operator"),this.json(t,200,{killed:{agentId:m,channel:v,chatId:S}})}catch(p){this.json(t,500,{error:p?.message||String(p)})}return}let T=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/intent-path$/);if(T){let p=n.searchParams.get("channel")||"",m=n.searchParams.get("chatId")||"";if(!p||!m){this.json(t,400,{error:"channel and chatId are required"});return}let v=decodeURIComponent(T[1]);this.json(t,200,{path:this.registry.runningIntentPath(v,p,m)??null,graphWeight:this.config.graph?.retrievalWeights?.graph??.6});return}let O=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/landscape$/);if(O){let p=decodeURIComponent(O[1]);if(!this.config.agents[p]){this.json(t,404,{error:`unknown agent "${p}"`});return}this.json(t,200,{landscape:this.landscape.getForAgent(p)??""});return}let D=e.method==="POST"&&s.match(/^\/channels\/([^/]+)\/switch$/);if(D){let p=await se(e).catch(()=>({}));if(typeof p.on!="boolean"){this.json(t,400,{error:"send { on: true | false, reason? }"});return}let m=decodeURIComponent(D[1]);try{this.router.setChannelSwitch(m,p.on,typeof p.reason=="string"&&p.reason.trim()?p.reason.trim().slice(0,200):void 0)}catch(v){this.json(t,404,{error:v.message});return}this.log(`[reach] channel ${m} switched ${p.on?"on":"off"}`),this.json(t,200,{ok:!0,channel:m,...this.router.channelHealth(m)});return}let P=e.method==="POST"&&s.match(/^\/crons\/([^/]+)\/enabled$/);if(P){let p=await se(e).catch(()=>({}));if(typeof p.enabled!="boolean"){this.json(t,400,{error:"send { enabled: true | false }"});return}let{setCronEnabled:m}=await import("./set-enabled-5X7MWSZH.js"),v=await m(decodeURIComponent(P[1]),p.enabled,{configPath:this.configPath});if(!v.ok){this.json(t,v.status,{error:v.error});return}v.changed&&await this.reload(),this.json(t,200,v);return}let j=e.method==="POST"&&s.match(/^\/api\/tasks\/([^/]+)\/cancel$/);if(j){let p=decodeURIComponent(j[1]);try{let m=await se(e).catch(()=>({})),v=typeof m?.reason=="string"?m.reason:"operator",S=this.registry.cancelRunningTask(p,v);if(!S){this.json(t,404,{error:`no running task with id ${p}`});return}this.json(t,200,{ok:!0,cancelled:{taskId:p,...S,reason:v}})}catch(m){this.json(t,500,{error:m?.message||String(m)})}return}let F=e.method==="POST"&&s.match(/^\/api\/tasks\/([^/]+)\/followup$/);if(F){let p=decodeURIComponent(F[1]);try{let m=await se(e),v=typeof m?.message=="string"?m.message.trim():"";if(!v){this.json(t,400,{error:"message required"});return}let S=m?.replace===!0,I=typeof m?.sender=="string"&&m.sender.trim()?m.sender.trim():"operator",R=this.registry.queueFollowUp(p,v,I,{replace:S});if(R){this.json(t,200,{ok:!0,taskId:p,...R});return}let _=typeof m?.agent=="string"?m.agent:"";if(!_){this.json(t,404,{error:`no running task with id ${p}`});return}let M=await this.registry.continueFinishedTask(_,p,v,I,{model:N=>this.cron.list().find(C=>`cron:${C.id}`===N)?.model});if(!M.ok){this.json(t,M.status,{error:M.error});return}this.json(t,200,{...M,resumed:!0,fromTaskId:p})}catch(m){this.json(t,500,{error:m?.message||String(m)})}return}if(e.method==="POST"&&(s==="/v1/chat/completions"||s.match(/^\/llm\/[^/]+\/v1\/chat\/completions$/))){await this.handleOpenAICompat(e,t,s);return}if(this.business&&s.startsWith("/business")&&await this.business.handleHttp(`${e.method} ${s}`,e,t))return;if(dS.has(s)){if(!this.checkMeshAuth(e,t,s))return;let p=e.method==="POST"?await U(e).catch(()=>({})):{},m=lS(e.method||"GET",s,p,{scheduler:this.idleRestart,inflight:()=>this.inflightCounts(),running:()=>this.runningSummaries(),policy:this.config.shutdown?.restart,service:()=>this.restartService(),pid:process.pid,cwd:process.cwd(),configPath:this.configPath});if(e.method==="POST"&&m.status<300){let v=this.idleRestart.state();this.log(` Restart when idle: ${s.endsWith("/cancel")?"cancelled":`${v.state} (requested by ${v.requestedBy}, until ${v.state==="deferred"?v.until:v.deadline}, then ${v.onTimeout})`}`)}this.json(t,m.status,m.body);return}if(uS.has(s)){if(!this.checkMeshAuth(e,t,s))return;let p=hS(e.method||"GET",s),m=p.body.lifted;m&&this.log(` Claude plan holds lifted by operator: ${m.map(v=>v.window).join(", ")||"none active"}`),this.json(t,p.status,p.body);return}switch(`${e.method} ${s}`){case"GET /health":{let p=this.projectRules.health();this.json(t,200,{status:"ok",node:this.config.node,version:tt.version,commit:tt.commit,startedAt:tt.startedAt,uptime:process.uptime(),pid:process.pid,...Av(this.bootLog),build:Fy(),agents:this.registry.list(),crons:this.cron.list().map(m=>({id:m.id,enabled:m.enabled,nextRun:m.nextRun})),mesh:this.mesh?.directory()||[],deferredMesh:this.router.getDeferredMeshCounts(),projectRules:{count:p.count,errors:p.errors},usage:this.resolveTodayUsage(),inflight:this.inflightCounts(),restart:(({state:m,requestedAt:v,deadline:S})=>({state:m,requestedAt:v,deadline:S}))(this.idleRestart.state()),voice:{canMeasure:Ua()!=null,allowUnmeasured:this.config.voice.allowUnmeasured},gitlab:this.gitlabHealth(),channels:Object.fromEntries(Object.entries(this.router.channelsHealth()).map(([m,v])=>[m,v.up?v:{...v,...this.reach?.watch.downSince(m)?{since:new Date(this.reach.watch.downSince(m)).toISOString()}:{}}]))});break}case"GET /usage":this.json(t,200,this.registry.getUsage(7));break;case"GET /agents":this.json(t,200,this.registry.list().map(p=>({...p,skillCount:lm(p.workspace).skills.length,color:we(p.id,this.config.agents[p.id]).color,palette:(({id:m,colors:v})=>({id:m,colors:v}))(ht(this.config.agents[p.id]?.presence,this.config.voice.palette))})));break;case"GET /api/admin/projects":{let{computeProjectsAggregate:p}=await import("./projects-api-E337EQNV.js");if(!this.workflowStore){this.json(t,503,{error:"workflow store not initialized"});break}let m=p({config:this.config,rules:this.projectRules,workflowStore:this.workflowStore,cwd:process.cwd()});this.json(t,200,m);break}case"POST /api/admin/projects/workflows/link":case"POST /api/admin/projects/workflows/unlink":{let p=await U(e),m=e.url?.endsWith("/link"),v=String(p.projectKey||"").trim(),S=String(p.workflowId||"").trim();if(!v||!S){this.json(t,400,{error:"projectKey + workflowId required"});break}if(!/^[a-z0-9][a-z0-9_-]*$/.test(S)){this.json(t,400,{error:"invalid workflow id"});break}let{setWorkflowProject:I}=await import("./projects-mutate-S5MY7V3V.js");try{let R=I({workflowId:S,projectKey:m?v:null,cwd:process.cwd()});this.json(t,200,R)}catch(R){this.json(t,400,{error:R?.message||"mutation failed"})}break}case"POST /api/admin/projects/header":case"POST /api/admin/projects/clauses":case"POST /api/admin/projects/contacts/link":case"POST /api/admin/projects/contacts/unlink":case"POST /api/admin/projects/create":case"POST /api/admin/projects/delete":{let p=await U(e),m=String(p.projectKey||"").trim();if(!m){this.json(t,400,{error:"projectKey required"});break}if(!/^[a-zA-Z0-9._-]+(\/[a-zA-Z0-9._-]+)*$/.test(m)){this.json(t,400,{error:"invalid projectKey"});break}let v=await import("./projects-mutate-S5MY7V3V.js");try{let S=process.cwd(),I=e.url||"";if(I.endsWith("/header"))this.json(t,200,v.patchProjectHeader({projectKey:m,cwd:S,patch:p.patch||{}}));else if(I.endsWith("/clauses"))this.json(t,200,v.setProjectClauses({projectKey:m,cwd:S,gitlab:p.gitlab,github:p.github}));else if(I.endsWith("/contacts/link")){let R=String(p.contactId||"").trim();if(!R){this.json(t,400,{error:"contactId required"});break}this.json(t,200,v.linkContact({projectKey:m,cwd:S,contactId:R}))}else if(I.endsWith("/contacts/unlink")){let R=String(p.contactId||"").trim();if(!R){this.json(t,400,{error:"contactId required"});break}this.json(t,200,v.unlinkContact({projectKey:m,cwd:S,contactId:R}))}else if(I.endsWith("/create")){let R=String(p.kind||"other");this.json(t,200,v.createProjectRule({projectKey:m,cwd:S,kind:R,displayName:typeof p.displayName=="string"?p.displayName:void 0,homeUrl:typeof p.homeUrl=="string"?p.homeUrl:void 0,runbook:typeof p.runbook=="string"?p.runbook:void 0,agent:typeof p.agent=="string"?p.agent:void 0}))}else I.endsWith("/delete")&&this.json(t,200,v.deleteProjectRule({projectKey:m,cwd:S}))}catch(S){this.json(t,400,{error:S?.message||"mutation failed"})}break}case"GET /whatsapp/state":{let{getWhatsAppState:p}=await import("./whatsapp-state-LB3R32BK.js");this.json(t,200,p());break}case"GET /whatsapp/qr.svg":{let{getWhatsAppState:p}=await import("./whatsapp-state-LB3R32BK.js"),m=p();if(!m.qr){t.writeHead(204,{"Cache-Control":"no-store"}),t.end();break}try{let v=await import("qrcode"),I=await(v.default||v).toString(m.qr,{type:"svg",errorCorrectionLevel:"L",margin:1,color:{dark:"#000",light:"#fff"}});t.writeHead(200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"no-store"}),t.end(I)}catch(v){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("qrcode package not installed or failed: "+(v?.message||"unknown"))}break}case"GET /whatsapp/chats":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{chats:p.listChats()});break}case"GET /whatsapp/contacts":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{contacts:p.listContacts()});break}case"POST /whatsapp/ingest":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}let m=await U(e),v=this.config.channels.whatsapp.ingest;if(!v.enabled&&!m.force){this.json(t,400,{error:'channels.whatsapp.ingest.enabled is false. Set it to true in agentx.json or pass {"force": true}.'});break}let S=typeof m.agent=="string"&&m.agent||this.config.channels.whatsapp.defaultAgent||this.config.node.defaultAgent;if(!S){this.json(t,400,{error:"No agent to own the entries. Pass {agent: '...'} or set channels.whatsapp.defaultAgent."});break}let I=!!m.dryRun,{runSweep:R}=await import("./ingest-whatsapp-4POCTRTP.js"),_=this.registry.getWikiHub().getAgentWiki(S),M=v;if(typeof m.onlyJid=="string"){let C=m.onlyJid,L=C.endsWith("@g.us"),H=m.forceMode==="metadata-only"||m.forceMode==="messages"?m.forceMode:void 0;M={...v,enabled:!0,mode:H??v.mode,allowContacts:L||m.onlyKind==="group"?[]:[C],allowGroups:L||m.onlyKind==="group"?[C]:[],denyContacts:[],denyGroups:[]}}let N=await R({source:p,store:_,config:M,agentId:S,dryRun:I});this.json(t,200,N);break}case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /crons/health":this.json(t,200,this.cron.health());break;case"GET /crons/runs":{let p=n.searchParams.get("date")||new Date().toISOString().slice(0,10),m=n.searchParams.get("timezone")||"UTC",v=n.searchParams.get("jobId")||void 0,S=await My({date:p,timezone:m,jobId:v});this.json(t,200,{date:p,timezone:m,runs:S});break}case"GET /routines":this.json(t,200,{routines:await this.routines()});break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"GET /debug":{let{getDebugState:p,getDebugLogs:m}=await import("./debug-FTAGG7MN.js");this.json(t,200,{...p(),recentLogs:m(50)});break}case"POST /debug/on":{let{setDebug:p}=await import("./debug-FTAGG7MN.js"),m=n.searchParams.get("categories")?.split(",")||["all"];p(!0,m),this.log(`Debug enabled: ${m.join(", ")}`),this.json(t,200,{enabled:!0,categories:m});break}case"POST /debug/off":{let{setDebug:p}=await import("./debug-FTAGG7MN.js");p(!1),this.log("Debug disabled"),this.json(t,200,{enabled:!1});break}case"POST /gitlab/react":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,noteId:I,agentId:R}=p,_=typeof p.name=="string"&&p.name?p.name:"eyes",M=this.resolveGitlabTokenForAgent(R),N=M.token,C=this.config.channels.gitlab?.host;if(this.log(`[gitlab/react] agent="${R}" project="${m}" source=${M.source} host=${C||"MISSING"}`),!N||!C){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:R,source:M.source,hasGlobalToken:!!this.config.channels.gitlab?.token,hasHost:!!C}});break}let L=encodeURIComponent(m),H=v==="issue"?`${C}/api/v4/projects/${L}/issues/${S}/notes/${I}/award_emoji`:`${C}/api/v4/projects/${L}/merge_requests/${S}/notes/${I}/award_emoji`;try{let W=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":N},body:JSON.stringify({name:_})}),z=await W.text().catch(()=>"");this.log(`[gitlab/react] "${_}" -> POST ${H} : ${W.status} ${z.slice(0,120)}`),this.json(t,200,{ok:W.ok,status:W.status,gitlabResponse:z.slice(0,200)})}catch(W){this.log(`[gitlab/react] FETCH ERROR: ${W.message}`),this.json(t,500,{error:W.message})}break}case"POST /gitlab/send-note":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,agentId:I,text:R}=p,_=this.resolveGitlabTokenForAgent(I),M=_.token,N=this.config.channels.gitlab?.host;if(!M||!N){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:I,source:_.source,hasToken:!!M,hasHost:!!N}});break}this.log(`[gitlab/send-note] agent="${I}" source=${_.source}`);let C=encodeURIComponent(m),L=v==="issue"?`${N}/api/v4/projects/${C}/issues/${S}/notes`:`${N}/api/v4/projects/${C}/merge_requests/${S}/notes`;try{let H=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":M},body:JSON.stringify({body:ie(String(R??""),I||wa)})}),W=await H.text().catch(()=>""),z="";try{z=String(JSON.parse(W).id||"")}catch{}this.log(`[gitlab/send-note] agent="${I}" -> POST ${L} : ${H.status} noteId=${z||"?"}`),this.json(t,200,{ok:H.ok,status:H.status,noteId:z,...H.ok?{}:{error:Hn(W)}})}catch(H){this.log(`[gitlab/send-note] FETCH ERROR: ${H.message}`),this.json(t,500,{error:H.message})}break}case"POST /gitlab/log-time":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,agentId:I,durationMs:R}=p,_=this.resolveGitlabTokenForAgent(I),M=_.token,N=this.config.channels.gitlab?.host;if(!M||!N){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:I,source:_.source}});break}let C=Math.max(60,Math.round(Number(R)/1e3)),L=Math.floor(C/3600),H=Math.ceil(C%3600/60),W=L>0?`${L}h${H>0?` ${H}m`:""}`:`${H}m`,z=encodeURIComponent(m),V=`${N}/api/v4/projects/${z}/${v==="merge_request"?"merge_requests":"issues"}/${S}/add_spent_time`;try{let Y=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":M},body:JSON.stringify({duration:W})});this.log(`[gitlab/log-time] agent="${I}" duration=${W} -> POST ${V} : ${Y.status}`);let K=Y.ok?void 0:Hn(await Y.text().catch(()=>""));this.json(t,200,{ok:Y.ok,status:Y.status,duration:W,...K?{error:K}:{}})}catch(Y){this.log(`[gitlab/log-time] FETCH ERROR: ${Y.message}`),this.json(t,500,{error:Y.message})}break}case"POST /channel/edit-comment":{let{channel:p,chatId:m,commentId:v,agentId:S,text:I}=await U(e),R=p==="gitlab"||p==="github"?this.router.getChannel(p):void 0;if(!R?.editComment){this.json(t,404,{error:"no such channel on this node"});break}let _=await R.editComment(String(m??""),String(v??""),String(I??""),S,!0);this.json(t,200,{ok:_});break}case"POST /github/send-comment":{let p=await U(e),{repo:m,issueNumber:v,agentId:S,text:I}=p,R=this.config.channels.github,M=(R?.agentMappings||[]).find(L=>L.agentId===S),N;if(M?.tokenFile)try{N=$s(M.tokenFile,"utf-8").trim().split(`
|
|
1317
|
+
`))}finally{clearInterval(v),t.end()}return}t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"method not allowed"}));return}if(Xw(s)){let p=e.method==="POST"?await se(e).catch(()=>({})):{},m=this.callerProof(e),v=typeof p.from=="string"?p.from:void 0,S=null;if(m.taskId){let M=this.registry.runningTaskOwner(m.taskId);S=M?{agentId:M.agentId,channel:M.channel}:null}else v&&m.channel&&m.chatId&&(S=this.provenTurn(v,m)?{agentId:v,channel:m.channel}:null);let I=e.headers.authorization,R=qw({proofGiven:!!(m.taskId||m.channel&&m.chatId),provenTurn:S,via:p.via,tokenPeer:Vr(Array.isArray(I)?I[0]:I,this.config.mesh.peers??[],process.env.MESH_TOKEN)}),_=await Vw(e.method||"GET",s,n.searchParams,p,{service:this.signals,selfNode:this.config.node.name||this.config.node.id||"local",sender:R,peers:()=>(this.mesh?.directory()??[]).filter(M=>M.healthy).map(M=>M.peer),forward:(M,N,C,L,H)=>this.signalsForward(M,N,C,L,H),reporter:this.stopAllReporter});this.json(t,_.status,_.body);return}if(e.method==="POST"&&s==="/api/processes/kill"){if(!this.processRegistry){this.json(t,503,{error:"process registry not enabled"});return}try{let p=await se(e),{agentId:m,channel:v,chatId:S,reason:I}=p;if(!m||!v||!S){this.json(t,400,{error:"agentId, channel, chatId required"});return}await this.processRegistry.kill({agentId:m,channel:v,chatId:S},I||"operator"),this.json(t,200,{killed:{agentId:m,channel:v,chatId:S}})}catch(p){this.json(t,500,{error:p?.message||String(p)})}return}let T=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/intent-path$/);if(T){let p=n.searchParams.get("channel")||"",m=n.searchParams.get("chatId")||"";if(!p||!m){this.json(t,400,{error:"channel and chatId are required"});return}let v=decodeURIComponent(T[1]);this.json(t,200,{path:this.registry.runningIntentPath(v,p,m)??null,graphWeight:this.config.graph?.retrievalWeights?.graph??.6});return}let O=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/landscape$/);if(O){let p=decodeURIComponent(O[1]);if(!this.config.agents[p]){this.json(t,404,{error:`unknown agent "${p}"`});return}this.json(t,200,{landscape:this.landscape.getForAgent(p)??""});return}let D=e.method==="POST"&&s.match(/^\/channels\/([^/]+)\/switch$/);if(D){let p=await se(e).catch(()=>({}));if(typeof p.on!="boolean"){this.json(t,400,{error:"send { on: true | false, reason? }"});return}let m=decodeURIComponent(D[1]);try{this.router.setChannelSwitch(m,p.on,typeof p.reason=="string"&&p.reason.trim()?p.reason.trim().slice(0,200):void 0)}catch(v){this.json(t,404,{error:v.message});return}this.log(`[reach] channel ${m} switched ${p.on?"on":"off"}`),this.json(t,200,{ok:!0,channel:m,...this.router.channelHealth(m)});return}let P=e.method==="POST"&&s.match(/^\/crons\/([^/]+)\/enabled$/);if(P){let p=await se(e).catch(()=>({}));if(typeof p.enabled!="boolean"){this.json(t,400,{error:"send { enabled: true | false }"});return}let{setCronEnabled:m}=await import("./set-enabled-API6VRUP.js"),v=await m(decodeURIComponent(P[1]),p.enabled,{configPath:this.configPath});if(!v.ok){this.json(t,v.status,{error:v.error});return}v.changed&&await this.reload(),this.json(t,200,v);return}let j=e.method==="POST"&&s.match(/^\/api\/tasks\/([^/]+)\/cancel$/);if(j){let p=decodeURIComponent(j[1]);try{let m=await se(e).catch(()=>({})),v=typeof m?.reason=="string"?m.reason:"operator",S=this.registry.cancelRunningTask(p,v);if(!S){this.json(t,404,{error:`no running task with id ${p}`});return}this.json(t,200,{ok:!0,cancelled:{taskId:p,...S,reason:v}})}catch(m){this.json(t,500,{error:m?.message||String(m)})}return}let F=e.method==="POST"&&s.match(/^\/api\/tasks\/([^/]+)\/followup$/);if(F){let p=decodeURIComponent(F[1]);try{let m=await se(e),v=typeof m?.message=="string"?m.message.trim():"";if(!v){this.json(t,400,{error:"message required"});return}let S=m?.replace===!0,I=typeof m?.sender=="string"&&m.sender.trim()?m.sender.trim():"operator",R=this.registry.queueFollowUp(p,v,I,{replace:S});if(R){this.json(t,200,{ok:!0,taskId:p,...R});return}let _=typeof m?.agent=="string"?m.agent:"";if(!_){this.json(t,404,{error:`no running task with id ${p}`});return}let M=await this.registry.continueFinishedTask(_,p,v,I,{model:N=>this.cron.list().find(C=>`cron:${C.id}`===N)?.model});if(!M.ok){this.json(t,M.status,{error:M.error});return}this.json(t,200,{...M,resumed:!0,fromTaskId:p})}catch(m){this.json(t,500,{error:m?.message||String(m)})}return}if(e.method==="POST"&&(s==="/v1/chat/completions"||s.match(/^\/llm\/[^/]+\/v1\/chat\/completions$/))){await this.handleOpenAICompat(e,t,s);return}if(this.business&&s.startsWith("/business")&&await this.business.handleHttp(`${e.method} ${s}`,e,t))return;if(dS.has(s)){if(!this.checkMeshAuth(e,t,s))return;let p=e.method==="POST"?await U(e).catch(()=>({})):{},m=lS(e.method||"GET",s,p,{scheduler:this.idleRestart,inflight:()=>this.inflightCounts(),running:()=>this.runningSummaries(),policy:this.config.shutdown?.restart,service:()=>this.restartService(),pid:process.pid,cwd:process.cwd(),configPath:this.configPath});if(e.method==="POST"&&m.status<300){let v=this.idleRestart.state();this.log(` Restart when idle: ${s.endsWith("/cancel")?"cancelled":`${v.state} (requested by ${v.requestedBy}, until ${v.state==="deferred"?v.until:v.deadline}, then ${v.onTimeout})`}`)}this.json(t,m.status,m.body);return}if(uS.has(s)){if(!this.checkMeshAuth(e,t,s))return;let p=hS(e.method||"GET",s),m=p.body.lifted;m&&this.log(` Claude plan holds lifted by operator: ${m.map(v=>v.window).join(", ")||"none active"}`),this.json(t,p.status,p.body);return}switch(`${e.method} ${s}`){case"GET /health":{let p=this.projectRules.health();this.json(t,200,{status:"ok",node:this.config.node,version:tt.version,commit:tt.commit,startedAt:tt.startedAt,uptime:process.uptime(),pid:process.pid,...Av(this.bootLog),build:Fy(),agents:this.registry.list(),crons:this.cron.list().map(m=>({id:m.id,enabled:m.enabled,nextRun:m.nextRun})),mesh:this.mesh?.directory()||[],deferredMesh:this.router.getDeferredMeshCounts(),projectRules:{count:p.count,errors:p.errors},usage:this.resolveTodayUsage(),inflight:this.inflightCounts(),restart:(({state:m,requestedAt:v,deadline:S})=>({state:m,requestedAt:v,deadline:S}))(this.idleRestart.state()),voice:{canMeasure:Ua()!=null,allowUnmeasured:this.config.voice.allowUnmeasured},gitlab:this.gitlabHealth(),channels:Object.fromEntries(Object.entries(this.router.channelsHealth()).map(([m,v])=>[m,v.up?v:{...v,...this.reach?.watch.downSince(m)?{since:new Date(this.reach.watch.downSince(m)).toISOString()}:{}}]))});break}case"GET /usage":this.json(t,200,this.registry.getUsage(7));break;case"GET /agents":this.json(t,200,this.registry.list().map(p=>({...p,skillCount:lm(p.workspace).skills.length,color:we(p.id,this.config.agents[p.id]).color,palette:(({id:m,colors:v})=>({id:m,colors:v}))(ht(this.config.agents[p.id]?.presence,this.config.voice.palette))})));break;case"GET /api/admin/projects":{let{computeProjectsAggregate:p}=await import("./projects-api-E337EQNV.js");if(!this.workflowStore){this.json(t,503,{error:"workflow store not initialized"});break}let m=p({config:this.config,rules:this.projectRules,workflowStore:this.workflowStore,cwd:process.cwd()});this.json(t,200,m);break}case"POST /api/admin/projects/workflows/link":case"POST /api/admin/projects/workflows/unlink":{let p=await U(e),m=e.url?.endsWith("/link"),v=String(p.projectKey||"").trim(),S=String(p.workflowId||"").trim();if(!v||!S){this.json(t,400,{error:"projectKey + workflowId required"});break}if(!/^[a-z0-9][a-z0-9_-]*$/.test(S)){this.json(t,400,{error:"invalid workflow id"});break}let{setWorkflowProject:I}=await import("./projects-mutate-S5MY7V3V.js");try{let R=I({workflowId:S,projectKey:m?v:null,cwd:process.cwd()});this.json(t,200,R)}catch(R){this.json(t,400,{error:R?.message||"mutation failed"})}break}case"POST /api/admin/projects/header":case"POST /api/admin/projects/clauses":case"POST /api/admin/projects/contacts/link":case"POST /api/admin/projects/contacts/unlink":case"POST /api/admin/projects/create":case"POST /api/admin/projects/delete":{let p=await U(e),m=String(p.projectKey||"").trim();if(!m){this.json(t,400,{error:"projectKey required"});break}if(!/^[a-zA-Z0-9._-]+(\/[a-zA-Z0-9._-]+)*$/.test(m)){this.json(t,400,{error:"invalid projectKey"});break}let v=await import("./projects-mutate-S5MY7V3V.js");try{let S=process.cwd(),I=e.url||"";if(I.endsWith("/header"))this.json(t,200,v.patchProjectHeader({projectKey:m,cwd:S,patch:p.patch||{}}));else if(I.endsWith("/clauses"))this.json(t,200,v.setProjectClauses({projectKey:m,cwd:S,gitlab:p.gitlab,github:p.github}));else if(I.endsWith("/contacts/link")){let R=String(p.contactId||"").trim();if(!R){this.json(t,400,{error:"contactId required"});break}this.json(t,200,v.linkContact({projectKey:m,cwd:S,contactId:R}))}else if(I.endsWith("/contacts/unlink")){let R=String(p.contactId||"").trim();if(!R){this.json(t,400,{error:"contactId required"});break}this.json(t,200,v.unlinkContact({projectKey:m,cwd:S,contactId:R}))}else if(I.endsWith("/create")){let R=String(p.kind||"other");this.json(t,200,v.createProjectRule({projectKey:m,cwd:S,kind:R,displayName:typeof p.displayName=="string"?p.displayName:void 0,homeUrl:typeof p.homeUrl=="string"?p.homeUrl:void 0,runbook:typeof p.runbook=="string"?p.runbook:void 0,agent:typeof p.agent=="string"?p.agent:void 0}))}else I.endsWith("/delete")&&this.json(t,200,v.deleteProjectRule({projectKey:m,cwd:S}))}catch(S){this.json(t,400,{error:S?.message||"mutation failed"})}break}case"GET /whatsapp/state":{let{getWhatsAppState:p}=await import("./whatsapp-state-LB3R32BK.js");this.json(t,200,p());break}case"GET /whatsapp/qr.svg":{let{getWhatsAppState:p}=await import("./whatsapp-state-LB3R32BK.js"),m=p();if(!m.qr){t.writeHead(204,{"Cache-Control":"no-store"}),t.end();break}try{let v=await import("qrcode"),I=await(v.default||v).toString(m.qr,{type:"svg",errorCorrectionLevel:"L",margin:1,color:{dark:"#000",light:"#fff"}});t.writeHead(200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"no-store"}),t.end(I)}catch(v){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("qrcode package not installed or failed: "+(v?.message||"unknown"))}break}case"GET /whatsapp/chats":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{chats:p.listChats()});break}case"GET /whatsapp/contacts":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{contacts:p.listContacts()});break}case"POST /whatsapp/ingest":{let p=this.router.getChannel("whatsapp");if(!p){this.json(t,503,{error:"WhatsApp channel not enabled"});break}let m=await U(e),v=this.config.channels.whatsapp.ingest;if(!v.enabled&&!m.force){this.json(t,400,{error:'channels.whatsapp.ingest.enabled is false. Set it to true in agentx.json or pass {"force": true}.'});break}let S=typeof m.agent=="string"&&m.agent||this.config.channels.whatsapp.defaultAgent||this.config.node.defaultAgent;if(!S){this.json(t,400,{error:"No agent to own the entries. Pass {agent: '...'} or set channels.whatsapp.defaultAgent."});break}let I=!!m.dryRun,{runSweep:R}=await import("./ingest-whatsapp-4POCTRTP.js"),_=this.registry.getWikiHub().getAgentWiki(S),M=v;if(typeof m.onlyJid=="string"){let C=m.onlyJid,L=C.endsWith("@g.us"),H=m.forceMode==="metadata-only"||m.forceMode==="messages"?m.forceMode:void 0;M={...v,enabled:!0,mode:H??v.mode,allowContacts:L||m.onlyKind==="group"?[]:[C],allowGroups:L||m.onlyKind==="group"?[C]:[],denyContacts:[],denyGroups:[]}}let N=await R({source:p,store:_,config:M,agentId:S,dryRun:I});this.json(t,200,N);break}case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /crons/health":this.json(t,200,this.cron.health());break;case"GET /crons/runs":{let p=n.searchParams.get("date")||new Date().toISOString().slice(0,10),m=n.searchParams.get("timezone")||"UTC",v=n.searchParams.get("jobId")||void 0,S=await My({date:p,timezone:m,jobId:v});this.json(t,200,{date:p,timezone:m,runs:S});break}case"GET /routines":this.json(t,200,{routines:await this.routines()});break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"GET /debug":{let{getDebugState:p,getDebugLogs:m}=await import("./debug-FTAGG7MN.js");this.json(t,200,{...p(),recentLogs:m(50)});break}case"POST /debug/on":{let{setDebug:p}=await import("./debug-FTAGG7MN.js"),m=n.searchParams.get("categories")?.split(",")||["all"];p(!0,m),this.log(`Debug enabled: ${m.join(", ")}`),this.json(t,200,{enabled:!0,categories:m});break}case"POST /debug/off":{let{setDebug:p}=await import("./debug-FTAGG7MN.js");p(!1),this.log("Debug disabled"),this.json(t,200,{enabled:!1});break}case"POST /gitlab/react":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,noteId:I,agentId:R}=p,_=typeof p.name=="string"&&p.name?p.name:"eyes",M=this.resolveGitlabTokenForAgent(R),N=M.token,C=this.config.channels.gitlab?.host;if(this.log(`[gitlab/react] agent="${R}" project="${m}" source=${M.source} host=${C||"MISSING"}`),!N||!C){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:R,source:M.source,hasGlobalToken:!!this.config.channels.gitlab?.token,hasHost:!!C}});break}let L=encodeURIComponent(m),H=v==="issue"?`${C}/api/v4/projects/${L}/issues/${S}/notes/${I}/award_emoji`:`${C}/api/v4/projects/${L}/merge_requests/${S}/notes/${I}/award_emoji`;try{let W=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":N},body:JSON.stringify({name:_})}),z=await W.text().catch(()=>"");this.log(`[gitlab/react] "${_}" -> POST ${H} : ${W.status} ${z.slice(0,120)}`),this.json(t,200,{ok:W.ok,status:W.status,gitlabResponse:z.slice(0,200)})}catch(W){this.log(`[gitlab/react] FETCH ERROR: ${W.message}`),this.json(t,500,{error:W.message})}break}case"POST /gitlab/send-note":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,agentId:I,text:R}=p,_=this.resolveGitlabTokenForAgent(I),M=_.token,N=this.config.channels.gitlab?.host;if(!M||!N){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:I,source:_.source,hasToken:!!M,hasHost:!!N}});break}this.log(`[gitlab/send-note] agent="${I}" source=${_.source}`);let C=encodeURIComponent(m),L=v==="issue"?`${N}/api/v4/projects/${C}/issues/${S}/notes`:`${N}/api/v4/projects/${C}/merge_requests/${S}/notes`;try{let H=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":M},body:JSON.stringify({body:ie(String(R??""),I||wa)})}),W=await H.text().catch(()=>""),z="";try{z=String(JSON.parse(W).id||"")}catch{}this.log(`[gitlab/send-note] agent="${I}" -> POST ${L} : ${H.status} noteId=${z||"?"}`),this.json(t,200,{ok:H.ok,status:H.status,noteId:z,...H.ok?{}:{error:Hn(W)}})}catch(H){this.log(`[gitlab/send-note] FETCH ERROR: ${H.message}`),this.json(t,500,{error:H.message})}break}case"POST /gitlab/log-time":{let p=await U(e),{project:m,noteableType:v,noteableIid:S,agentId:I,durationMs:R}=p,_=this.resolveGitlabTokenForAgent(I),M=_.token,N=this.config.channels.gitlab?.host;if(!M||!N){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:I,source:_.source}});break}let C=Math.max(60,Math.round(Number(R)/1e3)),L=Math.floor(C/3600),H=Math.ceil(C%3600/60),W=L>0?`${L}h${H>0?` ${H}m`:""}`:`${H}m`,z=encodeURIComponent(m),V=`${N}/api/v4/projects/${z}/${v==="merge_request"?"merge_requests":"issues"}/${S}/add_spent_time`;try{let Y=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":M},body:JSON.stringify({duration:W})});this.log(`[gitlab/log-time] agent="${I}" duration=${W} -> POST ${V} : ${Y.status}`);let K=Y.ok?void 0:Hn(await Y.text().catch(()=>""));this.json(t,200,{ok:Y.ok,status:Y.status,duration:W,...K?{error:K}:{}})}catch(Y){this.log(`[gitlab/log-time] FETCH ERROR: ${Y.message}`),this.json(t,500,{error:Y.message})}break}case"POST /channel/edit-comment":{let{channel:p,chatId:m,commentId:v,agentId:S,text:I}=await U(e),R=p==="gitlab"||p==="github"?this.router.getChannel(p):void 0;if(!R?.editComment){this.json(t,404,{error:"no such channel on this node"});break}let _=await R.editComment(String(m??""),String(v??""),String(I??""),S,!0);this.json(t,200,{ok:_});break}case"POST /github/send-comment":{let p=await U(e),{repo:m,issueNumber:v,agentId:S,text:I}=p,R=this.config.channels.github,M=(R?.agentMappings||[]).find(L=>L.agentId===S),N;if(M?.tokenFile)try{N=$s(M.tokenFile,"utf-8").trim().split(`
|
|
1318
1318
|
`)[0].trim()}catch{}if(N=N||M?.token,!N&&R?.tokenFile)try{N=$s(R.tokenFile,"utf-8").trim().split(`
|
|
1319
1319
|
`)[0].trim()}catch{}if(N=N||R?.token,!N){this.json(t,404,{error:"no github token for agent",debug:{agentId:S,hasMapping:!!M}});break}let C=`https://api.github.com/repos/${m}/issues/${v}/comments`;try{let L=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N}`,"User-Agent":"AgentX"},body:JSON.stringify({body:ie(String(I??""),S||wa)})}),H=await L.text().catch(()=>""),W="";try{W=String(JSON.parse(H).id||"")}catch{}this.log(`[github/send-comment] agent="${S}" -> POST ${C} : ${L.status} commentId=${W||"?"}`),this.json(t,200,{ok:L.ok,status:L.status,commentId:W})}catch(L){this.log(`[github/send-comment] FETCH ERROR: ${L.message}`),this.json(t,500,{error:L.message})}break}case"POST /github/react":{let p=await U(e),{repo:m,commentId:v,agentId:S}=p,I=this.config.channels.github,_=(I?.agentMappings||[]).find(C=>C.agentId===S),M;if(_?.tokenFile)try{M=$s(_.tokenFile,"utf-8").trim().split(`
|
|
1320
1320
|
`)[0].trim()}catch{}if(M=M||_?.token,!M&&I?.tokenFile)try{M=$s(I.tokenFile,"utf-8").trim().split(`
|
|
@@ -1331,4 +1331,4 @@ data: ${JSON.stringify(z)}
|
|
|
1331
1331
|
`)}catch{}},L=setInterval(()=>{try{t.write(`: ping
|
|
1332
1332
|
|
|
1333
1333
|
`)}catch{}},15e3);L.unref?.();let H=new AbortController;t.on("close",()=>{t.writableEnded||H.abort()});try{for await(let W of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:H.signal,vouchOwner:S}))C(W.event,W.data)}catch(W){C("error",{error:W?.message??String(W)})}finally{clearInterval(L);try{t.end()}catch{}}break}let _=p.context,M=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(F$(p,!0)==="callback"){let C=this.delegationGate(e,p,{callee:p.agent,peer:p.peer,message:p.message,calleeContext:_});if(!("track"in C)){let L=mo(C);this.json(t,L.status,L.body);break}}if(p.async===!0){let C=_?.channel,L=_?.chatId;if(!C||!L){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let H=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:H,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let W=p.peer,z=p.agent,Se=this.mesh;(async()=>{let V=Date.now(),Y;try{Y=await Se.sendTask(W,p.message,z,{vouchOwner:S,context:_,senderAgentId:M}),this.log(`[mesh/task async ${H}] ${W}/${z??"default"} finished in ${Date.now()-V}ms`)}catch(K){Y=`Delegation to ${W}/${z??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${H}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:Y,agentId:_?.agentId??M,accountId:_?.accountId})}catch(K){this.log(`[mesh/task async ${H}] delivery failed: ${K?.message??K}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:_,senderAgentId:M,vouchOwner:S});this.json(t,200,{response:N});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=await this.webrtc.handleOutgoing(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=this.webrtc.handleIncoming(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let p=await U(e),m=p.callId,v=p.target,S=p.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!v||!S){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:v,agentId:S});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let p=this.config.channels.webrtc;if(!p?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...p.stunServers.map(m=>({urls:m})),...p.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:p.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(p=>{let m=this.config.agents[p.id]||{},v=typeof m.description=="string"&&m.description.trim()||HL(m.systemPrompt)||`Agent "${p.name}" (${p.tier})`,S=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:p.id,name:p.name,description:v,tags:[p.tier,...S],color:we(p.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let p=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:p.summary()});break}case"GET /wiki/entries":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,v=n.searchParams.get("after")||void 0,S=m?p.getAgentEntries(m):p.getSharedStore().listEntries({after:v});this.json(t,200,{nodeId:this.config.node.id,count:S.length,entries:S.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let S=p.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:S.articles});break}case"GET /wiki/article":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent"),v=n.searchParams.get("path");if(!m||!v){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=p.getAgentWiki(m).readArticle(v);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /wiki/notes":{let{NoteStore:p}=await import("./notes-WJJEJ4CJ.js"),m=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(m)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let v=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new p(this.registry.getWikiHub().getBaseDir()).list(m==="all"?void 0:m);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:I.length,notes:I.slice(-v).reverse()});break}case"POST /wiki/notes":{let{NoteStore:p,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),v=this.config.wikiNotes;if(!v.enabled||!v.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let S=await U(e),I=m({...S,to:v.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let R=I.note;if(this.registry.getAgent(v.inbox)){try{let{note:N,added:C}=new p(this.registry.getWikiHub().getBaseDir()).add(R);this.json(t,C?201:200,{ok:!0,added:C,note:N,node:this.config.node.id})}catch(N){this.json(t,507,{error:N?.message??String(N)})}break}if(S.forwarded===!0){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node`});break}let _=this.mesh?.findAgentPeer(v.inbox);if(!_){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node or any known peer`});break}let M=this.mesh.directory().find(N=>N.peer===_.peer)?.peerUrl;if(!_.healthy||!M){this.json(t,503,{error:`the node hosting "${v.inbox}" (${_.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${M.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(_.peer)},body:JSON.stringify({...R,fromNode:R.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await N.json().catch(()=>({}));this.json(t,N.status,{...C,peer:_.peer})}catch(N){this.json(t,502,{error:`forward to ${_.peer} failed: ${N?.message??N}`,peer:_.peer})}break}case"GET /graph/schema":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:p.loadSchema()});break}case"GET /graph/nodes":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...p.loadNodes()});break}case"GET /graph/classifications":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",v=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),S=p.listByStatus(m,v);this.json(t,200,{nodeId:this.config.node.id,status:m,count:S.length,classifications:S});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await jy(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let d=this.registry.list().find(l=>l.id===i)?.runningTasks.filter(l=>l.channel===o&&l.chatId===a)||[];for(let l of d)this.registry.cancelRunningTask(l.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=Zp(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=gw();if(e==="json")return this.registry.getTodayUsage();let t=hw(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!kn(n)))try{let s=te(n,".claude","skills");zI(s,{recursive:!0});let i=te(s,wS);if(!kn(i))Dl(i,Cd(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=kS($s(i,"utf-8"),e);o&&(Dl(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!kn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||Rg(this.config.workflows,e)),i=qh(eh(t),this.config.requests.enabled||s?Bh():null);try{switch(Xh(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Yv(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(y=>y.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-NR7SLHGX.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return Mp(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(d){this.json(t,400,{error:"invalid JSON body",message:d.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let d=this.pushBridgeCaller(e);if("origin"in d)c=d.origin;else if(i!=="default"){this.json(t,403,{error:d.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:d}=await import("./push-bridge-NR7SLHGX.js"),l=d(i,this.pushBridgeCaller(e));if("error"in l){this.json(t,403,{error:l.error});return}}try{let d=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:d??null})}catch(d){this.log(`[mesh] /channel/send "${s}" failed: ${d.message}`),this.json(t,500,{error:d.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(d,l)=>{let u=0;for(let h of d)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:l}),u++);u>0&&o.push(`${l}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(d=>({id:d.jid,name:d.name,kind:d.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let d=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(d.map(async l=>{try{let u=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(l.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${l.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await yS({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Nl=Ll;Lt(Nl,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function HL(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function BL(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}QI();function Az(r){typeof r=="string"&&(Ts.error(r),process.exit(1)),r instanceof Error&&(Ts.error(r.message),process.exit(1)),Ts.error("Something went wrong. Please try again."),process.exit(1)}export{cj as a,Za as b,$t as c,jn as d,Wn as e,xt as f,gr as g,ay as h,ew as i,rR as j,iR as k,iw as l,Te as m,cw as n,dw as o,Or as p,t2 as q,n2 as r,Jr as s,bU as t,wC as u,bC as v,Vc as w,ib as x,kU as y,fb as z,vC as A,mb as B,yb as C,wb as D,vU as E,SU as F,$U as G,ti as H,Le as I,EG as J,bP as K,Dk as L,Nk as M,o_ as N,Zk as O,sv as P,J_ as Q,$d as R,SB as S,$B as T,IB as U,oS as V,xM as W,EB as X,CB as Y,is as Z,un as _,os as $,t4 as aa,LS as ba,fO as ca,V4 as da,Ui as ea,Hd as fa,Bd as ga,Xi as ha,we as ia,R0 as ja,zi as ka,hD as la,U0 as ma,pD as na,q0 as oa,Zi as pa,ps as qa,so as ra,io as sa,Y0 as ta,rl as ua,s$ as va,ct as wa,Ee as xa,c$ as ya,d$ as za,l$ as Aa,u$ as Ba,To as Ca,aI as Da,xl as Ea,dI as Fa,VN as Ga,p3 as Ha,Nl as Ia,Az as Ja};
|
|
1334
|
-
//# sourceMappingURL=chunk-
|
|
1334
|
+
//# sourceMappingURL=chunk-S7VM573Z.js.map
|