agentix-cli 0.114.0 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/{agent-5F4EKGQN.js → agent-NGCPRTBH.js} +2 -2
  2. package/dist/{board-dashboard-GGW5ZZLT.js → board-dashboard-7B2B564A.js} +244 -244
  3. package/dist/{board-dashboard-GGW5ZZLT.js.map → board-dashboard-7B2B564A.js.map} +1 -1
  4. package/dist/{chunk-O2RVUM2B.js → chunk-CSLVHAYV.js} +2 -2
  5. package/dist/{chunk-QQIWLN3H.js → chunk-DOQ6Y7GZ.js} +5 -5
  6. package/dist/chunk-DOQ6Y7GZ.js.map +1 -0
  7. package/dist/{chunk-4COYYJJY.js → chunk-EVB23EHN.js} +2 -2
  8. package/dist/chunk-JVSTKXMI.js +6 -0
  9. package/dist/chunk-JVSTKXMI.js.map +1 -0
  10. package/dist/{chunk-XTO4GRGN.js → chunk-QBWJGDKE.js} +3 -3
  11. package/dist/{chunk-XX7NXI3Y.js → chunk-TZIPWZY6.js} +2 -2
  12. package/dist/{chunk-HPY54DU6.js → chunk-UMFFIUU6.js} +2 -2
  13. package/dist/{chunk-YU5NDKPA.js → chunk-UZB5UO35.js} +2 -2
  14. package/dist/{chunk-VQM77L54.js → chunk-Z6OPM7EH.js} +2 -2
  15. package/dist/{chunk-6WNQY6K2.js → chunk-ZXQYOSHP.js} +2 -2
  16. package/dist/cli.js +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{program-IEMICVO3.js → program-4IMJEMDM.js} +7 -7
  19. package/dist/{promote-S7SKOKX2.js → promote-4VTXBVUC.js} +2 -2
  20. package/dist/{query-GOBQ3GL5.js → query-B32UDQJS.js} +2 -2
  21. package/dist/{registry-HUJEORRW.js → registry-GY4X2GZX.js} +2 -2
  22. package/dist/{wiki-FZHSX4K3.js → wiki-LVYHDK2R.js} +2 -2
  23. package/package.json +1 -1
  24. package/dist/chunk-ILGLEA3I.js +0 -6
  25. package/dist/chunk-ILGLEA3I.js.map +0 -1
  26. package/dist/chunk-QQIWLN3H.js.map +0 -1
  27. /package/dist/{agent-5F4EKGQN.js.map → agent-NGCPRTBH.js.map} +0 -0
  28. /package/dist/{chunk-O2RVUM2B.js.map → chunk-CSLVHAYV.js.map} +0 -0
  29. /package/dist/{chunk-4COYYJJY.js.map → chunk-EVB23EHN.js.map} +0 -0
  30. /package/dist/{chunk-XTO4GRGN.js.map → chunk-QBWJGDKE.js.map} +0 -0
  31. /package/dist/{chunk-XX7NXI3Y.js.map → chunk-TZIPWZY6.js.map} +0 -0
  32. /package/dist/{chunk-HPY54DU6.js.map → chunk-UMFFIUU6.js.map} +0 -0
  33. /package/dist/{chunk-YU5NDKPA.js.map → chunk-UZB5UO35.js.map} +0 -0
  34. /package/dist/{chunk-VQM77L54.js.map → chunk-Z6OPM7EH.js.map} +0 -0
  35. /package/dist/{chunk-6WNQY6K2.js.map → chunk-ZXQYOSHP.js.map} +0 -0
  36. /package/dist/{program-IEMICVO3.js.map → program-4IMJEMDM.js.map} +0 -0
  37. /package/dist/{promote-S7SKOKX2.js.map → promote-4VTXBVUC.js.map} +0 -0
  38. /package/dist/{query-GOBQ3GL5.js.map → query-B32UDQJS.js.map} +0 -0
  39. /package/dist/{registry-HUJEORRW.js.map → registry-GY4X2GZX.js.map} +0 -0
  40. /package/dist/{wiki-FZHSX4K3.js.map → wiki-LVYHDK2R.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-ILGLEA3I.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{y as C,z as I}from"./chunk-A35RTVMM.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
1
+ import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-JVSTKXMI.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{y as C,z as I}from"./chunk-A35RTVMM.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
2
2
  ## Intent
3
3
 
4
4
  The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
@@ -46,4 +46,4 @@ ${o}
46
46
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
47
47
 
48
48
  Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
49
- //# sourceMappingURL=chunk-O2RVUM2B.js.map
49
+ //# sourceMappingURL=chunk-CSLVHAYV.js.map
@@ -1,4 +1,4 @@
1
- import{$ as ad,$a as Kr,Ca as vd,D as Wl,Da as Mn,Ea as Xr,Fa as Sd,Ga as $d,H as ql,Ha as Id,Ia as Td,J as Vl,Ka as xd,L as Jl,M as Br,N as Xl,O as Pe,P as Kl,Q as Rn,Ra as Ad,S as Wr,Sa as Rd,T as zl,U as Vr,V as Ge,W as id,X as od,_ as He,a as ll,aa as cd,ab as zr,b as Dr,ba as ld,ca as dd,cb as Ed,da as ud,ea as hd,f as Nr,g as dl,ga as de,h as ul,ha as En,i as Ee,ia as Jr,j as hl,ja as gd,k as gl,ka as Pt,la as pd,m as pl,ma as ke,na as md,o as ml,oa as fd,p as xl,pa as yd,q as Al,qa as Cn,r as Rl,ra as Pn,s as El,sa as wd,t as Cl,ta as bd,u as Pl,v as Ml,ya as kd,z as An}from"./chunk-6WNQY6K2.js";import{c as ol,f as al,g as cl}from"./chunk-VTWSW4KB.js";import{m as yl,n as wl,o as Lr,p as Ce,r as bl,s as pe}from"./chunk-S2GAEH2F.js";import{c as rd}from"./chunk-BGG3ZSMW.js";import{a as fl}from"./chunk-ZVP6GB4G.js";import{a as Gl}from"./chunk-PPUN7YHA.js";import{a as Hl,b as Bl}from"./chunk-VZLIBDLH.js";import{b as Yl,c as Ql,d as qr,e as Zl,f as ed,g as td,h as nd,i as sd}from"./chunk-EKJG63EJ.js";import{o as jr}from"./chunk-4COYYJJY.js";import{b as Fr}from"./chunk-ACFQBLPX.js";import{g as kl}from"./chunk-LQE73AZR.js";import{b as vl,c as Sl}from"./chunk-2D3RYIDU.js";import{i as _l,m as Hr,n as Ol,p as Dl,q as Nl,r as jl,s as Ll,t as Fl,u as Ul}from"./chunk-QLWGLRT5.js";import{b as Ur,c as $l,d as $n,e as In,g as Tn,i as Il,j as Tl,k as Gr,l as xn}from"./chunk-JIT5GPTX.js";import{A as gc,B as pc,C as mc,D as se,E as yc,F as wc,G as bc,H as kc,I as vc,J as Sc,K as $c,L as qc,M as Vc,N as Jc,O as Xc,P as Kc,Q as zc,U as Zc,a as Fa,b as xr,c as Ga,ca as el,d as Ka,e as za,f as At,h as Rr,i as Er,j as Cr,k as Ya,l as Qa,s as Za,t as nc,u as Rt,v as sc,w as oc,x as B,z as hc}from"./chunk-XTO4GRGN.js";import{B as Qc,a as ec,c as rc,d as ic,e as Ue,f as et,l as Ic,m as Tc,o as jc,p as Lc,q as Hc,r as Bc,t as Wc,v as Yc}from"./chunk-J3GXZQXY.js";import{b as Mc,c as _c,d as _r,f as bn,g as Oc,h as Dc,i as Nc,j as Et,k as kn}from"./chunk-GLQLCBJS.js";import{a as Pr,b as tc}from"./chunk-6W74CHNW.js";import{A as tl,B as vn,C as nl,h as aa,n as ca,o as mr}from"./chunk-YU5NDKPA.js";import{b as ra}from"./chunk-SFQUP3BP.js";import{a as sl,b as Sn,c as rl,d as il}from"./chunk-LLNPKE7H.js";import{a as nt,b as st}from"./chunk-SHEUCITK.js";import{a as Ct}from"./chunk-Y4CYQV7G.js";import{a as xc,b as Mr,c as Ac,d as Rc,e as Ec,i as Cc}from"./chunk-76Z4VHDX.js";import{b as fc}from"./chunk-W4YR2RO2.js";import{b as ne,d as tt,f as fn,g as yn,i as ie,j as Pc,k as Ae,l as Re,m as Gc,s as Or}from"./chunk-VGI4EZTP.js";import{a as Fc,b as Uc}from"./chunk-CYKPDILL.js";import{d as ac,e as cc,f as lc,g as dc,h as uc,j as wn}from"./chunk-X5C5W3E4.js";import{c as La}from"./chunk-MYVHVJWZ.js";import{d as Ha,e as Ba,f as Ar,g as mn,h as Wa,i as qa,j as Va,k as Ja,q as Xa}from"./chunk-AV7T3SYT.js";import{b as Ua}from"./chunk-2GIDVZ4H.js";import{d as la,e as Jf,m as Da,n as ry,q as Na,v as ja,y as Ze,z as pn}from"./chunk-A35RTVMM.js";import{a as Fe,b as xt,f as Tr}from"./chunk-72SZI2UW.js";import{a as fr,b as Vf}from"./chunk-FCPTN6NF.js";import{a as cn,b as qf}from"./chunk-7I7IEX4S.js";import{b as ia,e as oa}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as ey,B as Ia,D as $r,F as Ta,G as xa,I as gn,J as Aa,K as Ra,L as Ea,M as Ca,N as ty,Q as Pa,T as Ma,U as _a,Y as ny,d as Qe,e as da,f as yr,g as Kf,h as ln,i as wr,j as dn,ja as Ir,ka as Oa,l as je,m as br,ma as sy,n as ua,o as zf,p as un,q as Yf,r as hn,s as ha,t as Qf,z as $a}from"./chunk-Y5HBYSJW.js";import{a as ma,b as fa,c as ya,e as wa,f as vr,g as ba,h as ka,i as Sr,j as va,k as Sa,n as Zf}from"./chunk-UIBUZ2N3.js";import{e as Le,f as ga,g as pa,h as kr}from"./chunk-BRK6M6LA.js";import{e as Xf}from"./chunk-2QNT5JDS.js";import{d as Ye}from"./chunk-QIJLFPWE.js";import{existsSync as iy,readFileSync as oy}from"fs";var Cd=["answer","narration","line"];function Pd(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Md(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Cd.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Cd.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:m,done:f}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:m}}:{status:200,body:{item:m,played:await f}}}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[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Yr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Yr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Yr(i)}default:return{status:404,body:{error:"Not found"}}}}function _d(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$ as ad,$a as Kr,Ca as vd,D as Wl,Da as Mn,Ea as Xr,Fa as Sd,Ga as $d,H as ql,Ha as Id,Ia as Td,J as Vl,Ka as xd,L as Jl,M as Br,N as Xl,O as Pe,P as Kl,Q as Rn,Ra as Ad,S as Wr,Sa as Rd,T as zl,U as Vr,V as Ge,W as id,X as od,_ as He,a as ll,aa as cd,ab as zr,b as Dr,ba as ld,ca as dd,cb as Ed,da as ud,ea as hd,f as Nr,g as dl,ga as de,h as ul,ha as En,i as Ee,ia as Jr,j as hl,ja as gd,k as gl,ka as Pt,la as pd,m as pl,ma as ke,na as md,o as ml,oa as fd,p as xl,pa as yd,q as Al,qa as Cn,r as Rl,ra as Pn,s as El,sa as wd,t as Cl,ta as bd,u as Pl,v as Ml,ya as kd,z as An}from"./chunk-ZXQYOSHP.js";import{c as ol,f as al,g as cl}from"./chunk-VTWSW4KB.js";import{m as yl,n as wl,o as Lr,p as Ce,r as bl,s as pe}from"./chunk-S2GAEH2F.js";import{c as rd}from"./chunk-BGG3ZSMW.js";import{a as fl}from"./chunk-ZVP6GB4G.js";import{a as Gl}from"./chunk-PPUN7YHA.js";import{a as Hl,b as Bl}from"./chunk-VZLIBDLH.js";import{b as Yl,c as Ql,d as qr,e as Zl,f as ed,g as td,h as nd,i as sd}from"./chunk-EKJG63EJ.js";import{o as jr}from"./chunk-EVB23EHN.js";import{b as Fr}from"./chunk-ACFQBLPX.js";import{g as kl}from"./chunk-LQE73AZR.js";import{b as vl,c as Sl}from"./chunk-2D3RYIDU.js";import{i as _l,m as Hr,n as Ol,p as Dl,q as Nl,r as jl,s as Ll,t as Fl,u as Ul}from"./chunk-QLWGLRT5.js";import{b as Ur,c as $l,d as $n,e as In,g as Tn,i as Il,j as Tl,k as Gr,l as xn}from"./chunk-JIT5GPTX.js";import{A as gc,B as pc,C as mc,D as se,E as yc,F as wc,G as bc,H as kc,I as vc,J as Sc,K as $c,L as qc,M as Vc,N as Jc,O as Xc,P as Kc,Q as zc,U as Zc,a as Fa,b as xr,c as Ga,ca as el,d as Ka,e as za,f as At,h as Rr,i as Er,j as Cr,k as Ya,l as Qa,s as Za,t as nc,u as Rt,v as sc,w as oc,x as B,z as hc}from"./chunk-QBWJGDKE.js";import{B as Qc,a as ec,c as rc,d as ic,e as Ue,f as et,l as Ic,m as Tc,o as jc,p as Lc,q as Hc,r as Bc,t as Wc,v as Yc}from"./chunk-J3GXZQXY.js";import{b as Mc,c as _c,d as _r,f as bn,g as Oc,h as Dc,i as Nc,j as Et,k as kn}from"./chunk-GLQLCBJS.js";import{a as Pr,b as tc}from"./chunk-6W74CHNW.js";import{A as tl,B as vn,C as nl,h as aa,n as ca,o as mr}from"./chunk-UZB5UO35.js";import{b as ra}from"./chunk-SFQUP3BP.js";import{a as sl,b as Sn,c as rl,d as il}from"./chunk-LLNPKE7H.js";import{a as nt,b as st}from"./chunk-SHEUCITK.js";import{a as Ct}from"./chunk-Y4CYQV7G.js";import{a as xc,b as Mr,c as Ac,d as Rc,e as Ec,i as Cc}from"./chunk-76Z4VHDX.js";import{b as fc}from"./chunk-W4YR2RO2.js";import{b as ne,d as tt,f as fn,g as yn,i as ie,j as Pc,k as Ae,l as Re,m as Gc,s as Or}from"./chunk-VGI4EZTP.js";import{a as Fc,b as Uc}from"./chunk-CYKPDILL.js";import{d as ac,e as cc,f as lc,g as dc,h as uc,j as wn}from"./chunk-X5C5W3E4.js";import{c as La}from"./chunk-MYVHVJWZ.js";import{d as Ha,e as Ba,f as Ar,g as mn,h as Wa,i as qa,j as Va,k as Ja,q as Xa}from"./chunk-AV7T3SYT.js";import{b as Ua}from"./chunk-2GIDVZ4H.js";import{d as la,e as Jf,m as Da,n as ry,q as Na,v as ja,y as Ze,z as pn}from"./chunk-A35RTVMM.js";import{a as Fe,b as xt,f as Tr}from"./chunk-72SZI2UW.js";import{a as fr,b as Vf}from"./chunk-FCPTN6NF.js";import{a as cn,b as qf}from"./chunk-7I7IEX4S.js";import{b as ia,e as oa}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as ey,B as Ia,D as $r,F as Ta,G as xa,I as gn,J as Aa,K as Ra,L as Ea,M as Ca,N as ty,Q as Pa,T as Ma,U as _a,Y as ny,d as Qe,e as da,f as yr,g as Kf,h as ln,i as wr,j as dn,ja as Ir,ka as Oa,l as je,m as br,ma as sy,n as ua,o as zf,p as un,q as Yf,r as hn,s as ha,t as Qf,z as $a}from"./chunk-Y5HBYSJW.js";import{a as ma,b as fa,c as ya,e as wa,f as vr,g as ba,h as ka,i as Sr,j as va,k as Sa,n as Zf}from"./chunk-UIBUZ2N3.js";import{e as Le,f as ga,g as pa,h as kr}from"./chunk-BRK6M6LA.js";import{e as Xf}from"./chunk-2QNT5JDS.js";import{d as Ye}from"./chunk-QIJLFPWE.js";import{existsSync as iy,readFileSync as oy}from"fs";var Cd=["answer","narration","line"];function Pd(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Md(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Cd.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Cd.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:m,done:f}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:m}}:{status:200,body:{item:m,played:await f}}}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[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Yr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Yr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Yr(i)}default:return{status:404,body:{error:"Not found"}}}}function _d(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Yr=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as ay}from"path";var cy={name:"agentx",version:"0.1.0"},ly="2024-11-05",dy={tools:{},elicitation:{form:{}}},uy=0;async function Od(r,e){let t=++uy;return Be({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Mt.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Mt.has(`elicit-${t}`)&&(Mt.delete(`elicit-${t}`),n(null))},6e4)})}var Mt=new Map,hy="http://localhost:19900",Qr;function gy(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=ay(process.cwd(),r);if(!iy(e))continue;let t=JSON.parse(oy(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 hy}function V(){return Qr===void 0&&(Qr=gy()),Qr}function Zr(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 py(){let r=process.env.AGENTX_AGENT_ID,e=Zr();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await fetch(`${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 my=/\x1B\[[0-9;]*[A-Za-z]/g;function rt(r){return r.replace(my,"")}async function fy(r,e,t){let n=await fetch(`${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:yy(i,!!s.hasMore)}]}}function yy(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}:
3
3
  ${o.join(`
4
4
  `)}`)}return e&&n.push("[older turns exist \u2014 pass a chatId, or call /recall with before=<ts>]"),n.join(`
@@ -34,7 +34,7 @@ Open it with your Read tool.`}]}}case"agentx_health":{let s=await(await fetch(`$
34
34
  `)}]}}case"agentx_attach_answer":{let n=process.env.CLAUDE_CODE_SESSION_ID;if(!n)return{content:[{type:"text",text:"Not running inside a Claude Code session \u2014 attach mode is unavailable here."}]};let s=await fetch(`${V()}/attach/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,text:String(e.text??"")})}),i=await s.json();if(!s.ok)return{content:[{type:"text",text:`Could not answer: ${i?.error??s.status}`}]};let o=i.pending>0?` ${i.pending} still queued.`:"";return{content:[{type:"text",text:`Sent to ${i.item?.channel}.${o}`}]}}case"agentx_events":{let n=process.env.AGENTX_AGENT_ID||e.agentId;if(!n)return{content:[{type:"text",text:"Error: agentId is required (no AGENTX_AGENT_ID in this session)."}]};let s=new URLSearchParams;typeof e.since=="string"&&e.since&&s.set("since",e.since),typeof e.limit=="number"&&s.set("limit",String(e.limit));let i=await fetch(`${V()}/agents/${encodeURIComponent(n)}/events?${s}`,{signal:AbortSignal.timeout(1e4)}),o=await i.json().catch(()=>({}));if(!i.ok)return{content:[{type:"text",text:`Error: ${o.error||i.statusText}`}]};let{formatEventLine:a}=await import("./subscriptions-RYVPHVIV.js");return{content:[{type:"text",text:by(n,o,a)}]}}case"agentx_crons":{let s=await(await fetch(`${V()}/crons/health`)).json(),i=`Healthy: ${s.healthy}, Failing: ${s.failing}, Disabled: ${s.disabled}, Missed: ${s.missed}`,o=(s.jobs||[]).map(a=>` ${a.id}: ${a.status}${a.consecutiveErrors?` (${a.consecutiveErrors} errors)`:""}${a.lastError?` \u2014 ${a.lastError.slice(0,100)}`:""}`).join(`
35
35
  `);return{content:[{type:"text",text:`${i}
36
36
 
37
- ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-FJKH2ERY.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await fetch(`${V()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-W3ODKQM2.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-J4VHHZWN.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-FZHSX4K3.js"),{agenticQuery:i}=await import("./query-GOBQ3GL5.js"),{resolve:o}=await import("path"),a=e.wiki_dir||o(process.cwd(),".agentx/wiki"),c=new s(a,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:k}=await import("fs");for(let S of c.listAgents()){let $=o(c.getAgentWiki(S).baseDir,"_index.md");if(k($)){l=S;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let d=c.getAgentWiki(l),u=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,m=await py(),f=await i(n,d,l,{maxHops:u,messagePath:m?.path,...m?.graphWeight!==void 0?{graphWeight:m.graphWeight}:{}});if(f.status!=="ok")return{content:[{type:"text",text:`Query returned status "${f.status}"${f.error?`: ${f.error}`:""}`}]};let p=f.citations.map(k=>` - ${k.title} [${k.type||"?"}] (${k.path})`).join(`
37
+ ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-FJKH2ERY.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await fetch(`${V()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-W3ODKQM2.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-J4VHHZWN.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-LVYHDK2R.js"),{agenticQuery:i}=await import("./query-B32UDQJS.js"),{resolve:o}=await import("path"),a=e.wiki_dir||o(process.cwd(),".agentx/wiki"),c=new s(a,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:k}=await import("fs");for(let S of c.listAgents()){let $=o(c.getAgentWiki(S).baseDir,"_index.md");if(k($)){l=S;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let d=c.getAgentWiki(l),u=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,m=await py(),f=await i(n,d,l,{maxHops:u,messagePath:m?.path,...m?.graphWeight!==void 0?{graphWeight:m.graphWeight}:{}});if(f.status!=="ok")return{content:[{type:"text",text:`Query returned status "${f.status}"${f.error?`: ${f.error}`:""}`}]};let p=f.citations.map(k=>` - ${k.title} [${k.type||"?"}] (${k.path})`).join(`
38
38
  `),y=f.walked.length;return{content:[{type:"text",text:`${f.answer}
39
39
 
40
40
  Citations (${y} article${y===1?"":"s"} walked):
@@ -193,7 +193,7 @@ ${s.length} commit(s):
193
193
  ${a}`,timestamp:new Date,raw:e,resolvedAgent:i,preferNode:o?.node};this.handler(c).catch(l=>this.log(`Error handling push: ${l.message}`))}resolveAgent(e){for(let t of this.config.routes)if(t.repo===e||t.repo==="*")return t.agent}postsAs(e){let t=e.toLowerCase();return this.postingLogins.has(t)||this.peerPostingLogins?.().some(n=>n.toLowerCase()===t)?!0:Ve(this.config.agentMappings,"githubUsernames").some(n=>n.toLowerCase()===t)}isBotUser(e){return this.botUsernames.has(e.toLowerCase())}getAgentToken(e){if(!e||!this.config.agentMappings?.length)return;let t=this.config.agentMappings.find(n=>n.agentId===e);if(t)return this.resolveToken(t.token,t.tokenFile)}resolveToken(e,t){if(e)return e;if(t)try{return Au(t,"utf-8").trim().split(`
194
194
  `)[0].trim()}catch(n){this.log(`Failed to read token file ${t}: ${n.message}`)}}verifySignature(e,t){if(!t||!this.config.webhookSecret)return!1;let n="sha256="+xw("sha256",this.config.webhookSecret).update(e).digest("hex");return t===n}async reactToComment(e,t){let n=await this.getTokenForRepo(e);if(n)try{await fetch(`https://api.github.com/repos/${e}/issues/comments/${t}/reactions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"},body:JSON.stringify({content:"eyes"})})}catch{}}async getTokenForRepo(e){if(this.appPrivateKey&&this.config.appId&&e){let t=await this.getInstallationToken(e);if(t)return t}return this.globalToken}generateAppJWT(){let e=Math.floor(Date.now()/1e3),t={iat:e-60,exp:e+600,iss:this.config.clientId||String(this.config.appId)},n=Buffer.from(JSON.stringify({alg:"RS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),i=`${n}.${s}`,o=Aw("RSA-SHA256");o.update(i);let a=o.sign(this.appPrivateKey,"base64url");return`${i}.${a}`}async getInstallationToken(e){let t=this.installationTokens.get(e);if(t&&t.expiresAt>Date.now()+6e4)return t.token;try{let n=this.generateAppJWT(),s=await fetch(`https://api.github.com/repos/${e}/installation`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"}});if(!s.ok){this.log(`GitHub App not installed on ${e}: ${s.status}`);return}let i=await s.json(),o=await fetch(`https://api.github.com/app/installations/${i.id}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"}});if(!o.ok){this.log(`Failed to get installation token for ${e}: ${o.status}`);return}let a=await o.json(),c=new Date(a.expires_at).getTime();return this.installationTokens.set(e,{token:a.token,expiresAt:c}),this.log(`Got installation token for ${e} (expires: ${a.expires_at})`),a.token}catch(n){this.log(`Installation token error for ${e}: ${n.message}`);return}}};var Se=null;async function Ew(){if(Se)return Se;let r;try{r=await import("@roamhq/wrtc")}catch(s){throw new Error(`WebRTC bot requires "@roamhq/wrtc" \u2014 install it on this node (\`pnpm add @roamhq/wrtc\`) or set channels.webrtc.bot.enabled=false. Original: ${s?.message??s}`)}let e=r.default??r,t=e.RTCPeerConnection,n=e.nonstandard?.RTCAudioSink;if(!t||!n)throw new Error("@roamhq/wrtc loaded but missing expected exports (RTCPeerConnection / nonstandard.RTCAudioSink)");return Se={RTCPeerConnection:t,RTCAudioSink:n,RTCVideoSink:e.nonstandard?.RTCVideoSink,i420ToRgba:typeof e.nonstandard?.i420ToRgba=="function"?e.nonstandard.i420ToRgba:void 0},Se}function Cu(){return Se?.i420ToRgba??null}var Eu=r=>r.toLowerCase().replace(/[^a-z0-9]/g,""),lt=class{pc;sinks=new Set;unsubscribe;closed=!1;opts;constructor(e){this.opts=e}async start(){if(this.pc)throw new Error("WebRtcBot already started");let{broker:e,callId:t,botName:n,target:s,iceServers:i,log:o}=this.opts,{RTCPeerConnection:a}=await Ew();if(this.pc=new a({iceServers:i}),this.pc.ontrack=l=>{if(this.closed)return;let d=l.track;d.kind==="audio"&&this.opts.onAudioFrame?(o(`[bot:${n}] audio track received from ${s}`),this.tapAudio(d)):d.kind==="video"&&this.opts.onVideoFrame?(o(`[bot:${n}] video track received from ${s}`),this.tapVideo(d)):o(`[bot:${n}] ${d.kind} track received \u2014 not asked for, ignored`)},this.pc.onicecandidate=l=>{!l.candidate||this.closed||this.send({kind:"ice",callId:t,from:n,to:s,candidate:{candidate:l.candidate.candidate,sdpMid:l.candidate.sdpMid,sdpMLineIndex:l.candidate.sdpMLineIndex,usernameFragment:l.candidate.usernameFragment}})},this.pc.onconnectionstatechange=()=>{let l=this.pc?.connectionState;o(`[bot:${n}] pc state: ${l}`),(l==="failed"||l==="disconnected"||l==="closed")&&this.close(`pc state ${l}`)},this.unsubscribe=e.subscribeInternal(t,n,l=>this.handleSignal(l)),await this.send({kind:"ring",callId:t,from:n,to:s}),this.opts.alwaysOffer||Eu(n)<Eu(s)){let l=await this.pc.createOffer({offerToReceiveAudio:!!this.opts.onAudioFrame,offerToReceiveVideo:!!this.opts.onVideoFrame});await this.pc.setLocalDescription(l),await this.send({kind:"offer",callId:t,from:n,to:s,sdp:l.sdp}),o(`[bot:${n}] role=caller, offer sent to ${s}`)}else o(`[bot:${n}] role=callee, waiting for offer from ${s}`)}async send(e){let t=await this.opts.broker.handleOutgoing(e);t.ok||this.opts.log(`[bot:${this.opts.botName}] send ${e.kind} -> ${e.to} failed: ${t.error}`)}async handleSignal(e){if(!(this.closed||!this.pc)&&e.callId===this.opts.callId)try{if(e.kind==="offer"){await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp});let t=await this.pc.createAnswer();await this.pc.setLocalDescription(t),await this.send({kind:"answer",callId:this.opts.callId,from:this.opts.botName,to:e.from,sdp:t.sdp})}else e.kind==="answer"?await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}):e.kind==="ice"?await this.pc.addIceCandidate(e.candidate):e.kind==="hangup"&&this.close(`hangup from ${e.from}`)}catch(t){this.opts.log(`[bot:${this.opts.botName}] signal ${e.kind} from ${e.from} failed: ${t.message}`)}}tapAudio(e){if(!Se)throw new Error("WebRtcBot.tapAudio called before loadWrtc \u2014 bug");let{RTCAudioSink:t}=Se,n=new t(e);n.ondata=s=>{this.closed||this.opts.onAudioFrame?.({samples:s.samples,sampleRate:s.sampleRate,channelCount:s.channelCount,receivedAt:Date.now()})},this.sinks.add({stop:()=>{try{n.stop()}catch{}}})}tapVideo(e){if(!Se)throw new Error("WebRtcBot.tapVideo called before loadWrtc \u2014 bug");let{RTCVideoSink:t}=Se;if(!t){this.opts.log(`[bot:${this.opts.botName}] this @roamhq/wrtc build has no RTCVideoSink \u2014 video ignored`);return}let n=new t(e);n.onframe=({frame:s})=>{this.closed||this.opts.onVideoFrame?.({width:s.width,height:s.height,data:s.data,rotation:s.rotation??0,receivedAt:Date.now()})},this.sinks.add({stop:()=>{try{n.stop()}catch{}}})}close(e){if(!this.closed){this.closed=!0,this.opts.log(`[bot:${this.opts.botName}] closing (${e})`);for(let t of this.sinks)t.stop();this.sinks.clear();try{this.unsubscribe?.()}catch{}try{this.pc?.close()}catch{}this.pc=void 0,this.opts.onClosed?.(e)}}};import{lstatSync as Dw,mkdirSync as Nw,rmSync as Ou,writeFileSync as jw}from"fs";import{join as zn,resolve as Lw}from"path";var Kn=class{constructor(e){this.opts=e}latest=null;count=0;lastSampledSeq=0;timer;busy=!1;stopped=!1;now(){return this.opts.now?.()??Date.now()}push(e){this.stopped||(this.count++,this.latest={frame:e,receivedAt:this.now(),seq:this.count})}take(){return this.latest}get received(){return this.count}start(){this.timer||this.stopped||!(this.opts.intervalMs>0)||!this.opts.onSample||(this.timer=setInterval(()=>{this.tick()},this.opts.intervalMs),this.timer.unref?.())}retime(e){this.stopped||(this.timer&&clearInterval(this.timer),this.timer=void 0,this.opts.intervalMs=e,this.start())}get intervalMs(){return this.timer?this.opts.intervalMs:0}async tick(){if(this.busy||this.stopped)return;let e=this.latest;if(!(!e||e.seq===this.lastSampledSeq)){this.lastSampledSeq=e.seq,this.busy=!0;try{await this.opts.onSample?.(e)}catch(t){this.opts.log?.(`[camera] sample ${e.seq} failed: ${t?.message??t}`)}finally{this.busy=!1}}}stop(){this.stopped=!0,this.timer&&clearInterval(this.timer),this.timer=void 0,this.latest=null}};import{deflateSync as Cw}from"zlib";var Pw=Buffer.from([137,80,78,71,13,10,26,10]),Pu=new Uint32Array(256);for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=e&1?3988292384^e>>>1:e>>>1;Pu[r]=e>>>0}function Mw(r){let e=4294967295;for(let t=0;t<r.length;t++)e=Pu[(e^r[t])&255]^e>>>8;return(e^4294967295)>>>0}function wi(r,e){let t=Buffer.alloc(8);t.writeUInt32BE(e.length,0),t.write(r,4,"ascii");let n=Buffer.alloc(4);return n.writeUInt32BE(Mw(Buffer.concat([t.subarray(4),e])),0),Buffer.concat([t,e,n])}function Mu(r,e,t){if(!Number.isInteger(e)||!Number.isInteger(t)||e<1||t<1)throw new Error(`encodePng: bad size ${e}x${t}`);if(r.length!==e*t*4)throw new Error(`encodePng: expected ${e*t*4} bytes for ${e}x${t} RGBA, got ${r.length}`);let n=Buffer.alloc(13);n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=8,n[9]=6,n[10]=0,n[11]=0,n[12]=0;let s=e*4,i=Buffer.alloc((s+1)*t),o=Buffer.from(r.buffer,r.byteOffset,r.byteLength);for(let a=0;a<t;a++)i[a*(s+1)]=0,o.copy(i,a*(s+1)+1,a*s,(a+1)*s);return Buffer.concat([Pw,wi("IHDR",n),wi("IDAT",Cw(i)),wi("IEND",Buffer.alloc(0))])}var bi=r=>r<0?0:r>255?255:Math.round(r);function ki(r){let{width:e,height:t,data:n}=r,s=e+1>>1,i=e*t,o=i,a=i+s*(t+1>>1);if(n.length<a+s*(t+1>>1))throw new Error(`i420ToRgba: ${n.length} bytes is too few for ${e}x${t}`);let c=new Uint8ClampedArray(e*t*4);for(let l=0;l<t;l++){let d=(l>>1)*s;for(let u=0;u<e;u++){let m=1.164*(n[l*e+u]-16),f=n[o+d+(u>>1)]-128,p=n[a+d+(u>>1)]-128,y=(l*e+u)*4;c[y]=bi(m+1.596*p),c[y+1]=bi(m-.392*f-.813*p),c[y+2]=bi(m+2.017*f),c[y+3]=255}}return{width:e,height:t,data:c}}function _w(r,e){let t=(Math.round(e/90)%4+4)%4;if(t===0)return r;let{width:n,height:s,data:i}=r,[o,a]=t===2?[n,s]:[s,n],c=new Uint8ClampedArray(o*a*4);for(let l=0;l<s;l++)for(let d=0;d<n;d++){let u=t===1?s-1-l:t===2?n-1-d:l,m=t===1?d:t===2?s-1-l:n-1-d,f=(l*n+d)*4,p=(m*o+u)*4;c[p]=i[f],c[p+1]=i[f+1],c[p+2]=i[f+2],c[p+3]=i[f+3]}return{width:o,height:a,data:c}}function Ow(r,e){let t=Math.max(r.width,r.height);if(!(e>0)||t<=e)return r;let n=e/t,s=Math.max(1,Math.round(r.width*n)),i=Math.max(1,Math.round(r.height*n)),o=new Uint8ClampedArray(s*i*4);for(let a=0;a<i;a++){let c=Math.min(r.height-1,Math.floor((a+.5)/n));for(let l=0;l<s;l++){let d=Math.min(r.width-1,Math.floor((l+.5)/n)),u=(c*r.width+d)*4,m=(a*s+l)*4;o[m]=r.data[u],o[m+1]=r.data[u+1],o[m+2]=r.data[u+2],o[m+3]=r.data[u+3]}}return{width:s,height:i,data:o}}function _u(r,e){let t=_w((e.toRgba??ki)(r),r.rotation??0),n=Ow(t,e.maxEdge);return{png:Mu(n.data,n.width,n.height),width:n.width,height:n.height}}var Yn=300,Du=20,Fw=/^[A-Za-z0-9_-]{4,64}$/,vi=r=>({channel:"voice",chatId:`voice:${r}`,sender:"Camera"});function Uw(r){let e=r.stream?(r.note?`You are watching while the owner works. They asked: "${r.note}" `:"You are watching while the owner works. ")+"Say only what matters now; if nothing changed or nothing needs saying, answer with one short sentence.":r.note?`The owner asks: "${r.note}"`:"Describe what you see, briefly.";return`[Camera] The owner is showing you their phone camera. The newest frame (${r.width}x${r.height} PNG, taken ${new Date(r.takenAt).toLocaleTimeString()}) is saved at:
195
195
  ${r.path}
196
- Open it with your Read tool and look at it. ${e} Your answer is read aloud on the phone, so keep it to one or two short plain sentences, with no lists or formatting, and say so if the picture is too dark or blurred to tell.`}var Qn=class{constructor(e){this.deps=e}watches=new Map;now(){return this.deps.now?.()??Date.now()}log(e){this.deps.log?.(`[camera] ${e}`)}async start(e){let t=String(e.callId??""),n=String(e.agentId??"").trim();if(!Fw.test(t))return{ok:!1,status:400,error:"callId must be 4 to 64 letters, digits, - or _"};let s=n?this.deps.agentName(n):null;if(s===null)return{ok:!1,status:404,error:`Unknown agent: ${n||"(none)"}`};if(this.watches.has(t))return{ok:!1,status:409,error:"an agent is already watching this share"};if(this.forAgent(n))return{ok:!1,status:409,error:`${n} is already watching a camera; stop that share first`};let i=this.deps.workspaceOf(n);if(!i)return{ok:!1,status:409,error:`${n} has no workspace to keep frames in`};let o;try{o=this.frameDir(i,t)}catch(f){return{ok:!1,status:500,error:f?.message??String(f)}}let a=this.deps.config(),c=this.now(),l={callId:t,agentId:n,agentName:s,startedAt:c,until:c+a.maxSessionMinutes*6e4,frames:0,looks:0,replies:[],session:e.session??vi(n),callRecordId:e.callRecordId??null,streamUntil:null},d=new Kn({intervalMs:a.frameIntervalSeconds*1e3,onSample:f=>this.sample(t,f),now:()=>this.now(),log:f=>this.log(f)}),u;try{u=await this.deps.startBot({callId:t,agentId:n,onFrame:f=>{d.push(f),l.frames=d.received},onClosed:f=>this.stop(t,f)})}catch(f){return d.stop(),{ok:!1,status:502,error:`could not join the share: ${f?.message??f}`}}let m=setTimeout(()=>this.stop(t,`time limit (${a.maxSessionMinutes} min)`),a.maxSessionMinutes*6e4);return m.unref?.(),this.watches.set(t,{view:l,sampler:d,bot:u,dir:o,timer:m,files:new Map,ending:!1,stream:null}),d.start(),this.log(`${n} is watching share ${t}`+(a.frameIntervalSeconds?` (a frame every ${a.frameIntervalSeconds} s)`:" (frames on demand)")),{ok:!0,watch:this.snapshotView(l)}}async look(e,t){let n=this.watches.get(e);if(!n)return{ok:!1,status:404,error:`No agent is watching share ${e}`};let s=String(t??"").replace(/\s+/g," ").trim();if(s.length>Yn)return{ok:!1,status:413,error:`the note is over ${Yn} characters`};let i=n.sampler.take();if(!i)return{ok:!1,status:409,error:"no picture has arrived from the phone yet"};let o=await this.handOver(n,i,s||null,"asked");return o.ok?{ok:!0,reply:o.reply,frame:o.frame}:o}stream(e,t,n){let s=this.watches.get(e);if(!s)return{ok:!1,status:404,error:`No agent is watching share ${e}`};let i=Number(t??0);if(!Number.isFinite(i)||i<0)return{ok:!1,status:400,error:"seconds must be 0 or more"};if(i===0)return this.endStream(s,"stopped by the owner"),{ok:!0,watch:this.snapshotView(s.view)};let o=String(n??"").replace(/\s+/g," ").trim();if(o.length>Yn)return{ok:!1,status:413,error:`the note is over ${Yn} characters`};let a=this.deps.config(),c=Math.min(Math.ceil(i),a.streamMaxSeconds)*1e3;s.stream&&clearTimeout(s.stream.timer);let l=setTimeout(()=>this.endStream(s,"time limit"),c);return l.unref?.(),s.stream={note:o||null,timer:l},s.view.streamUntil=Math.min(this.now()+c,s.view.until),s.sampler.retime(a.streamFrameSeconds*1e3),this.log(`${s.view.agentId} keeps watching share ${e}: a frame every ${a.streamFrameSeconds} s for ${c/1e3} s`),{ok:!0,watch:this.snapshotView(s.view)}}endStream(e,t){e.stream&&(clearTimeout(e.stream.timer),e.stream=null,e.view.streamUntil=null,e.ending||e.sampler.retime(this.deps.config().frameIntervalSeconds*1e3),this.log(`${e.view.agentId} stopped watching continuously on share ${e.view.callId} (${t})`))}snapshot(e){let t=this.forAgent(e);if(!t)return{ok:!1,status:404,error:`No live camera share for ${e}. Ask the owner to show you (agentx camera ask).`};let n=t.sampler.take();if(!n)return{ok:!1,status:409,error:"no picture has arrived from the phone yet; try again in a moment"};try{let s=this.writeFrame(t,n);return t.view.looks++,this.log(`${e} gets frame ${s.seq} of share ${t.view.callId} (its own look)`),{ok:!0,frame:s,callId:t.view.callId}}catch(s){return{ok:!1,status:500,error:`could not save the frame: ${s?.message??s}`}}}stop(e,t="stopped"){let n=this.watches.get(e);if(!n||n.ending)return!1;n.ending=!0,this.watches.delete(e),clearTimeout(n.timer),n.stream&&clearTimeout(n.stream.timer),n.sampler.stop();try{n.bot.close(t)}catch{}if(!this.deps.config().keepFrames)try{Ou(n.dir,{recursive:!0,force:!0})}catch(s){this.log(`could not delete ${n.dir}: ${s?.message??s}`)}this.log(`${n.view.agentId} stopped watching share ${e} (${t}; ${n.view.frames} frames, ${n.view.looks} looks)`);try{this.deps.onEnded?.(this.snapshotView(n.view),t)}catch(s){this.log(`onEnded threw: ${s?.message??s}`)}return!0}get(e){let t=this.watches.get(e);return t?this.snapshotView(t.view):void 0}active(){return[...this.watches.values()].map(e=>this.snapshotView(e.view))}watchingFor(e){let t=this.forAgent(e);return t?this.snapshotView(t.view):void 0}shutdown(){for(let e of[...this.watches.keys()])this.stop(e,"shutdown")}forAgent(e){for(let t of this.watches.values())if(t.view.agentId===e)return t}snapshotView(e){return{...e,replies:[...e.replies],session:{...e.session}}}async sample(e,t){let n=this.watches.get(e);if(!n)return;let s=n.stream,i=await this.handOver(n,t,s?s.note:null,s?"stream":"interval");if(!i.ok){this.log(`interval frame for ${e} not handed over: ${i.error}`);return}if(!s)try{await this.deps.deliver?.(this.snapshotView(n.view),i.reply)}catch(o){this.log(`deliver for ${e} failed: ${o?.message??o}`)}}async handOver(e,t,n,s){let i;try{i=this.writeFrame(e,t)}catch(l){return{ok:!1,status:500,error:`could not save the frame: ${l?.message??l}`}}e.view.looks++,this.log(`${e.view.agentId} gets frame ${i.seq} of share ${e.view.callId} (${s})`);let o=Uw({...i,note:n,stream:s==="stream"}),a;try{a=await this.deps.turn({agentId:e.view.agentId,message:o,session:e.view.session})}catch(l){a=null,this.log(`turn for ${e.view.callId} failed: ${l?.message??l}`)}if(this.deps.config().keepFrames||this.forget(e,i),!a?.trim())return{ok:!1,status:502,error:`${e.view.agentName} did not answer`};let c={at:this.now(),note:n,text:a.trim(),frame:i.path.slice(e.dir.length+1)};return e.view.replies.push(c),e.view.replies.length>Du&&e.view.replies.splice(0,e.view.replies.length-Du),{ok:!0,reply:c,frame:i}}writeFrame(e,t){let n=e.files.get(t.seq);if(n)return n;let{png:s,width:i,height:o}=_u(t.frame,{maxEdge:this.deps.config().maxFrameEdge,toRgba:this.deps.toRgba});Nw(e.dir,{recursive:!0});let a=zn(e.dir,`frame-${String(t.seq).padStart(6,"0")}.png`);jw(a,s);let c={path:a,width:i,height:o,takenAt:t.receivedAt,seq:t.seq};return e.files.set(t.seq,c),c}forget(e,t){if(e.files.delete(t.seq))try{Ou(t.path,{force:!0})}catch{}}frameDir(e,t){let n=Lw(this.deps.cwd?.()??process.cwd(),e);if(Dw(zn(n,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink())throw new Error(`${zn(n,".agentx")} is a link; frames are not written through it`);return zn(n,".agentx","camera",t)}};function ju(r){return r==="/webrtc/camera"||r.startsWith("/webrtc/camera/")}async function Lu(r,e,t,n,s={}){let{watch:i}=r;if(t==="/webrtc/camera/watch"){if(e==="GET")return{status:200,body:{active:i.active()}};if(e!=="POST")return{status:405,body:{error:"GET or POST"}};let l=String(n.callId??""),d=String(n.agentId??"").trim(),u,m,f=r.calls?.get(l);if(f){if(f.kind!=="camera")return{status:409,body:{error:`${l} is a voice call, not a camera ask`}};if(f.agentId!==d)return{status:403,body:{error:`${l} was asked by ${f.agentId}, not ${d||"(none)"}`}};if(f.status!=="answered")return{status:409,body:{error:`the owner has not accepted ${l} (it is ${f.status})`}};u=f.channel&&f.chatId?{channel:f.channel,chatId:f.chatId,sender:"Camera"}:vi(d),m=f.id}let p=await i.start({callId:l,agentId:d,session:u,callRecordId:m});return p.ok?{status:201,body:{watch:p.watch}}:{status:p.status,body:{error:p.error}}}if(t==="/webrtc/camera/look"){if(e!=="POST")return{status:405,body:{error:"POST"}};let l=String(n.agentId??"").trim();if(!l)return{status:400,body:{error:"Required: agentId"}};if(!r.isRunningTurn(l,s))return{status:403,body:{error:`No running turn of ${l} asked for this frame. An agent looks from inside its own run.`}};let d=i.snapshot(l);return d.ok?{status:200,body:{frame:d.frame,callId:d.callId}}:{status:d.status,body:{error:d.error}}}let[,,,,o,a,c]=t.split("/");if(t.split("/")[3]!=="watch"||!o||c!==void 0)return Nu;if(a===void 0){if(e!=="GET")return{status:405,body:{error:"GET"}};let l=i.get(o);return l?{status:200,body:{watch:l}}:{status:404,body:{error:`No agent is watching share ${o}`}}}if(e!=="POST")return{status:405,body:{error:"POST"}};switch(a){case"look":{let l=await i.look(o,n.note);if(!l.ok)return{status:l.status,body:{error:l.error}};let{width:d,height:u,takenAt:m,seq:f}=l.frame;return{status:200,body:{reply:l.reply,frame:{width:d,height:u,takenAt:m,seq:f}}}}case"stream":{let l=i.stream(o,n.seconds,n.note);return l.ok?{status:200,body:{watch:l.watch}}:{status:l.status,body:{error:l.error}}}case"stop":return i.stop(o,"stopped by the owner")?{status:200,body:{ok:!0}}:{status:404,body:{error:`No agent is watching share ${o}`}};default:return Nu}}var Nu={status:404,body:{error:"Not found"}};var Fu=`<!doctype html>
196
+ Open it with your Read tool and look at it. ${e} Your answer is read aloud on the phone, so keep it to one or two short plain sentences, with no lists or formatting, and say so if the picture is too dark or blurred to tell.`}var Qn=class{constructor(e){this.deps=e}watches=new Map;now(){return this.deps.now?.()??Date.now()}log(e){this.deps.log?.(`[camera] ${e}`)}async start(e){let t=String(e.callId??""),n=String(e.agentId??"").trim();if(!Fw.test(t))return{ok:!1,status:400,error:"callId must be 4 to 64 letters, digits, - or _"};let s=n?this.deps.agentName(n):null;if(s===null)return{ok:!1,status:404,error:`Unknown agent: ${n||"(none)"}`};if(this.watches.has(t))return{ok:!1,status:409,error:"an agent is already watching this share"};if(this.forAgent(n))return{ok:!1,status:409,error:`${n} is already watching a camera; stop that share first`};let i=this.deps.workspaceOf(n);if(!i)return{ok:!1,status:409,error:`${n} has no workspace to keep frames in`};let o;try{o=this.frameDir(i,t)}catch(f){return{ok:!1,status:500,error:f?.message??String(f)}}let a=this.deps.config(),c=this.now(),l={callId:t,agentId:n,agentName:s,startedAt:c,until:c+a.maxSessionMinutes*6e4,frames:0,looks:0,replies:[],session:e.session??vi(n),callRecordId:e.callRecordId??null,streamUntil:null},d=new Kn({intervalMs:a.frameIntervalSeconds*1e3,onSample:f=>this.sample(t,f),now:()=>this.now(),log:f=>this.log(f)}),u;try{u=await this.deps.startBot({callId:t,agentId:n,onFrame:f=>{d.push(f),l.frames=d.received},onClosed:f=>this.stop(t,f)})}catch(f){return d.stop(),{ok:!1,status:502,error:`could not join the share: ${f?.message??f}`}}let m=setTimeout(()=>this.stop(t,`time limit (${a.maxSessionMinutes} min)`),a.maxSessionMinutes*6e4);return m.unref?.(),this.watches.set(t,{view:l,sampler:d,bot:u,dir:o,timer:m,files:new Map,ending:!1,stream:null,turns:Promise.resolve()}),d.start(),this.log(`${n} is watching share ${t}`+(a.frameIntervalSeconds?` (a frame every ${a.frameIntervalSeconds} s)`:" (frames on demand)")),{ok:!0,watch:this.snapshotView(l)}}async look(e,t){let n=this.watches.get(e);if(!n)return{ok:!1,status:404,error:`No agent is watching share ${e}`};let s=String(t??"").replace(/\s+/g," ").trim();if(s.length>Yn)return{ok:!1,status:413,error:`the note is over ${Yn} characters`};let i=n.sampler.take();if(!i)return{ok:!1,status:409,error:"no picture has arrived from the phone yet"};let o=await this.handOver(n,i,s||null,"asked");return o.ok?{ok:!0,reply:o.reply,frame:o.frame}:o}stream(e,t,n){let s=this.watches.get(e);if(!s)return{ok:!1,status:404,error:`No agent is watching share ${e}`};let i=Number(t??0);if(!Number.isFinite(i)||i<0)return{ok:!1,status:400,error:"seconds must be 0 or more"};if(i===0)return this.endStream(s,"stopped by the owner"),{ok:!0,watch:this.snapshotView(s.view)};let o=String(n??"").replace(/\s+/g," ").trim();if(o.length>Yn)return{ok:!1,status:413,error:`the note is over ${Yn} characters`};let a=this.deps.config(),c=Math.min(Math.ceil(i),a.streamMaxSeconds)*1e3;s.stream&&clearTimeout(s.stream.timer);let l=setTimeout(()=>this.endStream(s,"time limit"),c);return l.unref?.(),s.stream={note:o||null,timer:l},s.view.streamUntil=Math.min(this.now()+c,s.view.until),s.sampler.retime(a.streamFrameSeconds*1e3),this.log(`${s.view.agentId} keeps watching share ${e}: a frame every ${a.streamFrameSeconds} s for ${c/1e3} s`),{ok:!0,watch:this.snapshotView(s.view)}}endStream(e,t){e.stream&&(clearTimeout(e.stream.timer),e.stream=null,e.view.streamUntil=null,e.ending||e.sampler.retime(this.deps.config().frameIntervalSeconds*1e3),this.log(`${e.view.agentId} stopped watching continuously on share ${e.view.callId} (${t})`))}snapshot(e){let t=this.forAgent(e);if(!t)return{ok:!1,status:404,error:`No live camera share for ${e}. Ask the owner to show you (agentx camera ask).`};let n=t.sampler.take();if(!n)return{ok:!1,status:409,error:"no picture has arrived from the phone yet; try again in a moment"};try{let s=this.writeFrame(t,n);return t.view.looks++,this.log(`${e} gets frame ${s.seq} of share ${t.view.callId} (its own look)`),{ok:!0,frame:s,callId:t.view.callId}}catch(s){return{ok:!1,status:500,error:`could not save the frame: ${s?.message??s}`}}}stop(e,t="stopped"){let n=this.watches.get(e);if(!n||n.ending)return!1;n.ending=!0,this.watches.delete(e),clearTimeout(n.timer),n.stream&&clearTimeout(n.stream.timer),n.sampler.stop();try{n.bot.close(t)}catch{}if(!this.deps.config().keepFrames)try{Ou(n.dir,{recursive:!0,force:!0})}catch(s){this.log(`could not delete ${n.dir}: ${s?.message??s}`)}this.log(`${n.view.agentId} stopped watching share ${e} (${t}; ${n.view.frames} frames, ${n.view.looks} looks)`);try{this.deps.onEnded?.(this.snapshotView(n.view),t)}catch(s){this.log(`onEnded threw: ${s?.message??s}`)}return!0}get(e){let t=this.watches.get(e);return t?this.snapshotView(t.view):void 0}active(){return[...this.watches.values()].map(e=>this.snapshotView(e.view))}watchingFor(e){let t=this.forAgent(e);return t?this.snapshotView(t.view):void 0}shutdown(){for(let e of[...this.watches.keys()])this.stop(e,"shutdown")}forAgent(e){for(let t of this.watches.values())if(t.view.agentId===e)return t}snapshotView(e){return{...e,replies:[...e.replies],session:{...e.session}}}async sample(e,t){let n=this.watches.get(e);if(!n)return;let s=n.stream,i=await this.handOver(n,t,s?s.note:null,s?"stream":"interval");if(!i.ok){this.log(`interval frame for ${e} not handed over: ${i.error}`);return}if(!s)try{await this.deps.deliver?.(this.snapshotView(n.view),i.reply)}catch(o){this.log(`deliver for ${e} failed: ${o?.message??o}`)}}handOver(e,t,n,s){let i=e.turns.then(()=>this.runTurn(e,t,n,s));return e.turns=i.then(()=>{},()=>{}),i}async runTurn(e,t,n,s){if(e.ending)return{ok:!1,status:404,error:`No agent is watching share ${e.view.callId}`};let i;try{i=this.writeFrame(e,t)}catch(l){return{ok:!1,status:500,error:`could not save the frame: ${l?.message??l}`}}e.view.looks++,this.log(`${e.view.agentId} gets frame ${i.seq} of share ${e.view.callId} (${s})`);let o=Uw({...i,note:n,stream:s==="stream"}),a;try{a=await this.deps.turn({agentId:e.view.agentId,message:o,session:e.view.session})}catch(l){a=null,this.log(`turn for ${e.view.callId} failed: ${l?.message??l}`)}if(this.deps.config().keepFrames||this.forget(e,i),!a?.trim())return{ok:!1,status:502,error:`${e.view.agentName} did not answer`};let c={at:this.now(),note:n,text:a.trim(),frame:i.path.slice(e.dir.length+1)};return e.view.replies.push(c),e.view.replies.length>Du&&e.view.replies.splice(0,e.view.replies.length-Du),{ok:!0,reply:c,frame:i}}writeFrame(e,t){let n=e.files.get(t.seq);if(n)return n;let{png:s,width:i,height:o}=_u(t.frame,{maxEdge:this.deps.config().maxFrameEdge,toRgba:this.deps.toRgba});Nw(e.dir,{recursive:!0});let a=zn(e.dir,`frame-${String(t.seq).padStart(6,"0")}.png`);jw(a,s);let c={path:a,width:i,height:o,takenAt:t.receivedAt,seq:t.seq};return e.files.set(t.seq,c),c}forget(e,t){if(e.files.delete(t.seq))try{Ou(t.path,{force:!0})}catch{}}frameDir(e,t){let n=Lw(this.deps.cwd?.()??process.cwd(),e);if(Dw(zn(n,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink())throw new Error(`${zn(n,".agentx")} is a link; frames are not written through it`);return zn(n,".agentx","camera",t)}};function ju(r){return r==="/webrtc/camera"||r.startsWith("/webrtc/camera/")}async function Lu(r,e,t,n,s={}){let{watch:i}=r;if(t==="/webrtc/camera/watch"){if(e==="GET")return{status:200,body:{active:i.active()}};if(e!=="POST")return{status:405,body:{error:"GET or POST"}};let l=String(n.callId??""),d=String(n.agentId??"").trim(),u,m,f=r.calls?.get(l);if(f){if(f.kind!=="camera")return{status:409,body:{error:`${l} is a voice call, not a camera ask`}};if(f.agentId!==d)return{status:403,body:{error:`${l} was asked by ${f.agentId}, not ${d||"(none)"}`}};if(f.status!=="answered")return{status:409,body:{error:`the owner has not accepted ${l} (it is ${f.status})`}};u=f.channel&&f.chatId?{channel:f.channel,chatId:f.chatId,sender:"Camera"}:vi(d),m=f.id}let p=await i.start({callId:l,agentId:d,session:u,callRecordId:m});return p.ok?{status:201,body:{watch:p.watch}}:{status:p.status,body:{error:p.error}}}if(t==="/webrtc/camera/look"){if(e!=="POST")return{status:405,body:{error:"POST"}};let l=String(n.agentId??"").trim();if(!l)return{status:400,body:{error:"Required: agentId"}};if(!r.isRunningTurn(l,s))return{status:403,body:{error:`No running turn of ${l} asked for this frame. An agent looks from inside its own run.`}};let d=i.snapshot(l);return d.ok?{status:200,body:{frame:d.frame,callId:d.callId}}:{status:d.status,body:{error:d.error}}}let[,,,,o,a,c]=t.split("/");if(t.split("/")[3]!=="watch"||!o||c!==void 0)return Nu;if(a===void 0){if(e!=="GET")return{status:405,body:{error:"GET"}};let l=i.get(o);return l?{status:200,body:{watch:l}}:{status:404,body:{error:`No agent is watching share ${o}`}}}if(e!=="POST")return{status:405,body:{error:"POST"}};switch(a){case"look":{let l=await i.look(o,n.note);if(!l.ok)return{status:l.status,body:{error:l.error}};let{width:d,height:u,takenAt:m,seq:f}=l.frame;return{status:200,body:{reply:l.reply,frame:{width:d,height:u,takenAt:m,seq:f}}}}case"stream":{let l=i.stream(o,n.seconds,n.note);return l.ok?{status:200,body:{watch:l.watch}}:{status:l.status,body:{error:l.error}}}case"stop":return i.stop(o,"stopped by the owner")?{status:200,body:{ok:!0}}:{status:404,body:{error:`No agent is watching share ${o}`}};default:return Nu}}var Nu={status:404,body:{error:"Not found"}};var Fu=`<!doctype html>
197
197
  <html lang="en">
198
198
  <head>
199
199
  <meta charset="utf-8">
@@ -520,7 +520,7 @@ ${l}`)}let S={agentId:o,message:k,context:{channel:y,sender:p?"opencode":"openai
520
520
 
521
521
  `)}}function Ku(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function zu(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}]})}
