agentix-cli 0.177.0 → 0.178.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 er,A as Wp,Aa as La,B as Up,Ba as _f,C as Xt,Ca as Fa,D as Vs,Da as kt,E as Gp,Ea as Uf,F as Hp,Fa as Gf,G as Bp,H as Kp,I as zp,Ia as vt,Ib as Ga,J as Yp,Ja as Hf,Jb as Ha,K as Qp,Ka as Bf,L as Zp,La as qf,Lb as um,M as ef,Ma as Xf,N as tf,Na as Vf,O as nf,Oa as Jf,P as sf,Q as rf,Qa as ve,R as _a,Ra as Qs,Sa as Wa,Ta as Kf,U as of,Ua as On,Va as zf,W as af,Wa as Oe,Xa as Yf,Ya as Qf,Za as Zf,_a as Zs,a as mp,ab as em,b as $a,ba as zs,bb as tm,ca as vf,ea as Sf,f as Ia,fa as Oa,g as yp,gb as nm,h as wp,i as Ta,ia as $f,j as bp,k as Mn,ka as If,kb as sm,l as kp,m as vp,mb as tr,n as Sp,na as Tf,nb as Ua,o as Qe,oa as xf,ob as rm,p as $p,pa as Af,pb as im,q as Ip,qa as Da,qb as om,ra as Rf,rb as am,s as Tp,ta as Ef,tb as cm,u as xp,ua as Na,v as Ze,va as Cf,w as Aa,wa as et,x as Lp,xa as Pf,y as jp,ya as Ys,yb as dm,z as Fp,zb as lm}from"./chunk-FZMS4UFL.js";import{d as gp,g as pp,h as fp}from"./chunk-YIR6FABW.js";import{a as Ap}from"./chunk-ZVP6GB4G.js";import{A as Pp,B as _p,D as Bs,E as Ra,F as qs,G as qt,K as cf,c as Jg,d as Kg,f as zg,g as _n,h as Hs,i as ka,j as Yg,k as Ke,z as Cp}from"./chunk-6FNJ7GQ2.js";import{b as Mf,c as Of,d as ja,e as Df,f as Nf,g as Lf,h as jf,i as Ff}from"./chunk-EKJG63EJ.js";import{b as Wf}from"./chunk-N6VBEITO.js";import{d as Mp}from"./chunk-6V5JBHUN.js";import{g as Op}from"./chunk-LQE73AZR.js";import{b as Dp,c as Np}from"./chunk-2D3RYIDU.js";import{b as df}from"./chunk-MRIVENBY.js";import{i as lf,m as Ma,n as uf,p as hf,q as gf,r as pf,s as ff,t as mf,u as yf}from"./chunk-FRR6DRLY.js";import{e as Ea,k as Ca,l as qp,m as Js,n as bt,o as Vt,p as Me,r as Xp,s as Vp,t as Jp,u as Pa,v as Ks}from"./chunk-LQS27HSV.js";import{a as wf}from"./chunk-PPUN7YHA.js";import{a as bf,b as kf}from"./chunk-VZLIBDLH.js";import{a as Rp,b as Ep}from"./chunk-A5GYG56I.js";import{o as xa}from"./chunk-3X2BFCOZ.js";import{b as Xs}from"./chunk-UKUH662W.js";import{a as Ye}from"./chunk-MNG2AMKZ.js";import{c as rp,d as ip,f as op,g as ap,i as cp,k as dp,l as lp}from"./chunk-RX5O5637.js";import{b as up,c as hp}from"./chunk-X7UQY7CH.js";import{a as va,b as Qg,c as Zg}from"./chunk-QPABR72X.js";import{a as ep,b as ze,c as tp,d as np,e as sp}from"./chunk-AJ5HMDRW.js";import{c as Bt}from"./chunk-KP7KDLZ2.js";import{$ as wa,A as B,C as Ah,D as Rh,E as Eh,F as Ch,G as ge,H as _h,I as Mh,J as Oh,K as Dh,L as Bh,M as qh,N as Xh,O as Mg,P as Og,Q as Dg,R as Ng,S as Lg,T as jg,V as Pn,W as Fg,Z as ie,_ as Je,a as Yu,aa as Ut,b as ia,ba,c as Zu,ca as Us,d as ah,da as Gt,e as ch,ea as Ht,f as An,fa as me,ga as wt,h as aa,ha as oe,i as ca,ia as Wg,j as da,ja as Ug,k as la,l as dh,ma as Bg,s as uh,t as fh,u as mt,v as mh,w as yh,x as wh,xa as qg,y as Wt,z as vh}from"./chunk-XWDZ37QZ.js";import{$ as vg,Da as Hg,G as Gh,H as Hh,N as Vh,P as Jh,R as dg,S as lg,T as mg,U as yg,V as wg,W as bg,Y as ya,Z as Ws,_ as kg,a as hh,aa as Sg,ba as $g,c as bh,ca as Ig,d as kh,da as Tg,e as yt,ea as xg,f as _e,fa as Ag,h as Nh,ha as Rg,i as Lh,j as jh,k as ha,ka as Eg,l as Fh,m as Wh,p as Uh,pa as Cg,q as Ls,qa as Pg,ta as _g,xa as Gg}from"./chunk-M4BNVLGJ.js";import{a as ua,b as ph}from"./chunk-MEFPXHQJ.js";import{A as Xg,B as Gs,C as Vg,h as Gl,n as Hl,o as jo}from"./chunk-SRX5O2BY.js";import{b as Fl}from"./chunk-SFQUP3BP.js";import{a as Sa}from"./chunk-6TTGRTDO.js";import{a as Kh,b as ga,c as zh,d as Yh,e as Qh,i as Zh,j as eg}from"./chunk-VE3SSOQX.js";import{b as Ph}from"./chunk-W4YR2RO2.js";import{b as ng,c as sg,d as pa,f as js,g as rg,h as ig,i as og,j as Cn,k as Fs,m as fa,n as ag,o as cg}from"./chunk-VJVXEVZ7.js";import{b as he,d as Be,f as qe,g as Rn,i as fe,j as tg,k as Xe,l as Ve,m as gg,p as pg,r as fg,t as ma}from"./chunk-CVFQA3TH.js";import{a as ug,b as hg}from"./chunk-KUZATIJA.js";import{b as gh}from"./chunk-PE5V2LI7.js";import{d as Sh,e as $h,f as Ih,g as Th,h as xh,j as En}from"./chunk-X5C5W3E4.js";import{c as Ns}from"./chunk-OWNQ2FD4.js";import{c as lh}from"./chunk-LUOW2YHY.js";import{d as ql,e as eT,m as Vu,n as gT,q as Ju,v as Ku,x as ra,y as He,z as xn}from"./chunk-FXMUUDSH.js";import{a as Pe,b as Tn,f as Os}from"./chunk-72SZI2UW.js";import{a as Sn,b as Bl}from"./chunk-FCPTN6NF.js";import{c as zu}from"./chunk-MYVHVJWZ.js";import{f as Qu}from"./chunk-QUFIUXMQ.js";import{d as eh,e as th,f as oa,g as Ds,h as nh,i as sh,j as rh,k as ih,q as oh}from"./chunk-AV7T3SYT.js";import{o as Lo,p as ZI}from"./chunk-DCIYOPJF.js";import{a as Ts,b as QI}from"./chunk-7I7IEX4S.js";import{b as Wl,e as Ul}from"./chunk-JHCI6XCJ.js";import{e as ut}from"./chunk-DSYKYZMT.js";import{Aa as Lu,B as Bo,Ba as In,C as nu,Ca as ju,D as su,Da as Fu,E as $n,Ea as Wu,F as Cs,Fa as Uu,G as ru,Ga as Gu,H as iu,Ha as dT,I as mu,J as oT,K as yu,Ka as Hu,M as Jo,N as wu,Na as Bu,O as bu,Oa as qu,P as aT,Q as ku,R as cT,Sa as lT,T as pt,U as vu,Ua as na,W as Ko,Wa as uT,X as zo,Y as Ge,Z as Ft,_ as Su,aa as Yo,ba as Qo,ca as $u,da as Iu,f as jt,fa as Tu,g as Vl,ga as xu,h as Wo,ha as ft,i as tT,ia as Zo,j as xs,ja as Au,k as Uo,ka as Ru,l as As,la as Ps,ma as Eu,n as ht,na as _s,o as Go,oa as Cu,p as Jl,pa as Pu,pb as sa,q as nT,qa as _u,r as Rs,ra as Mu,rb as Xu,s as sT,sa as ea,t as Es,ta,u as Kl,v as rT,va as Ms,w as zl,wa as Ou,x as Yl,y as Ql,ya as Du,yb as hT,za as Nu}from"./chunk-P7FSTC5E.js";import{a as Zl,e as gt,f as eu,g as tu,h as Ho}from"./chunk-VJ5HC63R.js";import{a as ou,b as au,c as cu,e as du,f as lu,i as iT,j as qo,k as uu,l as hu,m as Xo,n as gu,o as pu,q as Vo,r as fu}from"./chunk-UEEB3UTU.js";import{b as Fo,e as Xl}from"./chunk-VQRY4IDI.js";import{d as Lt}from"./chunk-QIJLFPWE.js";import{existsSync as za,readFileSync as Ya}from"fs";Ql();var hm=["answer","narration","line"],gm=5e3;function pm(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function fm(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let d=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!d||!l||!hm.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${hm.join(" | ")}`}};if(d.length>gm)return{status:413,body:{error:`text is over ${gm} characters`}};let h=e(l);if(!h)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:f,done:y}=r.enqueue({voice:h,text:d,agentId:l,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:f}}:{status:200,body:{item:f,played:await y}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,o,a,c]=n.split("/");if(t!=="POST"||!o||c!==void 0)return{status:404,body:{error:"Not found"}};switch(a){case"skip":return r.skip(o)?{status:200,body:r.view()}:Ba(o);case"front":return r.front(o)?{status:200,body:r.view()}:Ba(o);case"replay":{let d=r.replay(o);return d?{status:202,body:{item:d}}:Ba(o)}default:return{status:404,body:{error:"Not found"}}}}function mm(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`,t=r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.";return[...r.floor?.held?[Yl(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$a as er,A as Wp,Aa as La,B as Up,Ba as _f,C as Xt,Ca as Fa,D as Vs,Da as kt,E as Gp,Ea as Uf,F as Hp,Fa as Gf,G as Bp,H as Kp,I as zp,Ia as vt,Ib as Ga,J as Yp,Ja as Hf,Jb as Ha,K as Qp,Ka as Bf,L as Zp,La as qf,Lb as um,M as ef,Ma as Xf,N as tf,Na as Vf,O as nf,Oa as Jf,P as sf,Q as rf,Qa as ve,R as _a,Ra as Qs,Sa as Wa,Ta as Kf,U as of,Ua as On,Va as zf,W as af,Wa as Oe,Xa as Yf,Ya as Qf,Za as Zf,_a as Zs,a as mp,ab as em,b as $a,ba as zs,bb as tm,ca as vf,ea as Sf,f as Ia,fa as Oa,g as yp,gb as nm,h as wp,i as Ta,ia as $f,j as bp,k as Mn,ka as If,kb as sm,l as kp,m as vp,mb as tr,n as Sp,na as Tf,nb as Ua,o as Qe,oa as xf,ob as rm,p as $p,pa as Af,pb as im,q as Ip,qa as Da,qb as om,ra as Rf,rb as am,s as Tp,ta as Ef,tb as cm,u as xp,ua as Na,v as Ze,va as Cf,w as Aa,wa as et,x as Lp,xa as Pf,y as jp,ya as Ys,yb as dm,z as Fp,zb as lm}from"./chunk-FZMS4UFL.js";import{d as gp,g as pp,h as fp}from"./chunk-YIR6FABW.js";import{a as Ap}from"./chunk-ZVP6GB4G.js";import{A as Pp,B as _p,D as Bs,E as Ra,F as qs,G as qt,K as cf,c as Jg,d as Kg,f as zg,g as _n,h as Hs,i as ka,j as Yg,k as Ke,z as Cp}from"./chunk-6FNJ7GQ2.js";import{b as Mf,c as Of,d as ja,e as Df,f as Nf,g as Lf,h as jf,i as Ff}from"./chunk-EKJG63EJ.js";import{b as Wf}from"./chunk-N6VBEITO.js";import{d as Mp}from"./chunk-6V5JBHUN.js";import{g as Op}from"./chunk-LQE73AZR.js";import{b as Dp,c as Np}from"./chunk-2D3RYIDU.js";import{b as df}from"./chunk-MRIVENBY.js";import{i as lf,m as Ma,n as uf,p as hf,q as gf,r as pf,s as ff,t as mf,u as yf}from"./chunk-FRR6DRLY.js";import{e as Ea,k as Ca,l as qp,m as Js,n as bt,o as Vt,p as Me,r as Xp,s as Vp,t as Jp,u as Pa,v as Ks}from"./chunk-LQS27HSV.js";import{a as wf}from"./chunk-PPUN7YHA.js";import{a as bf,b as kf}from"./chunk-VZLIBDLH.js";import{a as Rp,b as Ep}from"./chunk-A5GYG56I.js";import{o as xa}from"./chunk-3X2BFCOZ.js";import{b as Xs}from"./chunk-UKUH662W.js";import{a as Ye}from"./chunk-MNG2AMKZ.js";import{c as rp,d as ip,f as op,g as ap,i as cp,k as dp,l as lp}from"./chunk-RX5O5637.js";import{b as up,c as hp}from"./chunk-X7UQY7CH.js";import{a as va,b as Qg,c as Zg}from"./chunk-QPABR72X.js";import{a as ep,b as ze,c as tp,d as np,e as sp}from"./chunk-AJ5HMDRW.js";import{c as Bt}from"./chunk-KP7KDLZ2.js";import{$ as wa,A as B,C as Ah,D as Rh,E as Eh,F as Ch,G as ge,H as _h,I as Mh,J as Oh,K as Dh,L as Bh,M as qh,N as Xh,O as Mg,P as Og,Q as Dg,R as Ng,S as Lg,T as jg,V as Pn,W as Fg,Z as ie,_ as Je,a as Yu,aa as Ut,b as ia,ba,c as Zu,ca as Us,d as ah,da as Gt,e as ch,ea as Ht,f as An,fa as me,ga as wt,h as aa,ha as oe,i as ca,ia as Wg,j as da,ja as Ug,k as la,l as dh,ma as Bg,s as uh,t as fh,u as mt,v as mh,w as yh,x as wh,y as Wt,ya as qg,z as vh}from"./chunk-S25OP23O.js";import{$ as vg,Da as Hg,G as Gh,H as Hh,N as Vh,P as Jh,R as dg,S as lg,T as mg,U as yg,V as wg,W as bg,Y as ya,Z as Ws,_ as kg,a as hh,aa as Sg,ba as $g,c as bh,ca as Ig,d as kh,da as Tg,e as yt,ea as xg,f as _e,fa as Ag,h as Nh,ha as Rg,i as Lh,j as jh,k as ha,ka as Eg,l as Fh,m as Wh,p as Uh,pa as Cg,q as Ls,qa as Pg,ta as _g,xa as Gg}from"./chunk-M4BNVLGJ.js";import{a as ua,b as ph}from"./chunk-MEFPXHQJ.js";import{A as Xg,B as Gs,C as Vg,h as Gl,n as Hl,o as jo}from"./chunk-XXWSFJFZ.js";import{b as Fl}from"./chunk-SFQUP3BP.js";import{a as Sa}from"./chunk-6TTGRTDO.js";import{a as Kh,b as ga,c as zh,d as Yh,e as Qh,i as Zh,j as eg}from"./chunk-VE3SSOQX.js";import{b as Ph}from"./chunk-W4YR2RO2.js";import{b as ng,c as sg,d as pa,f as js,g as rg,h as ig,i as og,j as Cn,k as Fs,m as fa,n as ag,o as cg}from"./chunk-VJVXEVZ7.js";import{b as he,d as Be,f as qe,g as Rn,i as fe,j as tg,k as Xe,l as Ve,m as gg,p as pg,r as fg,t as ma}from"./chunk-CVFQA3TH.js";import{a as ug,b as hg}from"./chunk-KUZATIJA.js";import{b as gh}from"./chunk-PE5V2LI7.js";import{d as Sh,e as $h,f as Ih,g as Th,h as xh,j as En}from"./chunk-X5C5W3E4.js";import{c as Ns}from"./chunk-OWNQ2FD4.js";import{c as lh}from"./chunk-LUOW2YHY.js";import{d as ql,e as eT,m as Vu,n as gT,q as Ju,v as Ku,x as ra,y as He,z as xn}from"./chunk-FXMUUDSH.js";import{a as Pe,b as Tn,f as Os}from"./chunk-72SZI2UW.js";import{a as Sn,b as Bl}from"./chunk-FCPTN6NF.js";import{c as zu}from"./chunk-MYVHVJWZ.js";import{f as Qu}from"./chunk-QUFIUXMQ.js";import{d as eh,e as th,f as oa,g as Ds,h as nh,i as sh,j as rh,k as ih,q as oh}from"./chunk-AV7T3SYT.js";import{o as Lo,p as ZI}from"./chunk-DCIYOPJF.js";import{a as Ts,b as QI}from"./chunk-7I7IEX4S.js";import{b as Wl,e as Ul}from"./chunk-JHCI6XCJ.js";import{e as ut}from"./chunk-DSYKYZMT.js";import{Aa as Lu,B as Bo,Ba as In,C as nu,Ca as ju,D as su,Da as Fu,E as $n,Ea as Wu,F as Cs,Fa as Uu,G as ru,Ga as Gu,H as iu,Ha as dT,I as mu,J as oT,K as yu,Ka as Hu,M as Jo,N as wu,Na as Bu,O as bu,Oa as qu,P as aT,Q as ku,R as cT,Sa as lT,T as pt,U as vu,Ua as na,W as Ko,Wa as uT,X as zo,Y as Ge,Z as Ft,_ as Su,aa as Yo,ba as Qo,ca as $u,da as Iu,f as jt,fa as Tu,g as Vl,ga as xu,h as Wo,ha as ft,i as tT,ia as Zo,j as xs,ja as Au,k as Uo,ka as Ru,l as As,la as Ps,ma as Eu,n as ht,na as _s,o as Go,oa as Cu,p as Jl,pa as Pu,pb as sa,q as nT,qa as _u,r as Rs,ra as Mu,rb as Xu,s as sT,sa as ea,t as Es,ta,u as Kl,v as rT,va as Ms,w as zl,wa as Ou,x as Yl,y as Ql,ya as Du,yb as hT,za as Nu}from"./chunk-P7FSTC5E.js";import{a as Zl,e as gt,f as eu,g as tu,h as Ho}from"./chunk-VJ5HC63R.js";import{a as ou,b as au,c as cu,e as du,f as lu,i as iT,j as qo,k as uu,l as hu,m as Xo,n as gu,o as pu,q as Vo,r as fu}from"./chunk-UEEB3UTU.js";import{b as Fo,e as Xl}from"./chunk-VQRY4IDI.js";import{d as Lt}from"./chunk-QIJLFPWE.js";import{existsSync as za,readFileSync as Ya}from"fs";Ql();var hm=["answer","narration","line"],gm=5e3;function pm(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function fm(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let d=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!d||!l||!hm.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${hm.join(" | ")}`}};if(d.length>gm)return{status:413,body:{error:`text is over ${gm} characters`}};let h=e(l);if(!h)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:f,done:y}=r.enqueue({voice:h,text:d,agentId:l,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:f}}:{status:200,body:{item:f,played:await y}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,o,a,c]=n.split("/");if(t!=="POST"||!o||c!==void 0)return{status:404,body:{error:"Not found"}};switch(a){case"skip":return r.skip(o)?{status:200,body:r.view()}:Ba(o);case"front":return r.front(o)?{status:200,body:r.view()}:Ba(o);case"replay":{let d=r.replay(o);return d?{status:202,body:{item:d}}:Ba(o)}default:return{status:404,body:{error:"Not found"}}}}function mm(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`,t=r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.";return[...r.floor?.held?[Yl(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Ba=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});var pT=20,qa=120,fT=80,mT=new Set(["waiting_owner","needs_attention"]);function Xa(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function nr(r){return{total:r.length,items:r.slice(0,pT)}}var Va=r=>new Date(r).toISOString();function ym(r){return{id:r.id,agentId:r.agentId,kind:r.kind,text:Xa(r.text,fT),enqueuedAt:Va(r.enqueuedAt)}}function wm(r){let e=r.cards.filter(i=>i.status==="pending").sort((i,o)=>String(i.created_at??"").localeCompare(String(o.created_at??""))).map(i=>({id:i.id,title:Xa(i.title,qa),raised_by:i.raised_by,node:i.node??null,createdAt:i.created_at})),t=[...r.held].sort((i,o)=>i.at.localeCompare(o.at)).map(i=>({id:i.id,title:Xa(i.title,qa),from:i.from,at:i.at,heldBecause:i.heldBecause})),n=(r.requests??[]).filter(i=>mT.has(i.state)).sort((i,o)=>i.createdAt-o.createdAt).map(i=>({id:i.id,title:Ke(i,qa).headline,agentId:i.agentId,state:i.state,since:Va(i.stateChangedAt??i.updatedAt)})),s=r.voice;return{ts:Va(r.now),cards:nr(e),held:nr(t),voice:s?{paused:s.paused,reserved:s.reserved,playing:s.playing?ym(s.playing):null,waiting:nr(s.waiting.map(ym))}:null,requests:nr(n),errors:r.errors??[]}}function bm(r){let e=[],t=n=>n.total>n.items.length?[` \u2026 and ${n.total-n.items.length} more`]:[];e.push(`Decision cards waiting for an answer: ${r.cards.total}`);for(let n of r.cards.items)e.push(` - ${n.title} (by ${n.raised_by}${n.node?` on ${n.node}`:""}, ${n.createdAt}, ${n.id})`);e.push(...t(r.cards)),e.push(`Notices held by Focus or a call: ${r.held.total}`);for(let n of r.held.items)e.push(` - ${n.title} (from ${n.from}, ${n.at})`);if(e.push(...t(r.held)),r.voice){let n=r.voice.paused?", paused":r.voice.reserved?", the floor is held":"";e.push(`Speaking now: ${r.voice.playing?`${r.voice.playing.agentId??"the host"}: ${r.voice.playing.text}`:"nothing"}${n}`),e.push(`Lines waiting to be spoken: ${r.voice.waiting.total}`);for(let s of r.voice.waiting.items)e.push(` - ${s.agentId??"the host"} (${s.kind}): ${s.text}`);e.push(...t(r.voice.waiting))}e.push(`Open requests waiting on the owner: ${r.requests.total}`);for(let n of r.requests.items)e.push(` - ${n.title} (${n.agentId}, ${n.state.replace("_"," ")} since ${n.since}, ${n.id})`);e.push(...t(r.requests));for(let n of r.errors)e.push(`Could not read: ${n}`);return e.join(`
3
3
  `)}import{resolve as Qa}from"path";uT();var yT={name:"agentx",version:"0.1.0"},wT=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],bT="2024-11-05";function kT(r){return typeof r=="string"&&wT.includes(r)?r:bT}var vT={tools:{},elicitation:{form:{}}},ST=0;async function km(r,e){let t=++ST;return St({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Nn.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Nn.has(`elicit-${t}`)&&(Nn.delete(`elicit-${t}`),n(null))},6e4)})}var Nn=new Map,$T="http://localhost:18800",Ja;function IT(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=Qa(process.cwd(),r);if(!za(e))continue;let t=JSON.parse(Ya(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return $T}function X(){return Ja===void 0&&(Ja=IT()),Ja}var Ka;function TT(r){try{let e=Qa(process.cwd(),".env");if(!za(e))return"";for(let t of Ya(e,"utf-8").split(`
4
4
  `)){let n=t.trim().replace(/^export\s+/,"");if(!n.startsWith(`${r}=`))continue;let s=n.slice(r.length+1).trim();return/^(["']).*\1$/.test(s)?s.slice(1,-1):s}}catch{}return""}function xT(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=TT("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=Qa(process.cwd(),t);if(!za(n))continue;let s=JSON.parse(Ya(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function AT(){return Ka===void 0&&(Ka=xT()),Ka}var J=(r,e)=>{let t=AT();if(!t)return fetch(r,e);let n=new Headers(e?.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${t}`),fetch(r,{...e,headers:n})};function Dn(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function RT(){let r=process.env.AGENTX_AGENT_ID,e=Dn();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await J(`${X()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var ET=1e4,CT=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function PT(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&CT.has(n))return`Error: the AgentX daemon could not be reached (${n}); the message to ${r} was not sent.`;let s=t?.name==="TimeoutError"||t?.name==="AbortError"?"no answer in time":t?.message||String(e);return`Probably delivered to ${r}: the daemon did not confirm (${s}), but the request was sent and is most likely queued. Do not treat this as a failure. If unsure, send the same message again: within 10 minutes a repeat returns the existing task id instead of a second task, and delivers it if the first never arrived. A busy ${r} shows no trace until its turn starts; later, \`agentx trace list --agent ${r} --since 1h\` or the daemon log ("[send/agent]") shows it.`}var _T=/\x1B\[[0-9;]*[A-Za-z]/g;function Jt(r){return r.replace(_T,"")}async function MT(r,e,t){let n=await J(`${X()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:OT(i,!!s.hasMore)}]}}function OT(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
@@ -531,7 +531,7 @@ ${d}`)}let $={agentId:o,message:b,context:{channel:g,sender:y?"opencode":"openai
531
531
 
532
532
  `)}}function Dy(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Ny(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
533
533
 
534
- `)}function Ly(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);$c(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function $c(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Vn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Vn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Vn.levelOrder[e]<Vn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Xn=Vn;Lt(Xn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as UA,statSync as GA}from"fs";var tt={version:"0.177.0",commit:"a1d5a5a",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function HA(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Fy(){let r=null;try{r=GA(UA(process.argv[1])).mtimeMs}catch{}let e=ay().version;return HA(tt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as BA}from"crypto";var Cr=class{constructor(e=new vh){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!qA.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};VA(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:BA(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=XA(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},qA=["run","task","signal","mesh","channel","status"];function XA(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function VA(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Wy(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Pr,timingSafeEqual as Uy}from"crypto";var _r=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let w={};for(let[b,$]of Object.entries(e.headers))(b.startsWith("x-hubspot")||b.startsWith("x-hub")||b.startsWith("x-github")||b.startsWith("x-gitlab")||b.startsWith("stripe")||b.startsWith("sentry")||b.startsWith("x-vercel")||b.startsWith("x-odoo")||b.startsWith("x-webhook")||b==="user-agent"||b==="content-type"||b==="host"||b==="x-forwarded-host"||b==="x-forwarded-proto"||b==="x-forwarded-for")&&(w[b]=$);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(d,c,e.headers),f=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===d),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(d,h,i,c),y&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${d}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:h,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${h??"\u2014"}] -> workflow=${y} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:h,workflow:y,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${d}/${h}/${y}]: ${w.message}`)}let g=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===d);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(w=>this.log(`Mesh-forwarded webhook [${d}] -> ${g.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${d}] -> ${g.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:d,response:w.content?.slice(0,500),error:w.error,duration:w.duration})}catch(w){this.sendJson(t,500,{error:w.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
534
+ `)}function Ly(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);$c(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function $c(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Vn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Vn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Vn.levelOrder[e]<Vn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Xn=Vn;Lt(Xn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as UA,statSync as GA}from"fs";var tt={version:"0.178.0",commit:"a54e923",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function HA(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Fy(){let r=null;try{r=GA(UA(process.argv[1])).mtimeMs}catch{}let e=ay().version;return HA(tt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as BA}from"crypto";var Cr=class{constructor(e=new vh){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!qA.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};VA(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:BA(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=XA(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},qA=["run","task","signal","mesh","channel","status"];function XA(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function VA(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Wy(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Pr,timingSafeEqual as Uy}from"crypto";var _r=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let w={};for(let[b,$]of Object.entries(e.headers))(b.startsWith("x-hubspot")||b.startsWith("x-hub")||b.startsWith("x-github")||b.startsWith("x-gitlab")||b.startsWith("stripe")||b.startsWith("sentry")||b.startsWith("x-vercel")||b.startsWith("x-odoo")||b.startsWith("x-webhook")||b==="user-agent"||b==="content-type"||b==="host"||b==="x-forwarded-host"||b==="x-forwarded-proto"||b==="x-forwarded-for")&&(w[b]=$);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(d,c,e.headers),f=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===d),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(d,h,i,c),y&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${d}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:h,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${h??"\u2014"}] -> workflow=${y} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:h,workflow:y,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${d}/${h}/${y}]: ${w.message}`)}let g=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===d);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(w=>this.log(`Mesh-forwarded webhook [${d}] -> ${g.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${d}] -> ${g.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:d,response:w.content?.slice(0,500),error:w.error,duration:w.duration})}catch(w){this.sendJson(t,500,{error:w.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
535
535
  `)[0]||"no message"} (${l.author?.name||""})`)}let d=t.object_attributes;if(d?.title&&(s.push(`Title: ${d.title}`),s.push(`State: ${d.state||""}`),s.push(`Action: ${d.action||""}`),d.source_branch&&s.push(`Branch: ${d.source_branch} -> ${d.target_branch}`),d.url&&s.push(`URL: ${d.url}`)),d?.iid&&!d?.source_branch&&(s.push(`Issue #${d.iid}: ${d.title||""}`),d.description&&s.push(`Description: ${d.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
536
536
  `)[0]||""} (${u.author?.name||""})`);let d=t.pull_request;d&&(s.push(`PR #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${d.head?.ref} -> ${d.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let d of a.slice(0,3)){let l=d.subscriptionType??"?",u=d.objectId??"?",h=d.changeFlag??d.changeSource??"";s.push(` - ${l} (object ${u}${h?`, ${h}`:""})`)}}else{let d=t.subscriptionType??"event",l=t.objectId??"?";s.push(`Event: ${d} (object ${l})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
537
537
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(l=>l.enabled&&l.agentId===s&&l.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=l=>{let u=e[l.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let l=c("x-hub-signature-256");if(!l)return"missing X-Hub-Signature-256";let u="sha256="+Pr("sha256",a).update(t).digest("hex");return Zt(u,l)}if(n==="gitlab"){let l=c("x-gitlab-token");return l?Zt(a,l):"missing X-Gitlab-Token"}if(n==="stripe"){let l=c("stripe-signature");if(!l)return"missing Stripe-Signature";let u=Object.fromEntries(l.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=Pr("sha256",a).update(`${u.t}.${t}`).digest("hex");return Zt(h,u.v1)}if(n==="hubspot"){let l=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!l)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-h;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let y="POST",g=i||e["x-original-uri"]||e["x-forwarded-path"]||"",w=e["x-forwarded-host"],b=e.host,$=e["x-forwarded-proto"]||"https",k=new Set;w&&g&&k.add(`${$}://${w}${g}`),b&&g&&k.add(`https://${b}${g}`),b&&g&&k.add(`http://${b}${g}`),g&&k.add(g),k.add("");for(let x of k){let E=Pr("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(l.length===E.length&&Uy(Buffer.from(l),Buffer.from(E)))return null}return`signature mismatch (tried ${k.size} URI variants)`}if(n==="odoo"){let l=c("x-odoo-signature");if(l){let h=Pr("sha256",a).update(t).digest("hex"),f=l.startsWith("sha256=")?l.slice(7):l;return Zt(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Zt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let d=c("x-webhook-secret");return d?Zt(a,d):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function Zt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Uy(t,n)?null:"signature mismatch"}fu();Bl();du();iT();function JA(r){return{insertTaskHistory:r.prepare(`
@@ -1331,4 +1331,4 @@ data: ${JSON.stringify(z)}
1331
1331
  `)}catch{}},L=setInterval(()=>{try{t.write(`: ping
1332
1332
 
1333
1333
  `)}catch{}},15e3);L.unref?.();let H=new AbortController;t.on("close",()=>{t.writableEnded||H.abort()});try{for await(let W of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:H.signal,vouchOwner:S}))C(W.event,W.data)}catch(W){C("error",{error:W?.message??String(W)})}finally{clearInterval(L);try{t.end()}catch{}}break}let _=p.context,M=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(F$(p,!0)==="callback"){let C=this.delegationGate(e,p,{callee:p.agent,peer:p.peer,message:p.message,calleeContext:_});if(!("track"in C)){let L=mo(C);this.json(t,L.status,L.body);break}}if(p.async===!0){let C=_?.channel,L=_?.chatId;if(!C||!L){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let H=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:H,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let W=p.peer,z=p.agent,Se=this.mesh;(async()=>{let V=Date.now(),Y;try{Y=await Se.sendTask(W,p.message,z,{vouchOwner:S,context:_,senderAgentId:M}),this.log(`[mesh/task async ${H}] ${W}/${z??"default"} finished in ${Date.now()-V}ms`)}catch(K){Y=`Delegation to ${W}/${z??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${H}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:Y,agentId:_?.agentId??M,accountId:_?.accountId})}catch(K){this.log(`[mesh/task async ${H}] delivery failed: ${K?.message??K}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:_,senderAgentId:M,vouchOwner:S});this.json(t,200,{response:N});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=await this.webrtc.handleOutgoing(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=this.webrtc.handleIncoming(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let p=await U(e),m=p.callId,v=p.target,S=p.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!v||!S){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:v,agentId:S});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let p=this.config.channels.webrtc;if(!p?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...p.stunServers.map(m=>({urls:m})),...p.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:p.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(p=>{let m=this.config.agents[p.id]||{},v=typeof m.description=="string"&&m.description.trim()||HL(m.systemPrompt)||`Agent "${p.name}" (${p.tier})`,S=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:p.id,name:p.name,description:v,tags:[p.tier,...S],color:we(p.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let p=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:p.summary()});break}case"GET /wiki/entries":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,v=n.searchParams.get("after")||void 0,S=m?p.getAgentEntries(m):p.getSharedStore().listEntries({after:v});this.json(t,200,{nodeId:this.config.node.id,count:S.length,entries:S.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let S=p.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:S.articles});break}case"GET /wiki/article":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent"),v=n.searchParams.get("path");if(!m||!v){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=p.getAgentWiki(m).readArticle(v);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /wiki/notes":{let{NoteStore:p}=await import("./notes-WJJEJ4CJ.js"),m=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(m)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let v=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new p(this.registry.getWikiHub().getBaseDir()).list(m==="all"?void 0:m);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:I.length,notes:I.slice(-v).reverse()});break}case"POST /wiki/notes":{let{NoteStore:p,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),v=this.config.wikiNotes;if(!v.enabled||!v.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let S=await U(e),I=m({...S,to:v.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let R=I.note;if(this.registry.getAgent(v.inbox)){try{let{note:N,added:C}=new p(this.registry.getWikiHub().getBaseDir()).add(R);this.json(t,C?201:200,{ok:!0,added:C,note:N,node:this.config.node.id})}catch(N){this.json(t,507,{error:N?.message??String(N)})}break}if(S.forwarded===!0){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node`});break}let _=this.mesh?.findAgentPeer(v.inbox);if(!_){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node or any known peer`});break}let M=this.mesh.directory().find(N=>N.peer===_.peer)?.peerUrl;if(!_.healthy||!M){this.json(t,503,{error:`the node hosting "${v.inbox}" (${_.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${M.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(_.peer)},body:JSON.stringify({...R,fromNode:R.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await N.json().catch(()=>({}));this.json(t,N.status,{...C,peer:_.peer})}catch(N){this.json(t,502,{error:`forward to ${_.peer} failed: ${N?.message??N}`,peer:_.peer})}break}case"GET /graph/schema":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:p.loadSchema()});break}case"GET /graph/nodes":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...p.loadNodes()});break}case"GET /graph/classifications":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",v=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),S=p.listByStatus(m,v);this.json(t,200,{nodeId:this.config.node.id,status:m,count:S.length,classifications:S});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await jy(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let d=this.registry.list().find(l=>l.id===i)?.runningTasks.filter(l=>l.channel===o&&l.chatId===a)||[];for(let l of d)this.registry.cancelRunningTask(l.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=Zp(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=gw();if(e==="json")return this.registry.getTodayUsage();let t=hw(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!kn(n)))try{let s=te(n,".claude","skills");zI(s,{recursive:!0});let i=te(s,wS);if(!kn(i))Dl(i,Cd(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=kS($s(i,"utf-8"),e);o&&(Dl(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!kn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||Rg(this.config.workflows,e)),i=qh(eh(t),this.config.requests.enabled||s?Bh():null);try{switch(Xh(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Yv(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(y=>y.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-NR7SLHGX.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return Mp(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(d){this.json(t,400,{error:"invalid JSON body",message:d.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let d=this.pushBridgeCaller(e);if("origin"in d)c=d.origin;else if(i!=="default"){this.json(t,403,{error:d.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:d}=await import("./push-bridge-NR7SLHGX.js"),l=d(i,this.pushBridgeCaller(e));if("error"in l){this.json(t,403,{error:l.error});return}}try{let d=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:d??null})}catch(d){this.log(`[mesh] /channel/send "${s}" failed: ${d.message}`),this.json(t,500,{error:d.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(d,l)=>{let u=0;for(let h of d)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:l}),u++);u>0&&o.push(`${l}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(d=>({id:d.jid,name:d.name,kind:d.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let d=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(d.map(async l=>{try{let u=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(l.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${l.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await yS({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Nl=Ll;Lt(Nl,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function HL(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function BL(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}QI();function Az(r){typeof r=="string"&&(Ts.error(r),process.exit(1)),r instanceof Error&&(Ts.error(r.message),process.exit(1)),Ts.error("Something went wrong. Please try again."),process.exit(1)}export{cj as a,Za as b,$t as c,jn as d,Wn as e,xt as f,gr as g,ay as h,ew as i,rR as j,iR as k,iw as l,Te as m,cw as n,dw as o,Or as p,t2 as q,n2 as r,Jr as s,bU as t,wC as u,bC as v,Vc as w,ib as x,kU as y,fb as z,vC as A,mb as B,yb as C,wb as D,vU as E,SU as F,$U as G,ti as H,Le as I,EG as J,bP as K,Dk as L,Nk as M,o_ as N,Zk as O,sv as P,J_ as Q,$d as R,SB as S,$B as T,IB as U,oS as V,xM as W,EB as X,CB as Y,is as Z,un as _,os as $,t4 as aa,LS as ba,fO as ca,V4 as da,Ui as ea,Hd as fa,Bd as ga,Xi as ha,we as ia,R0 as ja,zi as ka,hD as la,U0 as ma,pD as na,q0 as oa,Zi as pa,ps as qa,so as ra,io as sa,Y0 as ta,rl as ua,s$ as va,ct as wa,Ee as xa,c$ as ya,d$ as za,l$ as Aa,u$ as Ba,To as Ca,aI as Da,xl as Ea,dI as Fa,VN as Ga,p3 as Ha,Nl as Ia,Az as Ja};
1334
- //# sourceMappingURL=chunk-FXCBW52X.js.map
1334
+ //# sourceMappingURL=chunk-GQJMY5NH.js.map