agentix-cli 0.180.0 → 0.181.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-43V7KUZU.js → App-UXX5TGFF.js} +2 -2
- package/dist/{ChatApp-ZG2IXOB5.js → ChatApp-X635NOAE.js} +2 -2
- package/dist/{absorb-eval-4NMMBFH3.js → absorb-eval-4ZPDWNBA.js} +2 -2
- package/dist/{adapter-57X4HJEA.js → adapter-Z23K544D.js} +2 -2
- package/dist/{agent-LP5F5OCL.js → agent-OBRH5BJZ.js} +2 -2
- package/dist/{board-dashboard-SIBVGWSE.js → board-dashboard-KZ43CMZQ.js} +36 -9
- package/dist/{board-dashboard-SIBVGWSE.js.map → board-dashboard-KZ43CMZQ.js.map} +1 -1
- package/dist/{chunk-S25OP23O.js → chunk-33DLG4I2.js} +5 -5
- package/dist/{chunk-6FNJ7GQ2.js → chunk-5LPCJZKI.js} +2 -2
- package/dist/{chunk-L7F226TX.js → chunk-5RSTB45Q.js} +2 -2
- package/dist/{chunk-2BI43ZKI.js → chunk-7RVJWLIP.js} +2 -2
- package/dist/{chunk-KPRWATQR.js → chunk-CF7CPE7K.js} +2 -2
- package/dist/{chunk-FZMS4UFL.js → chunk-DUZOHLTF.js} +2 -2
- package/dist/{chunk-XXWSFJFZ.js → chunk-FRVFRWFN.js} +2 -2
- package/dist/{chunk-BCDC7BOQ.js → chunk-HBQRVCLU.js} +2 -2
- package/dist/{chunk-YIR6FABW.js → chunk-HMEFQL5P.js} +2 -2
- package/dist/{chunk-KUZATIJA.js → chunk-IRZYRLXQ.js} +2 -2
- package/dist/{chunk-3VZNOJJK.js → chunk-IYITREE5.js} +2 -2
- package/dist/{chunk-DUWKRQKT.js → chunk-J56YGKUO.js} +2 -2
- package/dist/{chunk-P7FSTC5E.js → chunk-KOY3EOPH.js} +41 -29
- package/dist/chunk-KOY3EOPH.js.map +1 -0
- package/dist/{chunk-T7E33M6T.js → chunk-LZY6YN2J.js} +2 -2
- package/dist/{chunk-FXMUUDSH.js → chunk-NI2XD6P3.js} +2 -2
- package/dist/{chunk-TLSMX7LZ.js → chunk-OYCMFCME.js} +2 -2
- package/dist/{chunk-7NJLRLQN.js → chunk-PCWXHXTM.js} +2 -2
- package/dist/{chunk-CVFQA3TH.js → chunk-SD6UDSXV.js} +2 -2
- package/dist/{chunk-3X2BFCOZ.js → chunk-SDINSYTN.js} +2 -2
- package/dist/{chunk-OHPCZOOM.js → chunk-TZ7GB7FI.js} +2 -2
- package/dist/{chunk-5DJOGAS2.js → chunk-U5S6IP7Z.js} +3 -3
- package/dist/{chunk-RMSB6DKW.js → chunk-UFUQQ5J5.js} +2 -2
- package/dist/{chunk-7WMZJFYD.js → chunk-UHTIZCKU.js} +2 -2
- package/dist/{chunk-E5QQJY6T.js → chunk-UOIEKYRR.js} +6 -6
- package/dist/{chunk-M4BNVLGJ.js → chunk-VK3M3TVL.js} +2 -2
- package/dist/{chunk-QJKQELHR.js → chunk-WKU7YFDV.js} +2 -2
- package/dist/{chunk-PHT6HTAW.js → chunk-WZUY7VGL.js} +2 -2
- package/dist/{chunk-HYLVA6VA.js → chunk-ZBM24D2Y.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-NJKGG5OP.js → client-ILPJFCTF.js} +2 -2
- package/dist/{config-HILBFLHC.js → config-JVWOL233.js} +2 -2
- package/dist/{config-mutate-SJYPUDP5.js → config-mutate-WYCHP6VK.js} +2 -2
- package/dist/config-mutator-DKNHE6VP.js +2 -0
- package/dist/{contributions-HN3JAPFB.js → contributions-XD66HYWE.js} +2 -2
- package/dist/{doctor-6P5PYFMD.js → doctor-CGZ56DYP.js} +2 -2
- package/dist/{follow-up-tool-MXMT3GED.js → follow-up-tool-HPET6LZW.js} +2 -2
- package/dist/{hub-EBZO3VRY.js → hub-L5FFJPS3.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-BB2XYW5V.js → program-XM3X7HIL.js} +23 -23
- package/dist/{promote-M3GWICXS.js → promote-XI6W27JK.js} +2 -2
- package/dist/{query-XBRRKY6I.js → query-MGG5QKNC.js} +2 -2
- package/dist/{query-settings-3UVI3UQF.js → query-settings-CALZYYWD.js} +2 -2
- package/dist/{registry-5YYMCHMF.js → registry-XJWSLJ4O.js} +2 -2
- package/dist/{request-planner-45D32J2H.js → request-planner-JCRGGJUO.js} +2 -2
- package/dist/{review-candidates-VOTQHP2K.js → review-candidates-OEBEEAEZ.js} +2 -2
- package/dist/{routing-SPX5VDTG.js → routing-CGH54RYG.js} +2 -2
- package/dist/schedule-tool-UM3CAPDX.js +2 -0
- package/dist/{scheduler-OVYVZN6N.js → scheduler-2K5YEV2U.js} +2 -2
- package/dist/{seat-4VQ2X5PF.js → seat-DEL5YUOS.js} +2 -2
- package/dist/{select-2QW6SYWW.js → select-MRTWSI7U.js} +2 -2
- package/dist/{set-enabled-API6VRUP.js → set-enabled-XTDCFCZY.js} +2 -2
- package/dist/{sprint-tool-4PLRLWOU.js → sprint-tool-N7WPDX5J.js} +2 -2
- package/dist/{tool-PVFI2DWN.js → tool-BQEJOTF3.js} +2 -2
- package/dist/{tool-CMOZJTA2.js → tool-KZHWJ7BC.js} +2 -2
- package/dist/{tool-XEGKIHUP.js → tool-NZTJZDSB.js} +2 -2
- package/dist/{wiki-3MTKUBPS.js → wiki-YERCKD3E.js} +2 -2
- package/dist/wiki-enrich-K54LGNU3.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-P7FSTC5E.js.map +0 -1
- package/dist/config-mutator-XGZRKKD4.js +0 -2
- package/dist/schedule-tool-IUUGZFJ3.js +0 -2
- package/dist/wiki-enrich-7KX7YTZ4.js +0 -2
- /package/dist/{App-43V7KUZU.js.map → App-UXX5TGFF.js.map} +0 -0
- /package/dist/{ChatApp-ZG2IXOB5.js.map → ChatApp-X635NOAE.js.map} +0 -0
- /package/dist/{absorb-eval-4NMMBFH3.js.map → absorb-eval-4ZPDWNBA.js.map} +0 -0
- /package/dist/{adapter-57X4HJEA.js.map → adapter-Z23K544D.js.map} +0 -0
- /package/dist/{agent-LP5F5OCL.js.map → agent-OBRH5BJZ.js.map} +0 -0
- /package/dist/{chunk-S25OP23O.js.map → chunk-33DLG4I2.js.map} +0 -0
- /package/dist/{chunk-6FNJ7GQ2.js.map → chunk-5LPCJZKI.js.map} +0 -0
- /package/dist/{chunk-L7F226TX.js.map → chunk-5RSTB45Q.js.map} +0 -0
- /package/dist/{chunk-2BI43ZKI.js.map → chunk-7RVJWLIP.js.map} +0 -0
- /package/dist/{chunk-KPRWATQR.js.map → chunk-CF7CPE7K.js.map} +0 -0
- /package/dist/{chunk-FZMS4UFL.js.map → chunk-DUZOHLTF.js.map} +0 -0
- /package/dist/{chunk-XXWSFJFZ.js.map → chunk-FRVFRWFN.js.map} +0 -0
- /package/dist/{chunk-BCDC7BOQ.js.map → chunk-HBQRVCLU.js.map} +0 -0
- /package/dist/{chunk-YIR6FABW.js.map → chunk-HMEFQL5P.js.map} +0 -0
- /package/dist/{chunk-KUZATIJA.js.map → chunk-IRZYRLXQ.js.map} +0 -0
- /package/dist/{chunk-3VZNOJJK.js.map → chunk-IYITREE5.js.map} +0 -0
- /package/dist/{chunk-DUWKRQKT.js.map → chunk-J56YGKUO.js.map} +0 -0
- /package/dist/{chunk-T7E33M6T.js.map → chunk-LZY6YN2J.js.map} +0 -0
- /package/dist/{chunk-FXMUUDSH.js.map → chunk-NI2XD6P3.js.map} +0 -0
- /package/dist/{chunk-TLSMX7LZ.js.map → chunk-OYCMFCME.js.map} +0 -0
- /package/dist/{chunk-7NJLRLQN.js.map → chunk-PCWXHXTM.js.map} +0 -0
- /package/dist/{chunk-CVFQA3TH.js.map → chunk-SD6UDSXV.js.map} +0 -0
- /package/dist/{chunk-3X2BFCOZ.js.map → chunk-SDINSYTN.js.map} +0 -0
- /package/dist/{chunk-OHPCZOOM.js.map → chunk-TZ7GB7FI.js.map} +0 -0
- /package/dist/{chunk-5DJOGAS2.js.map → chunk-U5S6IP7Z.js.map} +0 -0
- /package/dist/{chunk-RMSB6DKW.js.map → chunk-UFUQQ5J5.js.map} +0 -0
- /package/dist/{chunk-7WMZJFYD.js.map → chunk-UHTIZCKU.js.map} +0 -0
- /package/dist/{chunk-E5QQJY6T.js.map → chunk-UOIEKYRR.js.map} +0 -0
- /package/dist/{chunk-M4BNVLGJ.js.map → chunk-VK3M3TVL.js.map} +0 -0
- /package/dist/{chunk-QJKQELHR.js.map → chunk-WKU7YFDV.js.map} +0 -0
- /package/dist/{chunk-PHT6HTAW.js.map → chunk-WZUY7VGL.js.map} +0 -0
- /package/dist/{chunk-HYLVA6VA.js.map → chunk-ZBM24D2Y.js.map} +0 -0
- /package/dist/{client-NJKGG5OP.js.map → client-ILPJFCTF.js.map} +0 -0
- /package/dist/{config-HILBFLHC.js.map → config-JVWOL233.js.map} +0 -0
- /package/dist/{config-mutate-SJYPUDP5.js.map → config-mutate-WYCHP6VK.js.map} +0 -0
- /package/dist/{config-mutator-XGZRKKD4.js.map → config-mutator-DKNHE6VP.js.map} +0 -0
- /package/dist/{contributions-HN3JAPFB.js.map → contributions-XD66HYWE.js.map} +0 -0
- /package/dist/{doctor-6P5PYFMD.js.map → doctor-CGZ56DYP.js.map} +0 -0
- /package/dist/{follow-up-tool-MXMT3GED.js.map → follow-up-tool-HPET6LZW.js.map} +0 -0
- /package/dist/{hub-EBZO3VRY.js.map → hub-L5FFJPS3.js.map} +0 -0
- /package/dist/{program-BB2XYW5V.js.map → program-XM3X7HIL.js.map} +0 -0
- /package/dist/{promote-M3GWICXS.js.map → promote-XI6W27JK.js.map} +0 -0
- /package/dist/{query-XBRRKY6I.js.map → query-MGG5QKNC.js.map} +0 -0
- /package/dist/{query-settings-3UVI3UQF.js.map → query-settings-CALZYYWD.js.map} +0 -0
- /package/dist/{registry-5YYMCHMF.js.map → registry-XJWSLJ4O.js.map} +0 -0
- /package/dist/{request-planner-45D32J2H.js.map → request-planner-JCRGGJUO.js.map} +0 -0
- /package/dist/{review-candidates-VOTQHP2K.js.map → review-candidates-OEBEEAEZ.js.map} +0 -0
- /package/dist/{routing-SPX5VDTG.js.map → routing-CGH54RYG.js.map} +0 -0
- /package/dist/{schedule-tool-IUUGZFJ3.js.map → schedule-tool-UM3CAPDX.js.map} +0 -0
- /package/dist/{scheduler-OVYVZN6N.js.map → scheduler-2K5YEV2U.js.map} +0 -0
- /package/dist/{seat-4VQ2X5PF.js.map → seat-DEL5YUOS.js.map} +0 -0
- /package/dist/{select-2QW6SYWW.js.map → select-MRTWSI7U.js.map} +0 -0
- /package/dist/{set-enabled-API6VRUP.js.map → set-enabled-XTDCFCZY.js.map} +0 -0
- /package/dist/{sprint-tool-4PLRLWOU.js.map → sprint-tool-N7WPDX5J.js.map} +0 -0
- /package/dist/{tool-PVFI2DWN.js.map → tool-BQEJOTF3.js.map} +0 -0
- /package/dist/{tool-CMOZJTA2.js.map → tool-KZHWJ7BC.js.map} +0 -0
- /package/dist/{tool-XEGKIHUP.js.map → tool-NZTJZDSB.js.map} +0 -0
- /package/dist/{wiki-3MTKUBPS.js.map → wiki-YERCKD3E.js.map} +0 -0
- /package/dist/{wiki-enrich-7KX7YTZ4.js.map → wiki-enrich-K54LGNU3.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-DUZOHLTF.js";import{d as gp,g as pp,h as fp}from"./chunk-HMEFQL5P.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-5LPCJZKI.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-SDINSYTN.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,y as Wt,ya as qg,z as vh}from"./chunk-33DLG4I2.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-VK3M3TVL.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-FRVFRWFN.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-SD6UDSXV.js";import{a as ug,b as hg}from"./chunk-IRZYRLXQ.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-NI2XD6P3.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-KOY3EOPH.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-UM3CAPDX.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-KZHWJ7BC.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_content":{let{runContentTool:n}=await import("./tool-NZTJZDSB.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-BQEJOTF3.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_sprint":{let{runSprintTool:n}=await import("./sprint-tool-N7WPDX5J.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:J})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-HPET6LZW.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-YERCKD3E.js"),{agenticQuery:i,sharedQueryEnabled:o}=await import("./query-MGG5QKNC.js"),{loadQuerySettings:a,toolNoteSourceFor:c}=await import("./query-settings-CALZYYWD.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.181.0",commit:"7faf13f",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(`
|
|
@@ -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-Z23K544D.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-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(`
|
|
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-XTDCFCZY.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-UOIEKYRR.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Ct}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ut,c as Ht}from"./chunk-VJVXEVZ7.js";import{b as Dt,e as jt,f as Mt,i as Ft,k as _t,l as Lt,r as Bt}from"./chunk-
|
|
1
|
+
import{c as Ct}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ut,c as Ht}from"./chunk-VJVXEVZ7.js";import{b as Dt,e as jt,f as Mt,i as Ft,k as _t,l as Lt,r as Bt}from"./chunk-SD6UDSXV.js";import{b as Wt,d as Ot,e as Nt}from"./chunk-PE5V2LI7.js";import{e as xt,g as Pt,h as Tt,i as _e}from"./chunk-GQ76J72O.js";import{a as Et}from"./chunk-GV7S5BAX.js";import{y as St,z as yr}from"./chunk-NI2XD6P3.js";import{b as $t,f as wr}from"./chunk-72SZI2UW.js";import{a as At,b as Ee,d as Ce,e as Rt,f as Fe}from"./chunk-BERWTVG2.js";import{c as It,d as vt}from"./chunk-QOYAX2FT.js";import{Y as Me,ha as hr}from"./chunk-KOY3EOPH.js";import{j as je,r as mr}from"./chunk-UEEB3UTU.js";import{existsSync as kr,mkdirSync as Kt,readFileSync as br,writeFileSync as Ir,renameSync as vr}from"fs";import{resolve as qt,dirname as $r}from"path";var zt=class{filePath;log;constructor(e={}){let t=e.baseDir??qt(process.cwd(),".agentx");this.filePath=qt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Kt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!kr(this.filePath))return{version:1,overrides:{}};try{let e=br(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Kt($r(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Ir(t,JSON.stringify(e,null,2)),vr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Qt,writeFileSync as Ue,appendFileSync as xr,mkdirSync as Pr,existsSync as Zt,statSync as Tr}from"fs";import{resolve as ce}from"path";var Jt="[Agent Memory \u2014 persistent facts from past conversations]",Sr=2400;function Yt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Ar(n,e=Date.now()){let t=Ot(n,e),r=n.undated?"UNVERIFIED (never checked) ":Yt(t,xt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Rr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=Tt(n,e);return{line:`- [${n.category}] ${Yt(o,Pt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Gt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Jt.length,a=!1;for(let i of n){let d=e.length>0?Nt(i.content,e):null,l,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Ar(d,t),c=d.id}else l=Rr(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?_e.length:0;if(s+f+l.line.length>Sr)break;r.push({fact:i,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Vt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[_e]:[];return[Jt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var Xt=200,Wr=7,en=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ce(e,".agentx/memory"),this.ledger=new Wt(ce(e,".agentx/wiki")),Zt(this.memoryDir)||Pr(this.memoryDir,{recursive:!0})}filePath(e){return ce(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ee(t.content))return!1;let r=t.source.trust??At(t.source.channel),o=t.review??Rt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return xr(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Zt(t))return[];try{let{mtimeMs:r,size:o}=Tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Qt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Fe);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ce(this.memoryDir,`${t}_bm25_cache.json`),i=vt(s,a),d=It(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Vt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Gt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Ue(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -39,4 +39,4 @@ ${n.text}`}async function xe(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
39
39
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(ht(this.file))try{let e=JSON.parse(wt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Qn(er(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${nr(4).toString("hex")}.tmp`;Xn(t,JSON.stringify(e,null,2)+`
|
|
40
40
|
`,{encoding:"utf-8",mode:384}),Zn(t,this.file)}};import{extname as ti}from"path";var or=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,sr=/<agentx-artifact>[\s\S]*$/i;function Nl(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(or,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,c=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(sr,""):s).trim(),artifacts:r}}function Dl(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(or,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(sr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ni={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},jl={bytes:20*1024*1024,perMessage:20,pathChars:512};function Ml(n){return ni[ti(n).toLowerCase()]??null}var ri=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
41
41
|
`);function El(n,e,t){return n==="app"&&e&&t!==!1?ri:void 0}import{lstatSync as kt,mkdirSync as oi,readdirSync as si,realpathSync as yt,unlinkSync as ii}from"fs";import{join as Ne,resolve as ir}from"path";var ar=".agentx/outbox",ai=7*24*60*60*1e3;function di(n,e){try{let t=yt(ir(e,n)),r=Ne(t,ar);return yt(r)===r&&kt(r).isDirectory()?r:null}catch{return null}}function Ll(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=yt(ir(t,n));kt(Ne(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||oi(Ne(o,ar),{recursive:!0})}catch{return 0}let r=di(n,t);return r?dr(r,(e.now??Date.now())-(e.maxAgeMs??ai)):0}function dr(n,e){let t=0;for(let r of si(n)){let o=Ne(n,r);try{let s=kt(o);s.isDirectory()?t+=dr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(ii(o),t++)}catch{}}return t}export{zt as a,en as b,tn as c,Si as d,Dr as e,Ai as f,jr as g,xi as h,Pi as i,Ti as j,Wi as k,Oi as l,Ni as m,Di as n,Cr as o,ji as p,Mi as q,_i as r,qe as s,qr as t,Li as u,Ui as v,zr as w,Hi as x,ln as y,qi as z,zi as A,cn as B,pn as C,Qr as D,Qi as E,Zi as F,ta as G,na as H,O as I,te as J,S as K,he as L,go as M,Ve as N,L as O,Xe as P,tt as Q,pt as R,Is as S,xs as T,gt as U,No as V,Us as W,el as X,tl as Y,nl as Z,rl as _,ol as $,Hs as aa,Bs as ba,sl as ca,il as da,al as ea,dl as fa,cl as ga,pl as ha,fl as ia,gl as ja,ml as ka,hl as la,wl as ma,yl as na,kl as oa,bl as pa,Il as qa,Gs as ra,vl as sa,$l as ta,Sl as ua,Al as va,rr as wa,Nl as xa,Dl as ya,jl as za,Ml as Aa,El as Ba,ar as Ca,Ll as Da};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
42
|
+
//# sourceMappingURL=chunk-VK3M3TVL.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-
|
|
1
|
+
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-TZ7GB7FI.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-IRZYRLXQ.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function j(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
|
|
2
2
|
`)}async function L(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function ae(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,p;try{p=Y(t.configPath)}catch(a){return`Error: ${a.message}`}let h=p.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(h).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>ee(i,f,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!p.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),I=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=_(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!p.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||R;if(!b(g))return`Error: unknown timezone "${g}".`;let u=o||q(i.matched,f);if(!B(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(h[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=j(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let y=s(n.report);if(y&&y!=="always"&&y!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let G={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},H=k({parsed:i,agent:f,prompt:l,timezone:g,notify:$,report:y,enabled:!1,createdBy:e.agentId,approval:G}),N=await I(F=>E(F,`crons.${u}`,H));if(!N.success)return`Error: ${N.error}`;let T=S(w(i.cron,g,d),g),U=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${T}`,`Agent: ${f}`,$?`${y==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),X=await L(p,t,U);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${T}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=h[o];if(!c)return`Error: schedule "${o}" not found.`;if(!K(p,c,e))return Q(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&m(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await I(i=>E(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(m(c)&&c.approval.requestedBy===e.agentId){let u=await I($=>D($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(m(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await I(u=>{if(!P(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);E(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?S(w(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await L(p,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function ie(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),p=s(r?e.AGENTX_CHAT_ID:n.chatId),h=s(n.accountId);return{agentId:t,channel:d,chatId:p,...h?{accountId:h}:{}}}export{ae as a,ie as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-WKU7YFDV.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Za as y,yb as $}from"./chunk-
|
|
1
|
+
import{Za as y,yb as $}from"./chunk-KOY3EOPH.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as S,writeFileSync as C}from"fs";import{resolve as u}from"path";function f(t){return u(t,".agentx","email")}function d(t,e){k(u(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
|
|
2
2
|
`,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>u(f(t),"threads.json");function w(t){return g(D(t))??{}}function F(t,e){return w(t)[e.toLowerCase()]}function I(t,e){let r=w(t);r[e.to.toLowerCase()]=e,d(D(t),r)}var h=(t,e)=>u(f(t),"cursors",`${e}.json`);function L(t,e){return g(h(t,e))}function z(t,e,r){d(h(t,e),r)}var T=2e4,_=t=>u(f(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),c=(t,e)=>u(_(t),`${e}.json`);function B(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return d(c(t,s.id),s),s}function v(t,e){return N(e)?g(c(t,e)):null}function U(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function V(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${c(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(c(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let a=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...a?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let m=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!m.ok){d(c(t,e),{...s,error:m.error});try{S(i)}catch{}return{ok:!1,error:`not sent: ${m.error}`}}o.status="sent",delete o.error}d(c(t,e),o);try{S(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function J(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);let{default:i}=await import("nodemailer"),a=i.createTransport({host:s.host,port:s.port,secure:s.secure,auth:{user:s.user,pass:s.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await a.sendMail({from:{name:e,address:t.address},to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:{"Auto-Submitted":"auto-replied"}})).messageId}finally{a.close()}}function q(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=y.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,a=i.name||t?.agents?.[r.agent]?.name||r.agent;return await J(i,a,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{F as a,I as b,L as c,z as d,B as e,v as f,U as g,V as h,P as i,J as j,q as k};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-WZUY7VGL.js.map
|