agentix-cli 0.195.0 → 0.196.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.
@@ -1,4 +1,4 @@
1
- import{$a as xe,A as Af,Ab as Bm,B as Rf,Ba as oc,Bb as Xm,C as Zt,Ca as ym,Cb as Vm,D as hr,E as Ef,Eb as Jm,F as Cf,Fa as wm,G as Pf,Ga as xm,Gb as Km,H as Nf,I as Lf,Ib as zm,J as jf,K as Ff,L as Wf,M as Uf,Mb as Ym,N as Gf,Na as cc,Nb as Qm,O as Hf,Oa as At,P as fr,Pa as Am,Q as qf,Qa as Rm,R as nc,Ta as Rt,U as Bf,Ua as Em,Va as Cm,W as Xf,Wa as Pm,Wb as uc,Xa as _m,Xb as hc,Ya as Mm,Za as Om,Zb as Zm,a as tf,ab as wr,b as Va,ba as mr,bb as lc,ca as om,cb as Dm,db as Xn,ea as am,eb as Nm,f as Ja,fa as tn,fb as Fe,g as nf,gb as Lm,h as sf,hb as jm,i as Ka,ia as cm,ib as Fm,j as rf,jb as br,k as Bn,kb as kr,l as of,la as lm,lb as Wm,m as af,mb as Um,n as cf,o as it,oa as dm,p as lf,pa as um,q as df,qa as hm,ra as rc,rb as Gm,s as uf,sa as gm,u as hf,ua as pm,v as ot,va as ic,vb as Hm,w as Ya,wa as fm,x as If,xa as je,xb as vr,y as Tf,ya as mm,yb as dc,z as xf,za as yr,zb as qm}from"./chunk-I45E5TLK.js";import{d as Qp,g as Zp,h as ef}from"./chunk-XH36J3Z2.js";import{a as gf}from"./chunk-ZVP6GB4G.js";import{F as wf,G as bf,I as lr,J as Qa,K as dr,L as Qt,P as Vf,c as Cp,d as Pp,f as _p,g as qn,h as cr,i as Ha,j as Mp,k as Re,p as mf,r as yf}from"./chunk-M2E3CNFS.js";import{a as rm,b as im}from"./chunk-VZLIBDLH.js";import{b as bm,c as km,d as ac,e as vm,f as Sm,g as $m,h as Im,i as Tm}from"./chunk-EKJG63EJ.js";import{d as kf}from"./chunk-6V5JBHUN.js";import{g as vf}from"./chunk-LQE73AZR.js";import{b as Sf,c as $f}from"./chunk-2D3RYIDU.js";import{b as Jf}from"./chunk-MRIVENBY.js";import{i as Kf,m as sc,n as zf,p as Yf,q as Qf,r as Zf,s as em,t as tm,u as nm}from"./chunk-BIYEGA7Q.js";import{h as Za,n as ec,o as _f,p as gr,q as xt,r as en,s as Le,u as Mf,v as Of,w as Df,x as tc,y as pr}from"./chunk-XPZSEDE3.js";import{a as sm}from"./chunk-PPUN7YHA.js";import{a as pf,b as ff}from"./chunk-A5GYG56I.js";import{o as za}from"./chunk-FO762MEC.js";import{b as ur}from"./chunk-UKUH662W.js";import{a as Ba}from"./chunk-6TTGRTDO.js";import{a as rt}from"./chunk-MNG2AMKZ.js";import{c as Wp,d as Up,f as Gp,g as Hp,i as qp,k as Bp,l as Xp}from"./chunk-RX5O5637.js";import{d as Vp}from"./chunk-5ELIX7BQ.js";import{b as Jp,c as Kp}from"./chunk-X7UQY7CH.js";import{c as zp,d as Xa,e as Yp}from"./chunk-UOYIC7XN.js";import{a as qa,b as Op,c as Dp}from"./chunk-QPABR72X.js";import{a as Np,b as st,c as Lp,d as jp,e as Fp}from"./chunk-AJ5HMDRW.js";import{c as Yt}from"./chunk-KP7KDLZ2.js";import{A as Xt,B as sg,C as B,Ca as Ap,E as lg,F as dg,G as ug,H as hg,I as me,J as pg,K as fg,L as mg,M as Vt,N as yg,O as er,P as xg,Q as Ag,R as Rg,S as fp,T as mp,U as yp,V as wp,W as bp,X as kp,Z as Hn,_ as vp,a as _h,b as Ra,ba as oe,c as Oh,ca as nt,d as Gh,da as Ua,e as Hh,ea as Jt,f as Fn,fa as Ga,ga as or,h as Ca,ha as Kt,i as Pa,ia as zt,j as _a,ja as $e,k as Ma,ka as Tt,l as qh,la as ae,ma as Sp,na as $p,qa as xp,u as Vh,v as Yh,w as $t,x as Qh,y as Zh,z as eg}from"./chunk-MB5CBY2C.js";import{$ as sp,Da as Tp,G as Ig,H as Tg,N as Eg,P as Cg,R as Bg,S as Xg,T as Qg,U as Zg,V as ep,W as tp,Y as Wa,Z as ir,_ as np,a as Jh,aa as rp,ba as ip,c as tg,ca as op,d as ng,da as ap,e as It,ea as cp,f as Ne,fa as lp,h as wg,ha as dp,i as bg,j as kg,k as Da,ka as up,l as vg,m as Sg,p as $g,pa as hp,q as nr,qa as gp,ta as pp,xa as Ip}from"./chunk-PO2SORKY.js";import{a as Oa,b as zh}from"./chunk-MEFPXHQJ.js";import{a as Ze,d as tr}from"./chunk-3FZ6WHKX.js";import{A as Rp,B as ar,C as Ep,h as ku,n as vu,o as oa}from"./chunk-UOIWIVU3.js";import{b as yu}from"./chunk-SFQUP3BP.js";import{a as Pg,b as Na,c as _g,d as Mg,e as Og,i as Dg,j as Ng}from"./chunk-VE3SSOQX.js";import{b as gg}from"./chunk-W4YR2RO2.js";import{b as jg,c as Fg,d as La,f as sr,g as Wg,h as Ug,i as Gg,j as Gn,k as rr,m as ja,n as Hg,o as qg}from"./chunk-VJVXEVZ7.js";import{b as fe,d as Ye,f as Qe,g as Wn,i as Se,j as Lg,k as et,l as tt,m as Kg,p as zg,r as Yg,t as Fa}from"./chunk-MC3ZZA5G.js";import{a as Vg,b as Jg}from"./chunk-KXJRXRSD.js";import{b as Kh}from"./chunk-5ONH4ITT.js";import{d as rg,e as ig,f as og,g as ag,h as cg,j as Un}from"./chunk-X5C5W3E4.js";import{c as Zs}from"./chunk-OWNQ2FD4.js";import{c as Xh}from"./chunk-LUOW2YHY.js";import{d as $u,e as kx,m as Rh,n as Ox,q as Eh,v as Ch,x as Aa,y as ze,z as jn}from"./chunk-2KYGPVTX.js";import{a as De,b as Ln,f as Ys}from"./chunk-72SZI2UW.js";import{a as Mn,b as Su}from"./chunk-FCPTN6NF.js";import{c as Ph}from"./chunk-MYVHVJWZ.js";import{f as Mh}from"./chunk-QUFIUXMQ.js";import{d as Dh,e as Nh,f as Ea,g as Qs,h as Lh,i as jh,j as Fh,k as Wh,q as Uh}from"./chunk-AV7T3SYT.js";import{c as Bh}from"./chunk-A7JSRDJL.js";import{o as ia,p as bx}from"./chunk-DCIYOPJF.js";import{a as Fs,b as wx}from"./chunk-7I7IEX4S.js";import{b as wu,e as bu}from"./chunk-JHCI6XCJ.js";import{e as kt}from"./chunk-DSYKYZMT.js";import{A as Hs,Aa as gh,B as Ix,Ba as $a,Bb as Ah,C as qs,Ca as ph,D as Cu,Da as Ia,E as Tx,F as Pu,Fa as zs,G as _u,Ga as fh,H as Mu,Ia as mh,Ib as Mx,Ja as yh,K as pa,Ka as wh,L as Lu,La as Nn,M as ju,Ma as bh,N as On,Na as kh,O as Bs,Oa as vh,P as Fu,Pa as Sh,Q as Wu,Qa as $h,R as Yu,Ra as Cx,S as Ax,T as Dn,U as Qu,Ua as Ih,V as Xs,W as Vs,X as Zu,Xa as Th,Y as Rx,Ya as xh,Z as eh,_ as Ex,aa as Xe,ab as Px,ba as th,cb as Ta,d as aa,da as wa,e as ca,ea as ba,eb as _x,f as Iu,fa as Ve,g as Tu,ga as Je,h as xu,ha as nh,j as vx,ja as ka,ka as va,la as sh,ma as rh,n as Bt,o as Ru,oa as ih,p as da,pa as oh,q as Sx,qa as Ke,r as Ws,ra as Sa,s as ua,sa as ah,t as Us,ta as ch,u as Gs,ua as Js,va as lh,w as vt,wa as Ks,x as ha,xa as dh,y as Eu,ya as uh,z as $x,za as hh,zb as xa}from"./chunk-P6WSD2UR.js";import{a as Ou,e as St,f as Du,g as Nu,h as ga}from"./chunk-VJ5HC63R.js";import{a as Uu,b as Gu,c as Hu,e as qu,f as Bu,i as xx,j as fa,k as Xu,l as Vu,m as ma,n as Ju,o as Ku,q as ya,r as zu}from"./chunk-UEEB3UTU.js";import{b as la,e as Au}from"./chunk-VQRY4IDI.js";import{d as qt}from"./chunk-QIJLFPWE.js";import{existsSync as bc,readFileSync as kc}from"fs";Mu();var ey=["answer","narration","line"],ty=5e3;function ny(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function sy(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 l=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!l||!d||!ey.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${ey.join(" | ")}`}};if(l.length>ty)return{status:413,body:{error:`text is over ${ty} characters`}};let h=e(d);if(!h)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:f,done:y}=r.enqueue({voice:h,text:l,agentId:d,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()}:gc(o);case"front":return r.front(o)?{status:200,body:r.view()}:gc(o);case"replay":{let l=r.replay(o);return l?{status:202,body:{item:l}}:gc(o)}default:return{status:404,body:{error:"Not found"}}}}function ry(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?[_u(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$a as xe,A as Af,Ab as Bm,B as Rf,Ba as oc,Bb as Xm,C as Zt,Ca as ym,Cb as Vm,D as hr,E as Ef,Eb as Jm,F as Cf,Fa as wm,G as Pf,Ga as xm,Gb as Km,H as Nf,I as Lf,Ib as zm,J as jf,K as Ff,L as Wf,M as Uf,Mb as Ym,N as Gf,Na as cc,Nb as Qm,O as Hf,Oa as At,P as fr,Pa as Am,Q as qf,Qa as Rm,R as nc,Ta as Rt,U as Bf,Ua as Em,Va as Cm,W as Xf,Wa as Pm,Wb as uc,Xa as _m,Xb as hc,Ya as Mm,Za as Om,Zb as Zm,a as tf,ab as wr,b as Va,ba as mr,bb as lc,ca as om,cb as Dm,db as Xn,ea as am,eb as Nm,f as Ja,fa as tn,fb as Fe,g as nf,gb as Lm,h as sf,hb as jm,i as Ka,ia as cm,ib as Fm,j as rf,jb as br,k as Bn,kb as kr,l as of,la as lm,lb as Wm,m as af,mb as Um,n as cf,o as it,oa as dm,p as lf,pa as um,q as df,qa as hm,ra as rc,rb as Gm,s as uf,sa as gm,u as hf,ua as pm,v as ot,va as ic,vb as Hm,w as Ya,wa as fm,x as If,xa as je,xb as vr,y as Tf,ya as mm,yb as dc,z as xf,za as yr,zb as qm}from"./chunk-YWAJNF2A.js";import{d as Qp,g as Zp,h as ef}from"./chunk-XH36J3Z2.js";import{a as gf}from"./chunk-ZVP6GB4G.js";import{F as wf,G as bf,I as lr,J as Qa,K as dr,L as Qt,P as Vf,c as Cp,d as Pp,f as _p,g as qn,h as cr,i as Ha,j as Mp,k as Re,p as mf,r as yf}from"./chunk-M2E3CNFS.js";import{a as rm,b as im}from"./chunk-VZLIBDLH.js";import{b as bm,c as km,d as ac,e as vm,f as Sm,g as $m,h as Im,i as Tm}from"./chunk-EKJG63EJ.js";import{d as kf}from"./chunk-6V5JBHUN.js";import{g as vf}from"./chunk-LQE73AZR.js";import{b as Sf,c as $f}from"./chunk-2D3RYIDU.js";import{b as Jf}from"./chunk-MRIVENBY.js";import{i as Kf,m as sc,n as zf,p as Yf,q as Qf,r as Zf,s as em,t as tm,u as nm}from"./chunk-BIYEGA7Q.js";import{h as Za,n as ec,o as _f,p as gr,q as xt,r as en,s as Le,u as Mf,v as Of,w as Df,x as tc,y as pr}from"./chunk-XPZSEDE3.js";import{a as sm}from"./chunk-PPUN7YHA.js";import{a as pf,b as ff}from"./chunk-A5GYG56I.js";import{o as za}from"./chunk-FO762MEC.js";import{b as ur}from"./chunk-UKUH662W.js";import{a as Ba}from"./chunk-6TTGRTDO.js";import{a as rt}from"./chunk-MNG2AMKZ.js";import{c as Wp,d as Up,f as Gp,g as Hp,i as qp,k as Bp,l as Xp}from"./chunk-RX5O5637.js";import{d as Vp}from"./chunk-5ELIX7BQ.js";import{b as Jp,c as Kp}from"./chunk-X7UQY7CH.js";import{c as zp,d as Xa,e as Yp}from"./chunk-UOYIC7XN.js";import{a as qa,b as Op,c as Dp}from"./chunk-QPABR72X.js";import{a as Np,b as st,c as Lp,d as jp,e as Fp}from"./chunk-AJ5HMDRW.js";import{c as Yt}from"./chunk-KP7KDLZ2.js";import{A as Xt,B as sg,C as B,Ca as Ap,E as lg,F as dg,G as ug,H as hg,I as me,J as pg,K as fg,L as mg,M as Vt,N as yg,O as er,P as xg,Q as Ag,R as Rg,S as fp,T as mp,U as yp,V as wp,W as bp,X as kp,Z as Hn,_ as vp,a as _h,b as Ra,ba as oe,c as Oh,ca as nt,d as Gh,da as Ua,e as Hh,ea as Jt,f as Fn,fa as Ga,ga as or,h as Ca,ha as Kt,i as Pa,ia as zt,j as _a,ja as $e,k as Ma,ka as Tt,l as qh,la as ae,ma as Sp,na as $p,qa as xp,u as Vh,v as Yh,w as $t,x as Qh,y as Zh,z as eg}from"./chunk-MB5CBY2C.js";import{$ as sp,Da as Tp,G as Ig,H as Tg,N as Eg,P as Cg,R as Bg,S as Xg,T as Qg,U as Zg,V as ep,W as tp,Y as Wa,Z as ir,_ as np,a as Jh,aa as rp,ba as ip,c as tg,ca as op,d as ng,da as ap,e as It,ea as cp,f as Ne,fa as lp,h as wg,ha as dp,i as bg,j as kg,k as Da,ka as up,l as vg,m as Sg,p as $g,pa as hp,q as nr,qa as gp,ta as pp,xa as Ip}from"./chunk-PO2SORKY.js";import{a as Oa,b as zh}from"./chunk-MEFPXHQJ.js";import{a as Ze,d as tr}from"./chunk-3FZ6WHKX.js";import{A as Rp,B as ar,C as Ep,h as ku,n as vu,o as oa}from"./chunk-UOIWIVU3.js";import{b as yu}from"./chunk-SFQUP3BP.js";import{a as Pg,b as Na,c as _g,d as Mg,e as Og,i as Dg,j as Ng}from"./chunk-VE3SSOQX.js";import{b as gg}from"./chunk-W4YR2RO2.js";import{b as jg,c as Fg,d as La,f as sr,g as Wg,h as Ug,i as Gg,j as Gn,k as rr,m as ja,n as Hg,o as qg}from"./chunk-VJVXEVZ7.js";import{b as fe,d as Ye,f as Qe,g as Wn,i as Se,j as Lg,k as et,l as tt,m as Kg,p as zg,r as Yg,t as Fa}from"./chunk-MC3ZZA5G.js";import{a as Vg,b as Jg}from"./chunk-KXJRXRSD.js";import{b as Kh}from"./chunk-5ONH4ITT.js";import{d as rg,e as ig,f as og,g as ag,h as cg,j as Un}from"./chunk-X5C5W3E4.js";import{c as Zs}from"./chunk-OWNQ2FD4.js";import{c as Xh}from"./chunk-LUOW2YHY.js";import{d as $u,e as kx,m as Rh,n as Ox,q as Eh,v as Ch,x as Aa,y as ze,z as jn}from"./chunk-2KYGPVTX.js";import{a as De,b as Ln,f as Ys}from"./chunk-72SZI2UW.js";import{a as Mn,b as Su}from"./chunk-FCPTN6NF.js";import{c as Ph}from"./chunk-MYVHVJWZ.js";import{f as Mh}from"./chunk-QUFIUXMQ.js";import{d as Dh,e as Nh,f as Ea,g as Qs,h as Lh,i as jh,j as Fh,k as Wh,q as Uh}from"./chunk-AV7T3SYT.js";import{c as Bh}from"./chunk-A7JSRDJL.js";import{o as ia,p as bx}from"./chunk-DCIYOPJF.js";import{a as Fs,b as wx}from"./chunk-7I7IEX4S.js";import{b as wu,e as bu}from"./chunk-JHCI6XCJ.js";import{e as kt}from"./chunk-DSYKYZMT.js";import{A as Hs,Aa as gh,B as Ix,Ba as $a,Bb as Ah,C as qs,Ca as ph,D as Cu,Da as Ia,E as Tx,F as Pu,Fa as zs,G as _u,Ga as fh,H as Mu,Ia as mh,Ib as Mx,Ja as yh,K as pa,Ka as wh,L as Lu,La as Nn,M as ju,Ma as bh,N as On,Na as kh,O as Bs,Oa as vh,P as Fu,Pa as Sh,Q as Wu,Qa as $h,R as Yu,Ra as Cx,S as Ax,T as Dn,U as Qu,Ua as Ih,V as Xs,W as Vs,X as Zu,Xa as Th,Y as Rx,Ya as xh,Z as eh,_ as Ex,aa as Xe,ab as Px,ba as th,cb as Ta,d as aa,da as wa,e as ca,ea as ba,eb as _x,f as Iu,fa as Ve,g as Tu,ga as Je,h as xu,ha as nh,j as vx,ja as ka,ka as va,la as sh,ma as rh,n as Bt,o as Ru,oa as ih,p as da,pa as oh,q as Sx,qa as Ke,r as Ws,ra as Sa,s as ua,sa as ah,t as Us,ta as ch,u as Gs,ua as Js,va as lh,w as vt,wa as Ks,x as ha,xa as dh,y as Eu,ya as uh,z as $x,za as hh,zb as xa}from"./chunk-P6WSD2UR.js";import{a as Ou,e as St,f as Du,g as Nu,h as ga}from"./chunk-VJ5HC63R.js";import{a as Uu,b as Gu,c as Hu,e as qu,f as Bu,i as xx,j as fa,k as Xu,l as Vu,m as ma,n as Ju,o as Ku,q as ya,r as zu}from"./chunk-UEEB3UTU.js";import{b as la,e as Au}from"./chunk-VQRY4IDI.js";import{d as qt}from"./chunk-QIJLFPWE.js";import{existsSync as bc,readFileSync as kc}from"fs";Mu();var ey=["answer","narration","line"],ty=5e3;function ny(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function sy(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 l=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!l||!d||!ey.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${ey.join(" | ")}`}};if(l.length>ty)return{status:413,body:{error:`text is over ${ty} characters`}};let h=e(d);if(!h)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:f,done:y}=r.enqueue({voice:h,text:l,agentId:d,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()}:gc(o);case"front":return r.front(o)?{status:200,body:r.view()}:gc(o);case"replay":{let l=r.replay(o);return l?{status:202,body:{item:l}}:gc(o)}default:return{status:404,body:{error:"Not found"}}}}function ry(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?[_u(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var gc=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});var Dx=20,pc=120,Nx=80,Lx=new Set(["waiting_owner","needs_attention"]);function fc(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Sr(r){return{total:r.length,items:r.slice(0,Dx)}}var mc=r=>new Date(r).toISOString();function iy(r){return{id:r.id,agentId:r.agentId,kind:r.kind,text:fc(r.text,Nx),enqueuedAt:mc(r.enqueuedAt)}}function oy(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:fc(i.title,pc),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:fc(i.title,pc),from:i.from,at:i.at,heldBecause:i.heldBecause})),n=(r.requests??[]).filter(i=>Lx.has(i.state)).sort((i,o)=>i.createdAt-o.createdAt).map(i=>({id:i.id,title:Re(i,pc).headline,agentId:i.agentId,state:i.state,since:mc(i.stateChangedAt??i.updatedAt)})),s=r.voice;return{ts:mc(r.now),cards:Sr(e),held:Sr(t),voice:s?{paused:s.paused,reserved:s.reserved,playing:s.playing?iy(s.playing):null,waiting:Sr(s.waiting.map(iy))}:null,requests:Sr(n),errors:r.errors??[]}}function ay(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 vc}from"path";_x();var jx={name:"agentx",version:"0.1.0"},Fx=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],Wx="2024-11-05";function Ux(r){return typeof r=="string"&&Fx.includes(r)?r:Wx}var Gx={tools:{},elicitation:{form:{}}},Hx=0;async function cy(r,e){let t=++Hx;return Et({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Jn.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Jn.has(`elicit-${t}`)&&(Jn.delete(`elicit-${t}`),n(null))},6e4)})}var Jn=new Map,qx="http://localhost:18800",yc;function Bx(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=vc(process.cwd(),r);if(!bc(e))continue;let t=JSON.parse(kc(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 qx}function V(){return yc===void 0&&(yc=Bx()),yc}var wc;function Xx(r){try{let e=vc(process.cwd(),".env");if(!bc(e))return"";for(let t of kc(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 Vx(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=Xx("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=vc(process.cwd(),t);if(!bc(n))continue;let s=JSON.parse(kc(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function Jx(){return wc===void 0&&(wc=Vx()),wc}var J=(r,e)=>{let t=Jx();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 Vn(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 Kx(){let r=process.env.AGENTX_AGENT_ID,e=Vn();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await J(`${V()}/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 zx=1e4,Yx=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function Qx(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&Yx.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 Zx=/\x1B\[[0-9;]*[A-Za-z]/g;function nn(r){return r.replace(Zx,"")}async function eA(r,e,t){let n=await J(`${V()}/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:tA(i,!!s.hasMore)}]}}function tA(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}:
@@ -531,7 +531,7 @@ ${l}`)}let $={agentId:o,message:w,context:{channel:g,sender:y?"opencode":"openai
531
531
 
532
532
  `)}}function $w(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Iw(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 Tw(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Xc(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 Xc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new is(`${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(is.levelOrder[e]<is.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)}},rs=is;qt(rs,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as cE,statSync as lE}from"fs";var Ge={version:"0.195.0",commit:"c671742",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function dE(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 Aw(){let r=null;try{r=lE(cE(process.argv[1])).mtimeMs}catch{}let e=Ky().version;return dE(Ge,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as uE}from"crypto";var zr=class{constructor(e=new sg){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!hE.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};pE(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:uE(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=gE(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}},hE=["run","task","signal","mesh","channel","status"];function gE(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 pE(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 Rw(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 Yr,timingSafeEqual as Ew}from"crypto";var Qr=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),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,$]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=$);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.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 d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
534
+ `)}function Tw(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Xc(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 Xc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new is(`${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(is.levelOrder[e]<is.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)}},rs=is;qt(rs,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as cE,statSync as lE}from"fs";var Ge={version:"0.196.0",commit:"ffc3fd8",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function dE(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 Aw(){let r=null;try{r=lE(cE(process.argv[1])).mtimeMs}catch{}let e=Ky().version;return dE(Ge,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as uE}from"crypto";var zr=class{constructor(e=new sg){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!hE.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};pE(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:uE(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=gE(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}},hE=["run","task","signal","mesh","channel","status"];function gE(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 pE(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 Rw(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 Yr,timingSafeEqual as Ew}from"crypto";var Qr=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),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,$]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=$);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.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 d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
535
535
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.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 l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.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 l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}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(d=>d.enabled&&d.agentId===s&&d.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=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+Yr("sha256",a).update(t).digest("hex");return cn(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?cn(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=Yr("sha256",a).update(`${u.t}.${t}`).digest("hex");return cn(h,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)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"]||"",b=e["x-forwarded-host"],w=e.host,$=e["x-forwarded-proto"]||"https",k=new Set;b&&g&&k.add(`${$}://${b}${g}`),w&&g&&k.add(`https://${w}${g}`),w&&g&&k.add(`http://${w}${g}`),g&&k.add(g),k.add("");for(let x of k){let E=Yr("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(d.length===E.length&&Ew(Buffer.from(d),Buffer.from(E)))return null}return`signature mismatch (tried ${k.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let h=Yr("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return cn(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?cn(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?cn(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function cn(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Ew(t,n)?null:"signature mismatch"}zu();Su();qu();xx();function fE(r){return{insertTaskHistory:r.prepare(`
@@ -1356,4 +1356,4 @@ data: ${JSON.stringify(z)}
1356
1356
  `)}catch{}},L=setInterval(()=>{try{t.write(`: ping
1357
1357
 
1358
1358
  `)}catch{}},15e3);L.unref?.();let U=new AbortController;t.on("close",()=>{t.writableEnded||U.abort()});try{for await(let G of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:U.signal,vouchOwner:S}))C(G.event,G.data)}catch(G){C("error",{error:G?.message??String(G)})}finally{clearInterval(L);try{t.end()}catch{}}break}let _=p.context,O=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(iT(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=Lo(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 U=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:U,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let G=p.peer,z=p.agent,he=this.mesh;(async()=>{let W=Date.now(),Y;try{Y=await he.sendTask(G,p.message,z,{vouchOwner:S,context:_,senderAgentId:O}),this.log(`[mesh/task async ${U}] ${G}/${z??"default"} finished in ${Date.now()-W}ms`)}catch(K){Y=`Delegation to ${G}/${z??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${U}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:Y,agentId:_?.agentId??O,accountId:_?.accountId})}catch(K){this.log(`[mesh/task async ${U}] delivery failed: ${K?.message??K}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:_,senderAgentId:O,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 q(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 q(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 q(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()||o1(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:ke(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 q(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 O=this.mesh.directory().find(N=>N.peer===_.peer)?.peerUrl;if(!_.healthy||!O){this.json(t,503,{error:`the node hosting "${v.inbox}" (${_.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${O.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 q(e);await xw(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 l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.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=Wf(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=tb();if(e==="json")return this.registry.getTodayUsage();let t=eb(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||!Rn(n)))try{let s=ee(n,".claude","skills");mx(s,{recursive:!0});let i=ee(s,E0);if(!Rn(i))pu(i,od(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=P0(js(i,"utf-8"),e);o&&(pu(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||!Rn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||dp(this.config.workflows,e)),i=Ag(Dh(t),this.config.requests.enabled||s?xg():null);try{switch(Rg(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 t0(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 ne(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 d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.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 ne(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 kf(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await ne(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.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 l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-NR7SLHGX.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=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:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.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:${d.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 ne(e)}catch{s={}}try{let i=await R0({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})}}},fu=mu;qt(fu,"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 o1(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 ne(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 a1(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 q(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)})}function yx(r){let e=r.business;return JSON.stringify([e?.roles,e?.orgChart,e?.relations,e?.projects,(r.people??[]).map(t=>t.id)])}wx();function WQ(r){typeof r=="string"&&(Fs.error(r),process.exit(1)),r instanceof Error&&(Fs.error(r.message),process.exit(1)),Fs.error("Something went wrong. Please try again."),process.exit(1)}export{x1 as a,Sc as b,Ct as c,zn as d,Qn as e,Mt as f,Mr as g,Ky as h,Gw as i,TE as j,xE as k,Vw as l,Ce as m,zw as n,Yw as o,ei as p,bG as q,kG as r,pi as s,jH as t,FP as u,WP as v,ml as w,Vb as x,FH as y,sk as z,GP as A,rk as B,ik as C,ok as D,WH as E,UH as F,GH as G,vi as H,h_ as I,Lk as J,Me as K,dB as L,aM as M,Fv as N,Wv as O,JM as P,sS as Q,aS as R,NO as S,Zl as T,rX as U,iX as V,oX as W,d0 as X,pD as Y,uX as Z,hX as _,$0 as $,bs as aa,wn as ba,ks as ca,zX as da,J0 as ea,SN as fa,GV as ga,ao as ha,bd as ia,kd as ja,go as ka,ke as la,B$ as ma,xs as na,TL as oa,iI as pa,AL as qa,lI as ra,ko as sa,Es as ta,Io as ua,xo as va,fI as wa,Nd as xa,SI as ya,yt as za,Ae as Aa,Bd as Ba,RI as Ca,EI as Da,CI as Ea,PI as Fa,Bo as Ga,AT as Ha,iu as Ia,ET as Ja,dF as Ka,fK as La,fu as Ma,WQ as Na};
1359
- //# sourceMappingURL=chunk-XQF7UUZK.js.map
1359
+ //# sourceMappingURL=chunk-NT3DGEBE.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ge,b as k,c as D,d as Ve,e as ue,f as me,g as L,h as fe,i as N,j,n as Qe,o as Ze,p as ea,q as aa}from"./chunk-EFGAPAYZ.js";import{e as Je,i as Xe}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Ye}from"./chunk-PX7PWXBI.js";import{Ia as Be,Ja as Ue,Ka as Fe,Ma as qe,ja as $,oa as We,wb as Ke}from"./chunk-I45E5TLK.js";import{a as G}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as je}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-PO2SORKY.js";import{b as pe}from"./chunk-3FZ6WHKX.js";import{a as q,b as J}from"./chunk-KXJRXRSD.js";import{a as Me}from"./chunk-RW5FKJRE.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ib as ce,Va as ze,ab as Qa,fa as de,ga as Ie,qa as Va,vb as le,yb as F,zb as Ee}from"./chunk-P6WSD2UR.js";import{existsSync as K,readFileSync as la,writeFileSync as ca,appendFileSync as it,mkdirSync as st}from"fs";import{dirname as dt,resolve as M}from"path";import{fileURLToPath as lt}from"url";import{hostname as ct}from"os";import{spawn as pt}from"child_process";var he=`:root {
1
+ import{a as Ge,b as k,c as D,d as Ve,e as ue,f as me,g as L,h as fe,i as N,j,n as Qe,o as Ze,p as ea,q as aa}from"./chunk-EFGAPAYZ.js";import{e as Je,i as Xe}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Ye}from"./chunk-PX7PWXBI.js";import{Ia as Be,Ja as Ue,Ka as Fe,Ma as qe,ja as $,oa as We,wb as Ke}from"./chunk-YWAJNF2A.js";import{a as G}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as je}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-PO2SORKY.js";import{b as pe}from"./chunk-3FZ6WHKX.js";import{a as q,b as J}from"./chunk-KXJRXRSD.js";import{a as Me}from"./chunk-RW5FKJRE.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ib as ce,Va as ze,ab as Qa,fa as de,ga as Ie,qa as Va,vb as le,yb as F,zb as Ee}from"./chunk-P6WSD2UR.js";import{existsSync as K,readFileSync as la,writeFileSync as ca,appendFileSync as it,mkdirSync as st}from"fs";import{dirname as dt,resolve as M}from"path";import{fileURLToPath as lt}from"url";import{hostname as ct}from"os";import{spawn as pt}from"child_process";var he=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2889,7 +2889,7 @@ tr:hover td { background: var(--bg-hover); }
2889
2889
  </div>`}o+=d.length}}return o===0&&(n+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${p(a)}</code>.</p>`),A(`Tag: ${a}`,P(r),n)}function Jt(e,a,t,r){let n=r||e.summary(),o;try{o=e.getAgentWiki(a)}catch{return A(`Tag: ${t}`,P(n),`<h1>Agent not found: ${p(a)}</h1>`)}let i=o.findByTags([t],void 0,100),s=`/agent/${encodeURIComponent(a)}`,d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${s}">${p(a)}</a> <span class="sep">/</span> <span class="current">${p(t)}</span></nav>`;d+=`<div class="page-head"><div><h1>${p(t)}</h1><p class="page-sub">${i.length} article${i.length===1?"":"s"} tagged <code>${p(t)}</code> in <b>${p(a)}</b>.</p></div></div>`;for(let l of i)d+=`<div class="entry-card">
2890
2890
  <div class="meta-line">${H((l.meta.tags||[]).slice(0,6),a)}</div>
2891
2891
  <h3><a href="${s}/article/${encodeURIComponent(l.path)}">${p(l.meta.title)}</a></h3>
2892
- </div>`;return A(`${a} \xB7 ${t}`,P(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=$e(r.articles.map(i=>({title:i.title,path:i.path,tags:i.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${p(a)}</div>`,o+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of n){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${Se(i)}</div>`;for(let d of s){let l=d.path===t;o+=`<a class="nav-item${l?" active":""}" href="/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}o+="</div>"}return o}function Xt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Me(a,void 0,n),d=new ne(s,a),l=r.length>0?new te(r):null;return async(c,m)=>{let g=new URL(c.url||"/","http://localhost"),u=decodeURIComponent(g.pathname),x=i&&u.startsWith(i)?u.slice(i.length)||"/":u,f=null,C=200;try{if(x.startsWith("/remote/")&&l){let w=x.slice(8).split("/article/");if(w.length===2){let[v,b]=w,h=v.indexOf("/"),_=decodeURIComponent(v.slice(0,h)),y=v.slice(h+1),S=await l.getRemoteArticle(_,y,b);if(S){let O=await l.getRemoteAgents(),Y=[...s.summary(),...O.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],T=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(y)} @ ${p(_)}</div>`;T+=`<h1>${p(S.meta.title)}</h1>`,T+='<dl class="meta">',T+=`<dt>Tags</dt><dd>${(S.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,T+=`<dt>Owner</dt><dd>${p(S.meta.owner)}</dd>`,T+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(_)}</dd>`,T+=`<dt>Updated</dt><dd>${S.meta.lastUpdated}</dd>`,T+="</dl>";let R=new Map;T+=oe(S.content,R),f=A(S.meta.title,P(Y),T)}}}if(!f&&t){let w=s.getAgentWiki(t);if(x==="/"||x===""){let v=w.rebuildIndex(),b=s.getAgentEntries(t),h=`<h1>${p(t)}</h1>`;if(h+='<div class="stats">',h+=`<div class="stat-card"><div class="number">${v.articles.length}</div><div class="label">Articles</div></div>`,h+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,h+="</div>",v.articles.length>0){h+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let _ of v.articles)h+=`<tr><td><a href="/article/${encodeURIComponent(_.path)}">${p(_.title)}</a></td><td><span class="tag">${(_.tags||[]).slice(0,3).join(", ")}</span></td><td>${_.lastUpdated||""}</td></tr>`;h+="</table>"}f=A(t,B(w,t),h)}else if(x.startsWith("/article/")){let v=x.slice(9),b=w.readArticle(v);if(b){let h=w.rebuildIndex(),_=new Map;for(let S of h.articles)_.set(S.title,S.path);let y=`<h1>${p(b.meta.title)}</h1>`;y+='<dl class="meta">',y+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,y+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(y+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),y+="</dl>",y+=oe(b.content,_),f=A(b.meta.title,B(w,t,v),y)}}else if(x==="/lint"){let v=w.lint(),b="<h1>Health Check</h1>";if(v.length===0)b+='<p style="color:green;">No issues.</p>';else{b+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let h of v)b+=`<tr><td><span class="tag">${h.type}</span></td><td>${p(h.article)}</td><td>${p(h.message)}</td></tr>`;b+="</table>"}f=A("Health Check",B(w,t),b)}else if(x==="/search"){let v=g.searchParams.get("q")||"",b=await w.findRelevantReranked(v,void 0,20),h=`<h1>Search: "${p(v)}"</h1>`;for(let _ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(_.path)}">${p(_.meta.title)}</a></h3><p>${p(_.content.slice(0,200))}...</p></div>`;b.length===0&&(h+="<p>No results.</p>"),f=A(`Search: ${v}`,B(w,t),h)}else if(x.startsWith("/tag/")){let v=decodeURIComponent(x.slice(5)),b=w.findByTags([v],void 0,100),h=`<h1>Tag: <a class="tag" href="#">${p(v)}</a></h1>`;h+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(v)}</code></p>`;for(let _ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(_.path)}">${p(_.meta.title)}</a></h3><div class="meta-line">${H((_.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=A(`Tag: ${v}`,B(w,t),h)}}else if(!f&&(f=d.handle(x,g.searchParams))===null){let w=l?await l.getRemoteAgents():[],v=s.summary(),b=new Map(v.map(y=>[y.agentId,y])),h=[],_=new Set;for(let y of v){let S=w.find(O=>O.agentId===y.agentId);S&&S.totalArticles>y.totalArticles?h.push({...S,totalEntries:Math.max(y.totalEntries,S.totalEntries),unabsorbed:Math.max(y.unabsorbed,S.unabsorbed)}):h.push(y),_.add(y.agentId)}for(let y of w)_.has(y.agentId)||(h.push(y),_.add(y.agentId));if(x==="/agents")f=Bt(s,h,w);else if(x==="/entries")f=qt(s,h);else if(x==="/search")f=Kt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Yt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let y=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Jt(s,decodeURIComponent(y[1]),decodeURIComponent(y[2]),h)}else if(x.startsWith("/agent/")){let y=x.slice(7),S=y.indexOf("/article/");if(S===-1)f=Ut(s,y,h);else{let O=y.slice(0,S),Y=y.slice(S+9);if(f=Ft(s,O,Y,h),!f&&l){let T=w.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,Y);if(R){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(T.nodeId)}</span> / ${p(O)}</div>`;I+=`<h1>${p(R.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(R.meta.tags||[]).map(Ga=>`<span class="tag">${Ga}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(T.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${R.meta.lastUpdated}</dd>`,I+="</dl>",I+=oe(R.content,new Map),f=A(R.meta.title,P(h),I)}}}}}}if(!f){C=404;let w=t?B(s.getAgentWiki(t),t):P(s.summary());f=A("Not Found",w,"<h1>Page not found</h1>")}}catch(w){C=500,f=A("Error","",`<h1>Error</h1><pre>${p(w.message)}</pre>`)}if(C===200&&e.curator){let w=Gt(s,d,x,t);w&&(f=Ta(f,w,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?Vt(f,i):f)}}function Gt(e,a,t,r){let n,o;if(r&&t.startsWith("/article/"))n=r,o=t.slice(9);else if(!r&&t.startsWith("/agent/")){let d=t.match(/^\/agent\/([^/]+)\/article\/(.+)$/);d&&(n=d[1],o=d[2])}else if(!r)return a.pageAt(t);if(!n||!o||!e.listAgents([]).includes(n))return null;let i=e.getAgentWiki(n);if(!je(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function Vt(e,a){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${a}/`),e=e.replace(new RegExp(`(${a})${a}/`,"g"),`${a}/`);let t=`<a href="/admin" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${t}`),e}function go(e,a=4200,t,r=[],n="graph"){let o=Xt({wikiDir:e,agentFilter:t,peers:r,mode:n});Ht((s,d)=>{o(s,d)}).listen(a)}import{existsSync as Qt,readFileSync as Zt}from"fs";ce();function vo(e){let a=q(e),t={};if(Qt(a))try{t=F(JSON.parse(Zt(a,"utf-8")))}catch{t={}}let r=t?.workflows?.required??{},n={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(n[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:X.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:X.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:X.retentionDays,engine:t?.workflows?.enabled===!0}}async function wo(e,a={}){return e.retentionDays!==void 0&&!(Number.isInteger(e.retentionDays)&&e.retentionDays>=0&&e.retentionDays<=3650)?{success:!1,error:"retentionDays is a whole number of days from 0 to 3650"}:e.agent&&!/^[A-Za-z0-9_.@-]{1,80}$/.test(e.agent.id)?{success:!1,error:`"${e.agent.id}" is not an agent id`}:J(t=>{let r=t.workflows??={},n=r.required??={};if(e.enabled!==void 0&&(n.enabled=e.enabled),e.exemptQuestions!==void 0&&(n.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(n.retentionDays=e.retentionDays),e.agent){let o=n.agents??={};e.agent.value===null?delete o[e.agent.id]:o[e.agent.id]=e.agent.value}(e.enabled===!0||e.agent?.value===!0)&&(r.enabled=!0)},{configPath:a.configPath,reload:a.reload})}var er={"claude-code":{bin:"claude",login:"Install Claude Code (https://claude.com/claude-code) and run `claude` once to log in"},"codex-cli":{bin:"codex",login:"Install Codex CLI and run `codex login`"},opencode:{bin:"opencode",login:"Install OpenCode and run `opencode auth login`"}};function ar(e){if(typeof e!="string")return null;let a=e.match(/^\$\{(\w+)\}$/);return a?a[1]:null}function ko(e){let a=e.rawConfig?.agents?.[e.agentId];if(!a)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let t=String(a.tier||""),r=er[t];if(r)return e.hasBinary(r.bin)?e.cliLoggedIn?.(r.bin)===!1?{ready:!1,need:"cli",cli:r.bin,hint:`${r.bin} is installed but not logged in. In a terminal, run \`${r.bin}\` once and log in, then press Check again.`}:{ready:!0}:{ready:!1,need:"cli",cli:r.bin,hint:`${r.login}, then press Check again.`};if(t==="sdk"||t==="orchestrator"){let n=a.provider||(t==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[n];if(t==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=ar(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${n}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${n}.apiKey in agentx.json.`}}return{ready:!0}}import{appendFileSync as tr,chmodSync as rr,existsSync as za,readFileSync as Ea,writeFileSync as nr}from"fs";function or(e){return za(e)?Object.fromEntries(Pe(Ea(e,"utf-8"))):{}}function Ao(e,a,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(a))throw new Error(`not an environment variable name: ${a}`);if(!t||/[\r\n]/.test(t))throw new Error("the value must be one non-empty line");if(or(e)[a])return!1;if(!za(e))return nr(e,`# AgentX environment variables
2892
+ </div>`;return A(`${a} \xB7 ${t}`,P(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=$e(r.articles.map(i=>({title:i.title,path:i.path,tags:i.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${p(a)}</div>`,o+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of n){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${Se(i)}</div>`;for(let d of s){let l=d.path===t;o+=`<a class="nav-item${l?" active":""}" href="/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}o+="</div>"}return o}function Xt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Me(a,void 0,n),d=new ne(s,a),l=r.length>0?new te(r):null;return async(c,m)=>{let g=new URL(c.url||"/","http://localhost"),u=decodeURIComponent(g.pathname),x=i&&u.startsWith(i)?u.slice(i.length)||"/":u,f=null,C=200;try{if(x.startsWith("/remote/")&&l){let w=x.slice(8).split("/article/");if(w.length===2){let[v,b]=w,h=v.indexOf("/"),_=decodeURIComponent(v.slice(0,h)),y=v.slice(h+1),S=await l.getRemoteArticle(_,y,b);if(S){let O=await l.getRemoteAgents(),Y=[...s.summary(),...O.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],T=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(y)} @ ${p(_)}</div>`;T+=`<h1>${p(S.meta.title)}</h1>`,T+='<dl class="meta">',T+=`<dt>Tags</dt><dd>${(S.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,T+=`<dt>Owner</dt><dd>${p(S.meta.owner)}</dd>`,T+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(_)}</dd>`,T+=`<dt>Updated</dt><dd>${S.meta.lastUpdated}</dd>`,T+="</dl>";let R=new Map;T+=oe(S.content,R),f=A(S.meta.title,P(Y),T)}}}if(!f&&t){let w=s.getAgentWiki(t);if(x==="/"||x===""){let v=w.rebuildIndex(),b=s.getAgentEntries(t),h=`<h1>${p(t)}</h1>`;if(h+='<div class="stats">',h+=`<div class="stat-card"><div class="number">${v.articles.length}</div><div class="label">Articles</div></div>`,h+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,h+="</div>",v.articles.length>0){h+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let _ of v.articles)h+=`<tr><td><a href="/article/${encodeURIComponent(_.path)}">${p(_.title)}</a></td><td><span class="tag">${(_.tags||[]).slice(0,3).join(", ")}</span></td><td>${_.lastUpdated||""}</td></tr>`;h+="</table>"}f=A(t,B(w,t),h)}else if(x.startsWith("/article/")){let v=x.slice(9),b=w.readArticle(v);if(b){let h=w.rebuildIndex(),_=new Map;for(let S of h.articles)_.set(S.title,S.path);let y=`<h1>${p(b.meta.title)}</h1>`;y+='<dl class="meta">',y+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,y+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(y+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),y+="</dl>",y+=oe(b.content,_),f=A(b.meta.title,B(w,t,v),y)}}else if(x==="/lint"){let v=w.lint(),b="<h1>Health Check</h1>";if(v.length===0)b+='<p style="color:green;">No issues.</p>';else{b+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let h of v)b+=`<tr><td><span class="tag">${h.type}</span></td><td>${p(h.article)}</td><td>${p(h.message)}</td></tr>`;b+="</table>"}f=A("Health Check",B(w,t),b)}else if(x==="/search"){let v=g.searchParams.get("q")||"",b=await w.findRelevantReranked(v,void 0,20),h=`<h1>Search: "${p(v)}"</h1>`;for(let _ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(_.path)}">${p(_.meta.title)}</a></h3><p>${p(_.content.slice(0,200))}...</p></div>`;b.length===0&&(h+="<p>No results.</p>"),f=A(`Search: ${v}`,B(w,t),h)}else if(x.startsWith("/tag/")){let v=decodeURIComponent(x.slice(5)),b=w.findByTags([v],void 0,100),h=`<h1>Tag: <a class="tag" href="#">${p(v)}</a></h1>`;h+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(v)}</code></p>`;for(let _ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(_.path)}">${p(_.meta.title)}</a></h3><div class="meta-line">${H((_.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=A(`Tag: ${v}`,B(w,t),h)}}else if(!f&&(f=d.handle(x,g.searchParams))===null){let w=l?await l.getRemoteAgents():[],v=s.summary(),b=new Map(v.map(y=>[y.agentId,y])),h=[],_=new Set;for(let y of v){let S=w.find(O=>O.agentId===y.agentId);S&&S.totalArticles>y.totalArticles?h.push({...S,totalEntries:Math.max(y.totalEntries,S.totalEntries),unabsorbed:Math.max(y.unabsorbed,S.unabsorbed)}):h.push(y),_.add(y.agentId)}for(let y of w)_.has(y.agentId)||(h.push(y),_.add(y.agentId));if(x==="/agents")f=Bt(s,h,w);else if(x==="/entries")f=qt(s,h);else if(x==="/search")f=Kt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Yt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let y=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Jt(s,decodeURIComponent(y[1]),decodeURIComponent(y[2]),h)}else if(x.startsWith("/agent/")){let y=x.slice(7),S=y.indexOf("/article/");if(S===-1)f=Ut(s,y,h);else{let O=y.slice(0,S),Y=y.slice(S+9);if(f=Ft(s,O,Y,h),!f&&l){let T=w.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,Y);if(R){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(T.nodeId)}</span> / ${p(O)}</div>`;I+=`<h1>${p(R.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(R.meta.tags||[]).map(Ga=>`<span class="tag">${Ga}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(T.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${R.meta.lastUpdated}</dd>`,I+="</dl>",I+=oe(R.content,new Map),f=A(R.meta.title,P(h),I)}}}}}}if(!f){C=404;let w=t?B(s.getAgentWiki(t),t):P(s.summary());f=A("Not Found",w,"<h1>Page not found</h1>")}}catch(w){C=500,f=A("Error","",`<h1>Error</h1><pre>${p(w.message)}</pre>`)}if(C===200&&e.curator){let w=Gt(s,d,x,t);w&&(f=Ta(f,w,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?Vt(f,i):f)}}function Gt(e,a,t,r){let n,o;if(r&&t.startsWith("/article/"))n=r,o=t.slice(9);else if(!r&&t.startsWith("/agent/")){let d=t.match(/^\/agent\/([^/]+)\/article\/(.+)$/);d&&(n=d[1],o=d[2])}else if(!r)return a.pageAt(t);if(!n||!o||!e.listAgents([]).includes(n))return null;let i=e.getAgentWiki(n);if(!je(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function Vt(e,a){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${a}/`),e=e.replace(new RegExp(`(${a})${a}/`,"g"),`${a}/`);let t=`<a href="/hub" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${t}`),e}function go(e,a=4200,t,r=[],n="graph"){let o=Xt({wikiDir:e,agentFilter:t,peers:r,mode:n});Ht((s,d)=>{o(s,d)}).listen(a)}import{existsSync as Qt,readFileSync as Zt}from"fs";ce();function vo(e){let a=q(e),t={};if(Qt(a))try{t=F(JSON.parse(Zt(a,"utf-8")))}catch{t={}}let r=t?.workflows?.required??{},n={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(n[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:X.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:X.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:X.retentionDays,engine:t?.workflows?.enabled===!0}}async function wo(e,a={}){return e.retentionDays!==void 0&&!(Number.isInteger(e.retentionDays)&&e.retentionDays>=0&&e.retentionDays<=3650)?{success:!1,error:"retentionDays is a whole number of days from 0 to 3650"}:e.agent&&!/^[A-Za-z0-9_.@-]{1,80}$/.test(e.agent.id)?{success:!1,error:`"${e.agent.id}" is not an agent id`}:J(t=>{let r=t.workflows??={},n=r.required??={};if(e.enabled!==void 0&&(n.enabled=e.enabled),e.exemptQuestions!==void 0&&(n.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(n.retentionDays=e.retentionDays),e.agent){let o=n.agents??={};e.agent.value===null?delete o[e.agent.id]:o[e.agent.id]=e.agent.value}(e.enabled===!0||e.agent?.value===!0)&&(r.enabled=!0)},{configPath:a.configPath,reload:a.reload})}var er={"claude-code":{bin:"claude",login:"Install Claude Code (https://claude.com/claude-code) and run `claude` once to log in"},"codex-cli":{bin:"codex",login:"Install Codex CLI and run `codex login`"},opencode:{bin:"opencode",login:"Install OpenCode and run `opencode auth login`"}};function ar(e){if(typeof e!="string")return null;let a=e.match(/^\$\{(\w+)\}$/);return a?a[1]:null}function ko(e){let a=e.rawConfig?.agents?.[e.agentId];if(!a)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let t=String(a.tier||""),r=er[t];if(r)return e.hasBinary(r.bin)?e.cliLoggedIn?.(r.bin)===!1?{ready:!1,need:"cli",cli:r.bin,hint:`${r.bin} is installed but not logged in. In a terminal, run \`${r.bin}\` once and log in, then press Check again.`}:{ready:!0}:{ready:!1,need:"cli",cli:r.bin,hint:`${r.login}, then press Check again.`};if(t==="sdk"||t==="orchestrator"){let n=a.provider||(t==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[n];if(t==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=ar(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${n}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${n}.apiKey in agentx.json.`}}return{ready:!0}}import{appendFileSync as tr,chmodSync as rr,existsSync as za,readFileSync as Ea,writeFileSync as nr}from"fs";function or(e){return za(e)?Object.fromEntries(Pe(Ea(e,"utf-8"))):{}}function Ao(e,a,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(a))throw new Error(`not an environment variable name: ${a}`);if(!t||/[\r\n]/.test(t))throw new Error("the value must be one non-empty line");if(or(e)[a])return!1;if(!za(e))return nr(e,`# AgentX environment variables
2893
2893
  # (Never commit this file: it contains secrets.)
2894
2894
 
2895
2895
  ${a}=${t}
@@ -2903,4 +2903,4 @@ ${a}=${t}
2903
2903
  WHERE person = ? AND state IN (${t.map(()=>"?").join(",")})
2904
2904
  ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function ti(e,a){return Ba(e,a,de,"ORDER BY created_at")}function ri(e,a,t=50){return Ba(e,a,[...de,...Ie],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Qa();var Te="member:",xr=90,gr="members",ur="tailscale-user-login",mr=400,fr=60*60*1e3;function hr(e){let a=e.scopes.find(t=>t.startsWith(Te));return a?a.slice(Te.length):null}function Fa(e,a){if(!e)return null;let t=a.verify(e),r=t?hr(t):null;return t&&r?{rec:t,personId:r}:null}function ci(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${Te}${t.id}`],expiresInDays:xr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var br=Math.round(He/6e4);function vr(e){return e==="client"?"Your project":"My work"}function pi(e){let a=vr(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${Le(e.code)}`,` The code works once, for ${br} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
2905
2905
  `)}var wr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",yr="Too many machines are waiting for the owner's answer. Try again later.",Ua="That code didn't work. Check it, or ask the person who invited you for a new one.",qa=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ka(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function kr(e){if(!Ka(e))return null;let a=qa(e,ur).toLowerCase();return a?a.slice(0,80):null}function _r(e){let a=e.socket?.remoteAddress||"unknown";if(!Ka(e))return a;let t=qa(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Sr(e){return e.identities.map(ze).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function xi(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=_r(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await V(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?Fa(l.token,a.tokens):null;if(await Cr(t,a.minMs??mr),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Ua}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Ua}};let x=kr(e),f=Sr(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:wr}};let C=d||"Unnamed machine",w=u.name.slice(0,40),v=Ne(a.root,{title:`New machine for ${w}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${w}'s own work?`,recommend:`Yes if ${w} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:gr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:yr}})}var se="this machine is not paired",Ar="waiting for the owner to approve this machine";function Ya(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function gi(e,a){return a.state==="pending"&&a.cardId?Ya(xe(e,a.cardId)):null}function ui(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=Fa(e,a.tokens);if(!o)return{ok:!1,status:401,error:se};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:se};if(a.people&&!a.people().some(c=>c.id===s))return Ja(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:se};if(d.state==="pending"){let c=d.cardId?xe(a.root,d.cardId):null,m=Ya(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:se}}else return{ok:!1,status:403,error:Ar,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=fr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Ja(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function mi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Ja(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Xa=["gitlab","github"];function Tr(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Xa.includes(r))throw new Error(`Request status works on ${Xa.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function bi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function vi(e){let{summary:a}=Q(t=>Tr(t,e?.channel,!!e?.enabled));return{summary:a}}var yi="https://myaccount.google.com/apppasswords";function ki(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function _i(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function $i(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ci(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ti(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Ii(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Ir="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Ir,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pi(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}export{he as a,oa as b,ve as c,at as d,tt as e,rt as f,pa as g,xt as h,$n as i,Sn as j,An as k,ko as l,or as m,Ao as n,zo as o,Wa as p,Vo as q,Qo as r,Rn as s,On as t,At as u,It as v,we as w,Dn as x,Mn as y,zt as z,Bn as A,Un as B,Fn as C,ai as D,ti as E,ri as F,xr as G,ci as H,br as I,vr as J,pi as K,_r as L,xi as M,gi as N,ui as O,Ja as P,mi as Q,Xa as R,Tr as S,bi as T,vi as U,yi as V,ki as W,_i as X,$i as Y,Ai as Z,Ci as _,Ti as $,Ii as aa,Ei as ba,Pi as ca,Xt as da,go as ea,vo as fa,wo as ga};
2906
- //# sourceMappingURL=chunk-OEG476JY.js.map
2906
+ //# sourceMappingURL=chunk-V7FZBETJ.js.map