agentix-cli 0.121.0 → 0.121.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 (28) hide show
  1. package/dist/{agent-TQQOAVMU.js → agent-KR4B2G24.js} +2 -2
  2. package/dist/{board-dashboard-FNMZAP7A.js → board-dashboard-WBIQPRHQ.js} +2 -2
  3. package/dist/{chunk-2NGXOYTS.js → chunk-D7LGD7ZI.js} +69 -69
  4. package/dist/chunk-D7LGD7ZI.js.map +1 -0
  5. package/dist/{chunk-I4IDZSGF.js → chunk-FIB5LD6R.js} +4 -4
  6. package/dist/{chunk-RMA7KKR7.js → chunk-HVYS5ZBQ.js} +2 -2
  7. package/dist/chunk-KFSA2ZI7.js +4 -0
  8. package/dist/chunk-KFSA2ZI7.js.map +1 -0
  9. package/dist/{chunk-MORRCYJE.js → chunk-MSYBNVY3.js} +2 -2
  10. package/dist/cli.js +1 -1
  11. package/dist/index.d.ts +17 -2
  12. package/dist/index.js +1 -1
  13. package/dist/{program-OKPC77BN.js → program-4J6WMXLI.js} +128 -128
  14. package/dist/program-4J6WMXLI.js.map +1 -0
  15. package/dist/{registry-YHSHGJ4K.js → registry-XK2FTQZV.js} +2 -2
  16. package/dist/{wiki-F6EZBBUH.js → wiki-PAMLP6WO.js} +2 -2
  17. package/package.json +1 -1
  18. package/dist/chunk-2NGXOYTS.js.map +0 -1
  19. package/dist/chunk-DJQMG6TH.js +0 -4
  20. package/dist/chunk-DJQMG6TH.js.map +0 -1
  21. package/dist/program-OKPC77BN.js.map +0 -1
  22. /package/dist/{agent-TQQOAVMU.js.map → agent-KR4B2G24.js.map} +0 -0
  23. /package/dist/{board-dashboard-FNMZAP7A.js.map → board-dashboard-WBIQPRHQ.js.map} +0 -0
  24. /package/dist/{chunk-I4IDZSGF.js.map → chunk-FIB5LD6R.js.map} +0 -0
  25. /package/dist/{chunk-RMA7KKR7.js.map → chunk-HVYS5ZBQ.js.map} +0 -0
  26. /package/dist/{chunk-MORRCYJE.js.map → chunk-MSYBNVY3.js.map} +0 -0
  27. /package/dist/{registry-YHSHGJ4K.js.map → registry-XK2FTQZV.js.map} +0 -0
  28. /package/dist/{wiki-F6EZBBUH.js.map → wiki-PAMLP6WO.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{$ as gd,Aa as Td,B as Xl,Ba as Dn,Ca as Yr,Da as xd,Ea as Ad,F as Kl,Fa as Rd,Ga as Ed,H as zl,Ia as Cd,J as Yl,K as Vr,L as Ql,M as Pe,N as Zl,O as Pn,Pa as Pd,Q as Jr,Qa as Md,R as ed,S as Kr,T as Ge,U as ld,V as dd,Y as He,Z as ud,Za as Qr,_ as hd,_a as Zr,a as hl,aa as pd,ab as _d,b as Fr,ba as md,ca as fd,ea as de,f as Ur,fa as Mn,g as gl,ga as zr,h as pl,ha as yd,i as Ee,ia as _t,j as ml,ja as wd,k as fl,ka as ke,la as bd,m as yl,ma as kd,na as vd,o as wl,oa as _n,p as Cl,pa as On,q as Pl,qa as Sd,r as Ml,ra as $d,s as _l,t as Ol,u as Dl,v as Nl,wa as Id,z as Cn}from"./chunk-BWHHZJNJ.js";import{d as ll,g as dl,h as ul}from"./chunk-CAS2IWSM.js";import{m as kl,n as vl,o as Hr,p as Ce,r as Sl,s as pe}from"./chunk-S2GAEH2F.js";import{c as cd}from"./chunk-BGG3ZSMW.js";import{a as bl}from"./chunk-ZVP6GB4G.js";import{d as $l}from"./chunk-XGOBZCYC.js";import{g as Il}from"./chunk-LQE73AZR.js";import{b as Tl,c as xl}from"./chunk-2D3RYIDU.js";import{i as jl,m as qr,n as Ll,p as Fl,q as Ul,r as Gl,s as Hl,t as Bl,u as Wl}from"./chunk-7ZABMMSW.js";import{f as Br,g as Al,h as xn,i as An,k as Rn,m as Rl,n as El,o as Wr,p as En}from"./chunk-6FVFD5WU.js";import{a as ql}from"./chunk-PPUN7YHA.js";import{a as Vl,b as Jl}from"./chunk-VZLIBDLH.js";import{b as td,c as nd,d as Xr,e as sd,f as rd,g as id,h as od,i as ad}from"./chunk-EKJG63EJ.js";import{o as Gr}from"./chunk-H5Z42X7W.js";import{b as Tn}from"./chunk-EMGB23H5.js";import{A as fc,B as yc,C as wc,D as se,E as kc,F as vc,G as Sc,H as $c,I as Ic,J as Tc,K as xc,L as Xc,M as Kc,N as zc,O as Yc,P as Qc,Q as Zc,U as nl,a as Ha,b as Cr,c as Wa,ca as sl,d as Qa,e as Za,f as Et,h as Mr,i as _r,j as Or,k as ec,l as tc,s as nc,t as ic,u as Ct,v as oc,w as lc,x as B,z as mc}from"./chunk-2NGXOYTS.js";import{B as tl,a as sc,c as ac,d as cc,e as Ue,f as tt,l as Ac,m as Rc,o as Uc,p as Gc,q as qc,r as Vc,t as Jc,v as el}from"./chunk-7KY7EEEI.js";import{b as Dc,c as Nc,d as jr,f as vn,g as jc,h as Lc,i as Fc,j as Pt,k as Sn}from"./chunk-GLQLCBJS.js";import{a as Dr,b as rc}from"./chunk-6W74CHNW.js";import{A as rl,B as $n,C as il,h as da,n as ua,o as br}from"./chunk-RMA7KKR7.js";import{b as aa}from"./chunk-SFQUP3BP.js";import{a as Mt}from"./chunk-Y4CYQV7G.js";import{a as ol,b as In,c as al,d as cl}from"./chunk-LLNPKE7H.js";import{a as st,b as rt}from"./chunk-SHEUCITK.js";import{a as Ec,b as Nr,c as Cc,d as Pc,e as Mc,i as _c}from"./chunk-76Z4VHDX.js";import{b as bc}from"./chunk-W4YR2RO2.js";import{b as ne,d as nt,f as wn,g as bn,i as ie,j as Oc,k as Ae,l as Re,m as Wc,s as Lr}from"./chunk-25XR6QK2.js";import{a as Hc,b as Bc}from"./chunk-2IMK3NGJ.js";import{d as dc,e as uc,f as hc,g as gc,h as pc,j as kn}from"./chunk-X5C5W3E4.js";import{c as Ga}from"./chunk-MYVHVJWZ.js";import{d as qa,e as Va,f as Pr,g as yn,h as Ja,i as Xa,j as Ka,k as za,q as Ya}from"./chunk-AV7T3SYT.js";import{b as Ba}from"./chunk-56KNKUFF.js";import{d as ha,e as ty,m as La,n as hy,q as Fa,v as Ua,y as et,z as fn}from"./chunk-4GDLXWCH.js";import{a as Fe,b as Rt,f as Er}from"./chunk-72SZI2UW.js";import{a as kr,b as ey}from"./chunk-FCPTN6NF.js";import{a as dn,b as Zf}from"./chunk-7I7IEX4S.js";import{b as ca,e as la}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as cy,B as Aa,D as Ar,F as Ra,G as Ea,I as mn,J as Ca,K as Pa,L as Ma,M as _a,N as ly,Q as Oa,T as Da,U as Na,Y as dy,d as Ze,e as ga,f as vr,g as sy,h as un,i as Sr,j as hn,ja as Rr,ka as ja,l as je,m as $r,ma as uy,n as pa,o as ry,p as gn,q as iy,r as pn,s as ma,t as oy,z as xa}from"./chunk-OPNZWQ6Y.js";import{e as Le,f as fa,g as ya,h as Ir}from"./chunk-BRK6M6LA.js";import{a as wa,b as ba,c as ka,e as va,f as Tr,g as Sa,h as $a,i as xr,j as Ia,k as Ta,n as ay}from"./chunk-UIBUZ2N3.js";import{e as ny}from"./chunk-2QNT5JDS.js";import{d as Qe}from"./chunk-QIJLFPWE.js";import{existsSync as gy,readFileSync as py}from"fs";var Od=["answer","narration","line"];function Dd(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Nd(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||!Od.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Od.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()}:ei(i);case"front":return r.front(i)?{status:200,body:r.view()}:ei(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:ei(i)}default:return{status:404,body:{error:"Not found"}}}}function jd(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 gd,Aa as Td,B as Xl,Ba as Dn,Ca as Yr,Da as xd,Ea as Ad,F as Kl,Fa as Rd,Ga as Ed,H as zl,Ia as Cd,J as Yl,K as Vr,L as Ql,M as Pe,N as Zl,O as Pn,Pa as Pd,Q as Jr,Qa as Md,R as ed,S as Kr,T as Ge,U as ld,V as dd,Y as He,Z as ud,Za as Qr,_ as hd,_a as Zr,a as hl,aa as pd,ab as _d,b as Fr,ba as md,ca as fd,ea as de,f as Ur,fa as Mn,g as gl,ga as zr,h as pl,ha as yd,i as Ee,ia as _t,j as ml,ja as wd,k as fl,ka as ke,la as bd,m as yl,ma as kd,na as vd,o as wl,oa as _n,p as Cl,pa as On,q as Pl,qa as Sd,r as Ml,ra as $d,s as _l,t as Ol,u as Dl,v as Nl,wa as Id,z as Cn}from"./chunk-BWHHZJNJ.js";import{d as ll,g as dl,h as ul}from"./chunk-CAS2IWSM.js";import{m as kl,n as vl,o as Hr,p as Ce,r as Sl,s as pe}from"./chunk-S2GAEH2F.js";import{c as cd}from"./chunk-BGG3ZSMW.js";import{a as bl}from"./chunk-ZVP6GB4G.js";import{d as $l}from"./chunk-XGOBZCYC.js";import{g as Il}from"./chunk-LQE73AZR.js";import{b as Tl,c as xl}from"./chunk-2D3RYIDU.js";import{i as jl,m as qr,n as Ll,p as Fl,q as Ul,r as Gl,s as Hl,t as Bl,u as Wl}from"./chunk-7ZABMMSW.js";import{f as Br,g as Al,h as xn,i as An,k as Rn,m as Rl,n as El,o as Wr,p as En}from"./chunk-6FVFD5WU.js";import{a as ql}from"./chunk-PPUN7YHA.js";import{a as Vl,b as Jl}from"./chunk-VZLIBDLH.js";import{b as td,c as nd,d as Xr,e as sd,f as rd,g as id,h as od,i as ad}from"./chunk-EKJG63EJ.js";import{o as Gr}from"./chunk-H5Z42X7W.js";import{b as Tn}from"./chunk-EMGB23H5.js";import{A as fc,B as yc,C as wc,D as se,E as kc,F as vc,G as Sc,H as $c,I as Ic,J as Tc,K as xc,L as Xc,M as Kc,N as zc,O as Yc,P as Qc,Q as Zc,U as nl,a as Ha,b as Cr,c as Wa,ca as sl,d as Qa,e as Za,f as Et,h as Mr,i as _r,j as Or,k as ec,l as tc,s as nc,t as ic,u as Ct,v as oc,w as lc,x as B,z as mc}from"./chunk-D7LGD7ZI.js";import{B as tl,a as sc,c as ac,d as cc,e as Ue,f as tt,l as Ac,m as Rc,o as Uc,p as Gc,q as qc,r as Vc,t as Jc,v as el}from"./chunk-7KY7EEEI.js";import{b as Dc,c as Nc,d as jr,f as vn,g as jc,h as Lc,i as Fc,j as Pt,k as Sn}from"./chunk-GLQLCBJS.js";import{a as Dr,b as rc}from"./chunk-6W74CHNW.js";import{A as rl,B as $n,C as il,h as da,n as ua,o as br}from"./chunk-HVYS5ZBQ.js";import{b as aa}from"./chunk-SFQUP3BP.js";import{a as Mt}from"./chunk-Y4CYQV7G.js";import{a as ol,b as In,c as al,d as cl}from"./chunk-LLNPKE7H.js";import{a as st,b as rt}from"./chunk-SHEUCITK.js";import{a as Ec,b as Nr,c as Cc,d as Pc,e as Mc,i as _c}from"./chunk-76Z4VHDX.js";import{b as bc}from"./chunk-W4YR2RO2.js";import{b as ne,d as nt,f as wn,g as bn,i as ie,j as Oc,k as Ae,l as Re,m as Wc,s as Lr}from"./chunk-25XR6QK2.js";import{a as Hc,b as Bc}from"./chunk-2IMK3NGJ.js";import{d as dc,e as uc,f as hc,g as gc,h as pc,j as kn}from"./chunk-X5C5W3E4.js";import{c as Ga}from"./chunk-MYVHVJWZ.js";import{d as qa,e as Va,f as Pr,g as yn,h as Ja,i as Xa,j as Ka,k as za,q as Ya}from"./chunk-AV7T3SYT.js";import{b as Ba}from"./chunk-56KNKUFF.js";import{d as ha,e as ty,m as La,n as hy,q as Fa,v as Ua,y as et,z as fn}from"./chunk-4GDLXWCH.js";import{a as Fe,b as Rt,f as Er}from"./chunk-72SZI2UW.js";import{a as kr,b as ey}from"./chunk-FCPTN6NF.js";import{a as dn,b as Zf}from"./chunk-7I7IEX4S.js";import{b as ca,e as la}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as cy,B as Aa,D as Ar,F as Ra,G as Ea,I as mn,J as Ca,K as Pa,L as Ma,M as _a,N as ly,Q as Oa,T as Da,U as Na,Y as dy,d as Ze,e as ga,f as vr,g as sy,h as un,i as Sr,j as hn,ja as Rr,ka as ja,l as je,m as $r,ma as uy,n as pa,o as ry,p as gn,q as iy,r as pn,s as ma,t as oy,z as xa}from"./chunk-OPNZWQ6Y.js";import{e as Le,f as fa,g as ya,h as Ir}from"./chunk-BRK6M6LA.js";import{a as wa,b as ba,c as ka,e as va,f as Tr,g as Sa,h as $a,i as xr,j as Ia,k as Ta,n as ay}from"./chunk-UIBUZ2N3.js";import{e as ny}from"./chunk-2QNT5JDS.js";import{d as Qe}from"./chunk-QIJLFPWE.js";import{existsSync as gy,readFileSync as py}from"fs";var Od=["answer","narration","line"];function Dd(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Nd(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||!Od.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Od.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()}:ei(i);case"front":return r.front(i)?{status:200,body:r.view()}:ei(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:ei(i)}default:return{status:404,body:{error:"Not found"}}}}function jd(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 ei=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as my}from"path";var fy={name:"agentx",version:"0.1.0"},yy="2024-11-05",wy={tools:{},elicitation:{form:{}}},by=0;async function Ld(r,e){let t=++by;return Be({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Ot.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Ot.has(`elicit-${t}`)&&(Ot.delete(`elicit-${t}`),n(null))},6e4)})}var Ot=new Map,ky="http://localhost:19900",ti;function vy(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=my(process.cwd(),r);if(!gy(e))continue;let t=JSON.parse(py(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 ky}function V(){return ti===void 0&&(ti=vy()),ti}function si(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 Sy(){let r=process.env.AGENTX_AGENT_ID,e=si();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 $y=/\x1B\[[0-9;]*[A-Za-z]/g;function it(r){return r.replace($y,"")}async function Iy(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:Ty(i,!!s.hasMore)}]}}function Ty(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:Ay(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-MJLXMXN5.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-QTGNWXUA.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-BQUKONSF.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-F6EZBBUH.js"),{agenticQuery:i}=await import("./query-4OPS5PET.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 I=o(c.getAgentWiki(S).baseDir,"_index.md");if(k(I)){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 Sy(),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-MJLXMXN5.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-QTGNWXUA.js");return{content:[{type:"text",text:await n(e,{daemonUrl:V()})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-BQUKONSF.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-PAMLP6WO.js"),{agenticQuery:i}=await import("./query-4OPS5PET.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 I=o(c.getAgentWiki(S).baseDir,"_index.md");if(k(I)){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 Sy(),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):
@@ -520,7 +520,7 @@ ${l}`)}let S={agentId:o,message:k,context:{channel:y,sender:p?"opencode":"openai
520
520
 
521
521
  `)}}function Zu(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function eh(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 th(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ri(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 Ri(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Bt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Bt(`${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(Bt.levelOrder[e]<Bt.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)}},Ht=Bt;Qe(Ht,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Rb,statSync as Eb}from"fs";var ht={version:"0.121.0",commit:"367cc6e",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Cb(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 sh(){let r=null;try{r=Eb(Rb(process.argv[1])).mtimeMs}catch{}let e=Iu().version;return Cb(ht,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Pb}from"crypto";var ls=class{constructor(e=new lc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Mb.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Ob(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Pb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=_b(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}},Mb=["run","task","signal","mesh","channel","status"];function _b(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 Ob(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 rh(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 ds,timingSafeEqual as ih}from"crypto";var us=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 th(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ri(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 Ri(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Bt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Bt(`${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(Bt.levelOrder[e]<Bt.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)}},Ht=Bt;Qe(Ht,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Rb,statSync as Eb}from"fs";var ht={version:"0.121.1",commit:"8bdc9d7",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Cb(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 sh(){let r=null;try{r=Eb(Rb(process.argv[1])).mtimeMs}catch{}let e=Iu().version;return Cb(ht,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Pb}from"crypto";var ls=class{constructor(e=new lc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Mb.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Ob(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Pb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=_b(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}},Mb=["run","task","signal","mesh","channel","status"];function _b(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 Ob(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 rh(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 ds,timingSafeEqual as ih}from"crypto";var us=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="+ds("sha256",a).update(t).digest("hex");return gt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?gt(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=ds("sha256",a).update(`${u.t}.${t}`).digest("hex");return gt(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",I=new Set;b&&y&&I.add(`${S}://${b}${y}`),k&&y&&I.add(`https://${k}${y}`),k&&y&&I.add(`http://${k}${y}`),y&&I.add(y),I.add("");for(let E of I){let D=ds("sha256",a).update(`${p}${E}${t}${u}`).digest("base64");if(d.length===D.length&&ih(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${I.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let m=ds("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return gt(m,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?gt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?gt(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 gt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return ih(t,n)?null:"signature mismatch"}ay();ey();va();function Db(r){return{insertTaskHistory:r.prepare(`
@@ -1144,4 +1144,4 @@ data: ${JSON.stringify(q)}
1144
1144
  `)}catch{}},O=setInterval(()=>{try{t.write(`: ping
1145
1145
 
1146
1146
  `)}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}))x(j.event,j.data)}catch(j){x("error",{error:j?.message??String(j)})}finally{clearInterval(O);try{t.end()}catch{}}break}let A=h.context,R=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(Cf(h,!0)==="callback"){let x=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:A});if(!("track"in x)){let O=ar(x);this.json(t,O.status,O.body);break}}if(h.async===!0){let x=A?.channel,O=A?.chatId;if(!x||!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:`${x}:${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:A,senderAgentId:R}),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:x,chatId:O,text:W,agentId:A?.agentId??R,accountId:A?.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:A,senderAgentId:R,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 $=await this.botManager.invite({callId:g,target:w,agentId:v});this.json(t,$.ok?200:500,$);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()||uI(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($=>({id:$.id,date:$.date,agentId:$.agentId,source:$.source,sourceContext:$.sourceContext,content:$.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 $=h.getAgentWiki(g).readArticle(w);if(!$){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:g,path:$.path,title:$.meta.title,tags:$.meta.tags,owner:$.meta.owner,created:$.meta.created,lastUpdated:$.meta.lastUpdated,sources:$.meta.sources,content:$.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 nh(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=gp(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=Eh();if(e==="json")return this.registry.getTodayUsage();let t=Rh(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||!xt(n)))try{let s=Q(n,".claude","skills");Yf(s,{recursive:!0});let i=Q(s,pp);if(!xt(i))sa(i,io(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=fp(ln(i,"utf-8"),e);o&&(sa(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||!xt(n))continue;let s=Tc(qa(t),this.config.requests.enabled?Ic():null);try{switch(xc(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 Vg(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 Z(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 postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await Z(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-325SXDGN.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return $l(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await Z(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-325SXDGN.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let 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 Z(e)}catch{s={}}try{let i=await hp({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})}}},ra=ia;Qe(ra,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function uI(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 Z(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 hI(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)})}Zf();function gL(r){typeof r=="string"&&(dn.error(r),process.exit(1)),r instanceof Error&&(dn.error(r.message),process.exit(1)),dn.error("Something went wrong. Please try again."),process.exit(1)}export{II as a,ri as b,We as c,Dt as d,Lt as e,Xe as f,Vn as g,Iu as h,wh as i,qb as j,Vb as k,$h as l,Me as m,pt as n,xh as o,mt as p,uR as q,hR as r,cv as s,Qi as t,QE as u,ZE as v,eC as w,tp as x,Uv as y,iC as z,oC as A,Jt as B,kt as C,Xt as D,MC as E,_p as F,PS as G,TP as H,Ms as I,bo as J,ko as K,js as L,ce as M,Sm as N,Us as O,R0 as P,Dm as Q,C0 as R,Fm as S,Bs as T,nn as U,Js as V,Ks as W,qm as X,Oo as Y,De as Z,we as _,Zm as $,ef as aa,tf as ba,nf as ca,mr as da,Hf as ea,ea as fa,Wf as ga,Z$ as ha,BO as ia,ra as ja,gL as ka};
1147
- //# sourceMappingURL=chunk-I4IDZSGF.js.map
1147
+ //# sourceMappingURL=chunk-FIB5LD6R.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-YHSHGJ4K.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-XK2FTQZV.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-RMA7KKR7.js.map
126
+ //# sourceMappingURL=chunk-HVYS5ZBQ.js.map
@@ -0,0 +1,4 @@
1
+ import{a as c}from"./chunk-IKBWV7YJ.js";import{resolve as a}from"path";import{existsSync as h,readdirSync as y,mkdirSync as l,readFileSync as u,writeFileSync as p,renameSync as f}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=a(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=a(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new c(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=a(this.agentsDir,e,this.mode),i=new c(t,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(h(this.agentsDir))for(let t of y(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let i=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let s of r)g.entries[s]={at:d,cited:i.has(s)};let n=this.ledgerPath(e);l(a(n,".."),{recursive:!0});let o=`${n}.tmp`;p(o,`${JSON.stringify(g,null,2)}
2
+ `),f(o,n)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let i=r.get(t.agentId);i?i.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:i,cited:g,read:d,pending:n,articles:o}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:i.length,totalArticles:o.length,cited:g.length,readNotCited:d.length,unabsorbed:n.length,articles:o}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,i=new Set;for(let s of t)if(s.sources)for(let S of s.sources)i.add(S);let g=this.readLedger(e).entries,d=[],n=[],o=[];for(let s of r)i.has(s.id)?d.push(s):g[s.id]?n.push(s):o.push(s);return{all:r,cited:d,read:n,pending:o,articles:t}}syncedFrom(e){let r=a(this.agentsDir,e,"_synced.json");if(!h(r))return null;try{return JSON.parse(u(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=a(this.agentsDir,e,"_synced.json");l(a(t,".."),{recursive:!0});let i=`${t}.tmp`;p(i,`${JSON.stringify(r,null,2)}
3
+ `),f(i,t)}ledgerPath(e){return a(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!h(r))return{entries:{}};try{return{entries:JSON.parse(u(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
4
+ //# sourceMappingURL=chunk-KFSA2ZI7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync, readFileSync, writeFileSync, renameSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n listAgents(entries: WikiEntry[] = this.sharedStore.listEntries()): string[] {\n const agents = new Set<string>()\n\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n /**\n * Entries absorb has not dealt with yet: no article cites them and no\n * successful absorb run has read them. Without the second check an\n * entry absorb read and chose not to cite came back on every run, and\n * a backfill kept re-reading the head of the queue (#762).\n */\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n return this.classifyEntries(agentId).pending\n }\n\n /**\n * Record every entry handed to the model in a successful absorb run,\n * cited or not. Callers must not call this for a failed run, so those\n * entries are offered again.\n */\n markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void {\n const cited = new Set(citedIds)\n const ledger = this.readLedger(agentId)\n const at = new Date().toISOString()\n for (const id of entryIds) ledger.entries[id] = { at, cited: cited.has(id) }\n\n const file = this.ledgerPath(agentId)\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(ledger, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /**\n * Counts and articles per agent, for `GET /wiki/agents` and the mesh.\n * The raw entries are read once and grouped here: reading them again\n * per agent made the endpoint take 25 to 75 s on a fleet with 30\n * agents and 10k entries, past the mesh client's 5 s timeout (#603).\n */\n summary(): AgentWikiSummary[] {\n const entries = this.sharedStore.listEntries()\n const byAgent = new Map<string, WikiEntry[]>()\n for (const e of entries) {\n const list = byAgent.get(e.agentId)\n if (list) list.push(e)\n else byAgent.set(e.agentId, [e])\n }\n return this.listAgents(entries).map(agentId => {\n const { all, cited, read, pending, articles } = this.classifyEntries(agentId, byAgent.get(agentId) ?? [])\n return {\n agentId,\n totalEntries: all.length,\n totalArticles: articles.length,\n cited: cited.length,\n readNotCited: read.length,\n unabsorbed: pending.length,\n articles,\n }\n })\n }\n\n /** Split an agent's entries into cited by an article, read but not cited, and pending. */\n private classifyEntries(agentId: string, all: WikiEntry[] = this.getAgentEntries(agentId)) {\n const articles = this.getAgentWiki(agentId).rebuildIndex().articles\n\n const citedIds = new Set<string>()\n for (const article of articles) {\n if (article.sources) {\n for (const s of article.sources) citedIds.add(s)\n }\n }\n const ledger = this.readLedger(agentId).entries\n\n const cited: WikiEntry[] = []\n const read: WikiEntry[] = []\n const pending: WikiEntry[] = []\n for (const e of all) {\n if (citedIds.has(e.id)) cited.push(e)\n else if (ledger[e.id]) read.push(e)\n else pending.push(e)\n }\n return { all, cited, read, pending, articles }\n }\n\n /**\n * The peer an agent's articles were copied from by `wiki sync --articles`,\n * or null for an agent this node absorbs itself. A copied agent is\n * read-only here: absorb and patch leave it to its home node.\n */\n syncedFrom(agentId: string): SyncedFrom | null {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n if (!existsSync(file)) return null\n try {\n return JSON.parse(readFileSync(file, \"utf-8\")) as SyncedFrom\n } catch (err) {\n // A damaged marker still means the agent lives elsewhere.\n this.log(`synced marker ${file} is not valid JSON: ${(err as Error).message}`)\n return { node: \"unknown\", peerUrl: \"\", at: \"\" }\n }\n }\n\n markSynced(agentId: string, from: SyncedFrom): void {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(from, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /** agents/<id>/_absorbed.json — shared by every mode, like the raw entries. */\n private ledgerPath(agentId: string): string {\n return resolve(this.agentsDir, agentId, \"_absorbed.json\")\n }\n\n private readLedger(agentId: string): AbsorbLedger {\n const file = this.ledgerPath(agentId)\n if (!existsSync(file)) return { entries: {} }\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\")) as AbsorbLedger\n return { entries: parsed.entries ?? {} }\n } catch (err) {\n // Treating a damaged ledger as empty would let the next run\n // overwrite it and re-queue everything it recorded.\n throw new Error(`absorb ledger ${file} is not valid JSON: ${(err as Error).message}`)\n }\n }\n}\n\nexport interface SyncedFrom {\n /** The peer's node id. */\n node: string\n peerUrl: string\n /** When the last copy finished. */\n at: string\n}\n\ninterface AbsorbLedger {\n entries: Record<string, { at: string; cited: boolean }>\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n /** Entries an article cites. */\n cited: number\n /** Entries a successful absorb run read and did not cite. */\n readNotCited: number\n /** Entries absorb has not read yet. */\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,WAAAA,MAAe,OACxB,OAAS,cAAAC,EAAY,eAAAC,EAAa,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KAerF,IAAMC,EAAN,KAAc,CACX,QACA,UACA,KACA,YACA,YAAsC,IAAI,IAC1C,IAER,YACEC,EAAkBR,EAAQ,QAAQ,IAAI,EAAG,cAAc,EACvDS,EAAoC,QAAQ,MAAM,KAAK,QAAS,YAAY,EAC5EC,EAAiB,QACjB,CACA,KAAK,QAAUF,EACf,KAAK,UAAYR,EAAQQ,EAAS,QAAQ,EAC1C,KAAK,KAAOE,EACZ,KAAK,IAAMD,EAEXN,EAAU,KAAK,UAAW,CAAE,UAAW,EAAK,CAAC,EAC7C,KAAK,YAAc,IAAIQ,EAAUH,EAASC,CAAG,CAC/C,CAEA,SAAoB,CAAE,OAAO,KAAK,IAAK,CAOvC,aAAaG,EAA4B,CACvC,IAAMC,EAAM,GAAGD,KAAW,KAAK,OAC/B,GAAI,KAAK,YAAY,IAAIC,CAAG,EAAG,OAAO,KAAK,YAAY,IAAIA,CAAG,EAE9D,IAAMC,EAAWd,EAAQ,KAAK,UAAWY,EAAS,KAAK,IAAI,EACrDG,EAAQ,IAAIJ,EAAUG,EAAU,KAAK,GAAG,EAC9C,YAAK,YAAY,IAAID,EAAKE,CAAK,EACxBA,CACT,CAGA,YAAqB,CACnB,OAAO,KAAK,OACd,CAEA,gBAA4B,CAC1B,OAAO,KAAK,WACd,CAEA,WAAWC,EAAuB,KAAK,YAAY,YAAY,EAAa,CAC1E,IAAMC,EAAS,IAAI,IAEnB,QAAWC,KAAKF,EAASC,EAAO,IAAIC,EAAE,OAAO,EAE7C,GAAIjB,EAAW,KAAK,SAAS,EAC3B,QAAWkB,KAAOjB,EAAY,KAAK,SAAS,EACtC,CAACiB,EAAI,WAAW,GAAG,GAAK,CAACA,EAAI,WAAW,GAAG,GAC7CF,EAAO,IAAIE,CAAG,EAKpB,MAAO,CAAC,GAAGF,CAAM,EAAE,KAAK,CAC1B,CAEA,gBAAgBL,EAA8B,CAC5C,OAAO,KAAK,YAAY,YAAY,CAAE,QAAAA,CAAQ,CAAC,CACjD,CAQA,qBAAqBA,EAA8B,CACjD,OAAO,KAAK,gBAAgBA,CAAO,EAAE,OACvC,CAOA,cAAcA,EAAiBQ,EAAoBC,EAAkC,CACnF,IAAMC,EAAQ,IAAI,IAAID,CAAQ,EACxBE,EAAS,KAAK,WAAWX,CAAO,EAChCY,EAAK,IAAI,KAAK,EAAE,YAAY,EAClC,QAAWC,KAAML,EAAUG,EAAO,QAAQE,CAAE,EAAI,CAAE,GAAAD,EAAI,MAAOF,EAAM,IAAIG,CAAE,CAAE,EAE3E,IAAMC,EAAO,KAAK,WAAWd,CAAO,EACpCT,EAAUH,EAAQ0B,EAAM,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,IAAMC,EAAM,GAAGD,QACfrB,EAAcsB,EAAK,GAAG,KAAK,UAAUJ,EAAQ,KAAM,CAAC;AAAA,CAAK,EACzDjB,EAAWqB,EAAKD,CAAI,CACtB,CAQA,SAA8B,CAC5B,IAAMV,EAAU,KAAK,YAAY,YAAY,EACvCY,EAAU,IAAI,IACpB,QAAWV,KAAKF,EAAS,CACvB,IAAMa,EAAOD,EAAQ,IAAIV,EAAE,OAAO,EAC9BW,EAAMA,EAAK,KAAKX,CAAC,EAChBU,EAAQ,IAAIV,EAAE,QAAS,CAACA,CAAC,CAAC,EAEjC,OAAO,KAAK,WAAWF,CAAO,EAAE,IAAIJ,GAAW,CAC7C,GAAM,CAAE,IAAAkB,EAAK,MAAAR,EAAO,KAAAS,EAAM,QAAAC,EAAS,SAAAC,CAAS,EAAI,KAAK,gBAAgBrB,EAASgB,EAAQ,IAAIhB,CAAO,GAAK,CAAC,CAAC,EACxG,MAAO,CACL,QAAAA,EACA,aAAckB,EAAI,OAClB,cAAeG,EAAS,OACxB,MAAOX,EAAM,OACb,aAAcS,EAAK,OACnB,WAAYC,EAAQ,OACpB,SAAAC,CACF,CACF,CAAC,CACH,CAGQ,gBAAgBrB,EAAiBkB,EAAmB,KAAK,gBAAgBlB,CAAO,EAAG,CACzF,IAAMqB,EAAW,KAAK,aAAarB,CAAO,EAAE,aAAa,EAAE,SAErDS,EAAW,IAAI,IACrB,QAAWa,KAAWD,EACpB,GAAIC,EAAQ,QACV,QAAWC,KAAKD,EAAQ,QAASb,EAAS,IAAIc,CAAC,EAGnD,IAAMZ,EAAS,KAAK,WAAWX,CAAO,EAAE,QAElCU,EAAqB,CAAC,EACtBS,EAAoB,CAAC,EACrBC,EAAuB,CAAC,EAC9B,QAAWd,KAAKY,EACVT,EAAS,IAAIH,EAAE,EAAE,EAAGI,EAAM,KAAKJ,CAAC,EAC3BK,EAAOL,EAAE,EAAE,EAAGa,EAAK,KAAKb,CAAC,EAC7Bc,EAAQ,KAAKd,CAAC,EAErB,MAAO,CAAE,IAAAY,EAAK,MAAAR,EAAO,KAAAS,EAAM,QAAAC,EAAS,SAAAC,CAAS,CAC/C,CAOA,WAAWrB,EAAoC,CAC7C,IAAMc,EAAO1B,EAAQ,KAAK,UAAWY,EAAS,cAAc,EAC5D,GAAI,CAACX,EAAWyB,CAAI,EAAG,OAAO,KAC9B,GAAI,CACF,OAAO,KAAK,MAAMtB,EAAasB,EAAM,OAAO,CAAC,CAC/C,OAASU,EAAP,CAEA,YAAK,IAAI,iBAAiBV,wBAA4BU,EAAc,SAAS,EACtE,CAAE,KAAM,UAAW,QAAS,GAAI,GAAI,EAAG,CAChD,CACF,CAEA,WAAWxB,EAAiByB,EAAwB,CAClD,IAAMX,EAAO1B,EAAQ,KAAK,UAAWY,EAAS,cAAc,EAC5DT,EAAUH,EAAQ0B,EAAM,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,IAAMC,EAAM,GAAGD,QACfrB,EAAcsB,EAAK,GAAG,KAAK,UAAUU,EAAM,KAAM,CAAC;AAAA,CAAK,EACvD/B,EAAWqB,EAAKD,CAAI,CACtB,CAGQ,WAAWd,EAAyB,CAC1C,OAAOZ,EAAQ,KAAK,UAAWY,EAAS,gBAAgB,CAC1D,CAEQ,WAAWA,EAA+B,CAChD,IAAMc,EAAO,KAAK,WAAWd,CAAO,EACpC,GAAI,CAACX,EAAWyB,CAAI,EAAG,MAAO,CAAE,QAAS,CAAC,CAAE,EAC5C,GAAI,CAEF,MAAO,CAAE,QADM,KAAK,MAAMtB,EAAasB,EAAM,OAAO,CAAC,EAC5B,SAAW,CAAC,CAAE,CACzC,OAASU,EAAP,CAGA,MAAM,IAAI,MAAM,iBAAiBV,wBAA4BU,EAAc,SAAS,CACtF,CACF,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","readFileSync","writeFileSync","renameSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","entries","agents","e","dir","entryIds","citedIds","cited","ledger","at","id","file","tmp","byAgent","list","all","read","pending","articles","article","s","err","from"]}
@@ -1,4 +1,4 @@
1
- import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-SCJ5ZXEN.js";import{a as de,b as le}from"./chunk-BGG3ZSMW.js";import{b as ae}from"./chunk-WCXXXAHV.js";import{c as oe,e as ie}from"./chunk-LQE73AZR.js";import{i as F,k as se}from"./chunk-6FVFD5WU.js";import{a as ne,b as re}from"./chunk-2IMK3NGJ.js";import{a as te}from"./chunk-DJQMG6TH.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as W,ma as j,w as L,x as Q}from"./chunk-OPNZWQ6Y.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function U(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
1
+ import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-SCJ5ZXEN.js";import{a as de,b as le}from"./chunk-BGG3ZSMW.js";import{b as ae}from"./chunk-WCXXXAHV.js";import{c as oe,e as ie}from"./chunk-LQE73AZR.js";import{i as F,k as se}from"./chunk-6FVFD5WU.js";import{a as ne,b as re}from"./chunk-2IMK3NGJ.js";import{a as te}from"./chunk-KFSA2ZI7.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as W,ma as j,w as L,x as Q}from"./chunk-OPNZWQ6Y.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function U(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
2
2
  `,l=n+".tmp";Y(l,s,"utf-8");try{JSON.parse(pe(l,"utf-8"))}catch(c){throw new Error(`config did not round-trip cleanly: ${c.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,Me(n,i)),Y(n,s,"utf-8"),t.skipReload||Ne().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function ue(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(ge(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return Y(n,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:n}}async function Ne(){try{let t=W().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function fe(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
@@ -742,4 +742,4 @@ tr:hover td { background: var(--bg-hover); }
742
742
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
743
  ${r}`).all(t,...n,...a).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function pn(e,t){return Ae(e,t,L,"ORDER BY created_at")}function gn(e,t,n=50){return Ae(e,t,[...L,...Q],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ze();var V="member:",gt=90,mt="members",ut="tailscale-user-login",ft=400,ht=60*60*1e3;function vt(e){let t=e.scopes.find(n=>n.startsWith(V));return t?t.slice(V.length):null}function Ie(e,t){if(!e)return null;let n=t.verify(e),r=n?vt(n):null;return n&&r?{rec:n,personId:r}:null}function xn(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${V}${n.id}`],expiresInDays:gt}),{code:o,expiresAt:s}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:a.id,person:n}}var bt=Math.round(oe/6e4);function xt(e){return e==="client"?"Your project":"My work"}function yn(e){let t=xt(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${ie(e.code)}`,` The code works once, for ${bt} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
744
744
  `)}var yt="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",kt="Too many machines are waiting for the owner's answer. Try again later.",Se="That code didn't work. Check it, or ask the person who invited you for a new one.",Ee=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Te(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function wt(e){if(!Te(e))return null;let t=Ee(e,ut).toLowerCase();return t?t.slice(0,80):null}function $t(e){let t=e.socket?.remoteAddress||"unknown";if(!Te(e))return t;let n=Ee(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function At(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function St(e){return e.identities.map(Z).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function kn(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(m=>console.log(m)),o=$t(e),s=t.limiter.retryAfter(o);if(s>0)return a(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await ae(e,2048);l=m.code,i=At(m.machine)}catch{}let c=t.codes.redeem(l),g=c?Ie(c.token,t.tokens):null;if(await Et(n,t.minMs??ft),!c||!g)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Se}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:Se}};let u=wt(e),A=St(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),a(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:yt}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=se(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:mt},{now:r()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),a(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:c.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),a(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:kt}})}var H="this machine is not paired",It="waiting for the owner to approve this machine";function Ce(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function wn(e,t){return t.state==="pending"&&t.cardId?Ce(F(e,t.cardId)):null}function $n(e,t,n){let r=t.now??Date.now,a=t.log??(g=>console.log(g)),o=Ie(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Re(t,s.id,"person no longer listed"),a(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?F(t.root,i.cardId):null,f=Ce(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(r()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),a(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),a(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:It,waiting:!0}}let c=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(r()-c>=ht||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Re(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function An(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Re(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Et(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pe=["gitlab","github"];function Tt(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pe.includes(r))throw new Error(`Request status works on ${Pe.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function En(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Tn(e){let{summary:t}=U(n=>Tt(n,e?.channel,!!e?.enabled));return{summary:t}}var Ct="https://ntfy.sh";function Rn(e){return{enabled:!!e?.enabled,server:e?.server||Ct,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{U as a,xe as b,jt as c,Ft as d,Jt as e,Vt as f,Qt as g,Zt as h,cn as i,pn as j,gn as k,gt as l,xn as m,bt as n,xt as o,yn as p,$t as q,kn as r,wn as s,$n as t,Re as u,An as v,Pe as w,Tt as x,En as y,Tn as z,Rn as A,Pn as B,lt as C,sn as D};
745
- //# sourceMappingURL=chunk-MORRCYJE.js.map
745
+ //# sourceMappingURL=chunk-MSYBNVY3.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-OKPC77BN.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-4J6WMXLI.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/index.d.ts CHANGED
@@ -10896,7 +10896,13 @@ declare class SessionStore {
10896
10896
  * null when there is no native session to resume.
10897
10897
  */
10898
10898
  sessionIdleMs(agentId: string, channel: string, chatId: string): number | null;
10899
- isSessionStale(agentId: string, channel: string, chatId: string): boolean;
10899
+ /**
10900
+ * Whether the session has been idle longer than staleMinutes. Pass the
10901
+ * idle time read before this turn touched the session: recording the
10902
+ * inbound message bumps updatedAt, so reading it afterwards always sees
10903
+ * an idle time of about zero.
10904
+ */
10905
+ isSessionStale(agentId: string, channel: string, chatId: string, idleMs?: number | null): boolean;
10900
10906
  /**
10901
10907
  * Build a summary of recent messages from OTHER sessions for the same agent today.
10902
10908
  * This bridges the cross-chat amnesia gap — if someone shared info in a DM,
@@ -10976,6 +10982,9 @@ declare class SessionStore {
10976
10982
  /** The rotation metric shouldRotateByTierTwo actually used: per-request
10977
10983
  * context size when available, else the cumulative fallback. */
10978
10984
  getLastTurnContextTokens(agentId: string, channel: string, chatId: string): number;
10985
+ /** The per-request context reading alone, with no cumulative fallback.
10986
+ * Null when the last turn left none (a non-streaming turn). */
10987
+ getRawLastTurnContextTokens(agentId: string, channel: string, chatId: string): number | null;
10979
10988
  getMaxTurnsPerSession(): number;
10980
10989
  getTierTwoThresholdTokens(channel?: string): number;
10981
10990
  /**
@@ -11281,7 +11290,7 @@ declare class WikiHub {
11281
11290
  /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */
11282
11291
  getBaseDir(): string;
11283
11292
  getSharedStore(): WikiStore;
11284
- listAgents(): string[];
11293
+ listAgents(entries?: WikiEntry[]): string[];
11285
11294
  getAgentEntries(agentId: string): WikiEntry[];
11286
11295
  /**
11287
11296
  * Entries absorb has not dealt with yet: no article cites them and no
@@ -11296,6 +11305,12 @@ declare class WikiHub {
11296
11305
  * entries are offered again.
11297
11306
  */
11298
11307
  markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void;
11308
+ /**
11309
+ * Counts and articles per agent, for `GET /wiki/agents` and the mesh.
11310
+ * The raw entries are read once and grouped here: reading them again
11311
+ * per agent made the endpoint take 25 to 75 s on a fleet with 30
11312
+ * agents and 10k entries, past the mesh client's 5 s timeout (#603).
11313
+ */
11299
11314
  summary(): AgentWikiSummary[];
11300
11315
  /** Split an agent's entries into cited by an article, read but not cited, and pending. */
11301
11316
  private classifyEntries;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,ja as Tt,ka as Mt}from"./chunk-I4IDZSGF.js";import"./chunk-BWHHZJNJ.js";import"./chunk-GTJIKXDB.js";import"./chunk-CAS2IWSM.js";import"./chunk-S2GAEH2F.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-7ZABMMSW.js";import"./chunk-6FVFD5WU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-H5Z42X7W.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMGB23H5.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-2NGXOYTS.js";import"./chunk-7KY7EEEI.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-RMA7KKR7.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-BLEW5WQL.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-25XR6QK2.js";import"./chunk-2IMK3NGJ.js";import"./chunk-VWTBHLMX.js";import"./chunk-DJQMG6TH.js";import{a as ht}from"./chunk-IKBWV7YJ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-6TUQHOO3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-Y4PR5LR3.js";import{f as gt,g as ft}from"./chunk-ELUEF4NC.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import{j as it,k as rt,l as at}from"./chunk-4GDLXWCH.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ha as tt,ja as st,ka as ot,ma as nt}from"./chunk-OPNZWQ6Y.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,ja as Tt,ka as Mt}from"./chunk-FIB5LD6R.js";import"./chunk-BWHHZJNJ.js";import"./chunk-GTJIKXDB.js";import"./chunk-CAS2IWSM.js";import"./chunk-S2GAEH2F.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-7ZABMMSW.js";import"./chunk-6FVFD5WU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-H5Z42X7W.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMGB23H5.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-D7LGD7ZI.js";import"./chunk-7KY7EEEI.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-HVYS5ZBQ.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-BLEW5WQL.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-25XR6QK2.js";import"./chunk-2IMK3NGJ.js";import"./chunk-VWTBHLMX.js";import"./chunk-KFSA2ZI7.js";import{a as ht}from"./chunk-IKBWV7YJ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-6TUQHOO3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-Y4PR5LR3.js";import{f as gt,g as ft}from"./chunk-ELUEF4NC.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import{j as it,k as rt,l as at}from"./chunk-4GDLXWCH.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ha as tt,ja as st,ka as ot,ma as nt}from"./chunk-OPNZWQ6Y.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).