522
522
 
523
- `)}function Yu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ii(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 Ii(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Gt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Gt(`${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(Gt.levelOrder[e]<Gt.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)}},Ut=Gt;Ye(Ut,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as bb,statSync as kb}from"fs";var ut={version:"0.114.0",commit:"5762f07",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function vb(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 Zu(){let r=null;try{r=kb(bb(process.argv[1])).mtimeMs}catch{}let e=ku().version;return vb(ut,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Sb}from"crypto";var is=class{constructor(e=new oc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!$b.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Tb(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Sb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Ib(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}},$b=["run","task","signal","mesh","channel","status"];function Ib(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 Tb(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 eh(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 os,timingSafeEqual as th}from"crypto";var as=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[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(b[k]=S);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 m=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),p=m&&f?.triggers?.[m]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,m,i,c),p&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:p,entityRef:{kind:"webhook",id:`${l}:${i}:${m??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:m,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${m??"\u2014"}] -> workflow=${p} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:m,workflow:p,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${m}/${p}]: ${b.message}`)}let y=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${y.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${y.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(`
523
+ `)}function Yu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ii(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 Ii(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Gt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Gt(`${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(Gt.levelOrder[e]<Gt.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)}},Ut=Gt;Ye(Ut,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as bb,statSync as kb}from"fs";var ut={version:"0.114.1",commit:"2651483",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function vb(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 Zu(){let r=null;try{r=kb(bb(process.argv[1])).mtimeMs}catch{}let e=ku().version;return vb(ut,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Sb}from"crypto";var is=class{constructor(e=new oc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!$b.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Tb(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Sb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Ib(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}},$b=["run","task","signal","mesh","channel","status"];function Ib(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 Tb(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 eh(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 os,timingSafeEqual as th}from"crypto";var as=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[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(b[k]=S);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 m=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),p=m&&f?.triggers?.[m]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,m,i,c),p&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:p,entityRef:{kind:"webhook",id:`${l}:${i}:${m??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:m,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${m??"\u2014"}] -> workflow=${p} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:m,workflow:p,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${m}/${p}]: ${b.message}`)}let y=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${y.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${y.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(`
524
524
  `)[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(`
525
525
  `)[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??"?",m=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${m?`, ${m}`:""})`)}}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(`
526
526
  `)}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="+os("sha256",a).update(t).digest("hex");return ht(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?ht(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 m=os("sha256",a).update(`${u.t}.${t}`).digest("hex");return ht(m,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 m=parseInt(u,10);if(!Number.isFinite(m))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-m;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let p="POST",y=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],k=e.host,S=e["x-forwarded-proto"]||"https",$=new Set;b&&y&&$.add(`${S}://${b}${y}`),k&&y&&$.add(`https://${k}${y}`),k&&y&&$.add(`http://${k}${y}`),y&&$.add(y),$.add("");for(let R of $){let D=os("sha256",a).update(`${p}${R}${t}${u}`).digest("base64");if(d.length===D.length&&th(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${$.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let m=os("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return ht(m,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?ht(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?ht(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 ht(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return th(t,n)?null:"signature mismatch"}Zf();Vf();wa();function xb(r){return{insertTaskHistory:r.prepare(`
@@ -1145,4 +1145,4 @@ data: ${JSON.stringify(q)}
1145
1145
  `)}catch{}},O=setInterval(()=>{try{t.write(`: ping
1146
1146
 
1147
1147
  `)}catch{}},15e3);O.unref?.();let L=new AbortController;t.on("close",()=>{t.writableEnded||L.abort()});try{for await(let j of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:L.signal,vouchOwner:v}))A(j.event,j.data)}catch(j){A("error",{error:j?.message??String(j)})}finally{clearInterval(O);try{t.end()}catch{}}break}let x=h.context,E=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if($f(h,!0)==="callback"){let A=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:x});if(!("track"in A)){let O=rr(A);this.json(t,O.status,O.body);break}}if(h.async===!0){let A=x?.channel,O=x?.chatId;if(!A||!O){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let L=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:L,deliverTo:`${A}:${O}`,note:"result will be delivered to the originating chat when the peer finishes"});let j=h.peer,q=h.agent,he=this.mesh;(async()=>{let H=Date.now(),W;try{W=await he.sendTask(j,h.message,q,{vouchOwner:v,context:x,senderAgentId:E}),this.log(`[mesh/task async ${L}] ${j}/${q??"default"} finished in ${Date.now()-H}ms`)}catch(K){W=`Delegation to ${j}/${q??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${L}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:A,chatId:O,text:W,agentId:x?.agentId??E,accountId:x?.accountId})}catch(K){this.log(`[mesh/task async ${L}] delivery failed: ${K?.message??K}`)}})();break}let M=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:x,senderAgentId:E,vouchOwner:v});this.json(t,200,{response:M});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let g=await G(e);if(!g.kind||!g.callId||!g.from||!g.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=await this.webrtc.handleOutgoing(g);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let g=await G(e);if(!g.kind||!g.callId||!g.from||!g.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=this.webrtc.handleIncoming(g);this.json(t,w.ok?200:400,w);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 h=await G(e),g=h.callId,w=h.target,v=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!g||!w||!v){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:g,target:w,agentId:v});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 h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(g=>({urls:g})),...h.turnServers],peers:this.mesh?.directory().map(g=>({name:g.peer,healthy:g.healthy}))||[],camera:h.camera,agents:this.registry.list().map(g=>({id:g.id,name:g.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(h=>{let g=this.config.agents[h.id]||{},w=typeof g.description=="string"&&g.description.trim()||nI(g.systemPrompt)||`Agent "${h.name}" (${h.tier})`,v=Array.isArray(g.mentions)?g.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:w,tags:[h.tier,...v],color:ce(h.id,g).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),g=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,v=g?h.getAgentEntries(g):h.getSharedStore().listEntries({after:w});this.json(t,200,{nodeId:this.config.node.id,count:v.length,entries:v.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 h=this.registry.getWikiHub(),g=n.searchParams.get("agent");if(!g){this.json(t,400,{error:"?agent= required"});break}let v=h.getAgentWiki(g).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:g,articles:v.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),g=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!g||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=h.getAgentWiki(g).readArticle(w);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:g,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 /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let g=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),v=h.listByStatus(g,w);this.json(t,200,{nodeId:this.config.node.id,status:g,count:v.length,classifications:v});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 /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 G(e);await Qu(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=lp(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=Th();if(e==="json")return this.registry.getTodayUsage();let t=Ih(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||!It(n)))try{let s=Q(n,".claude","skills");Bf(s,{recursive:!0});let i=Q(s,dp);if(!It(i))ea(i,to(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=hp(an(i,"utf-8"),e);o&&(ea(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||!It(n))continue;let s=Sc(Ha(t),this.config.requests.enabled?vc():null);try{switch($c(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).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(s).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(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Hg(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 te(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 m=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${m}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:m}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(p=>p.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(p=>p.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(m=>m.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 relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await te(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.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}try{let c=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},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let m of l)!m.id||s.has(m.id)||(s.add(m.id),i.push({...m,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 m=await u.json();Array.isArray(m.chats)&&a(m.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 te(e)}catch{s={}}try{let i=await cp({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(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})}}},ta=na;Ye(ta,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function nI(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 te(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 sI(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 G(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)})}qf();function nL(r){typeof r=="string"&&(cn.error(r),process.exit(1)),r instanceof Error&&(cn.error(r.message),process.exit(1)),cn.error("Something went wrong. Please try again."),process.exit(1)}export{mI as a,ei as b,We as c,_t as d,Nt as e,Xe as f,Hn as g,ku as h,ph as i,Nb as j,jb as k,bh as l,Me as m,gt as n,Sh as o,pt as p,nR as q,sR as r,Zk as s,Xi as t,BE as u,WE as v,qE as w,Yg as x,Pv as y,zE as z,YE as A,qt as B,Ts as C,Vt as D,Ap as E,IS as F,mP as G,Es as H,fo as I,yo as J,Os as K,ce as L,fm as M,js as N,v0 as O,Em as P,$0 as Q,_m as R,Us as S,en as T,Ws as U,Vs as V,Fm as W,Po as X,De as Y,we as Z,Jm as _,Xm as $,Km as aa,zm as ba,ur as ca,Of as da,Yo as ea,Nf as fa,W$ as ga,_O as ha,ta as ia,nL as ja};
1148
- //# sourceMappingURL=chunk-QQIWLN3H.js.map
1148
+ //# sourceMappingURL=chunk-DOQ6Y7GZ.js.map