agentix-cli 0.185.0 → 0.185.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 (26) hide show
  1. package/dist/{board-dashboard-TCZ3RAQR.js → board-dashboard-BIERRXDD.js} +12 -8
  2. package/dist/{board-dashboard-TCZ3RAQR.js.map → board-dashboard-BIERRXDD.js.map} +1 -1
  3. package/dist/{chunk-JJ7FHH53.js → chunk-BIYEGA7Q.js} +2 -2
  4. package/dist/{chunk-LZVQ4N2Z.js → chunk-BXTSO66H.js} +2 -2
  5. package/dist/{chunk-Z5DHUJIL.js → chunk-MYFTR4NH.js} +2 -2
  6. package/dist/{chunk-P7K5ZQVT.js → chunk-TAZIS2VP.js} +2 -2
  7. package/dist/{chunk-2HZXLYWQ.js → chunk-UXWG4DMD.js} +3 -3
  8. package/dist/{chunk-BLWVMGSJ.js → chunk-XPZSEDE3.js} +1 -1
  9. package/dist/chunk-XPZSEDE3.js.map +1 -0
  10. package/dist/{chunk-DSIPKP2D.js → chunk-ZRC2ZHHE.js} +2 -2
  11. package/dist/cli.js +1 -1
  12. package/dist/{doctor-DKW3EP3O.js → doctor-NPHNPYHR.js} +2 -2
  13. package/dist/{grants-COGXFWO3.js → grants-3UVDASRI.js} +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/{program-2DFU4DCC.js → program-GQ3YWR5W.js} +5 -5
  16. package/package.json +1 -1
  17. package/dist/chunk-BLWVMGSJ.js.map +0 -1
  18. /package/dist/{chunk-JJ7FHH53.js.map → chunk-BIYEGA7Q.js.map} +0 -0
  19. /package/dist/{chunk-LZVQ4N2Z.js.map → chunk-BXTSO66H.js.map} +0 -0
  20. /package/dist/{chunk-Z5DHUJIL.js.map → chunk-MYFTR4NH.js.map} +0 -0
  21. /package/dist/{chunk-P7K5ZQVT.js.map → chunk-TAZIS2VP.js.map} +0 -0
  22. /package/dist/{chunk-2HZXLYWQ.js.map → chunk-UXWG4DMD.js.map} +0 -0
  23. /package/dist/{chunk-DSIPKP2D.js.map → chunk-ZRC2ZHHE.js.map} +0 -0
  24. /package/dist/{doctor-DKW3EP3O.js.map → doctor-NPHNPYHR.js.map} +0 -0
  25. /package/dist/{grants-COGXFWO3.js.map → grants-3UVDASRI.js.map} +0 -0
  26. /package/dist/{program-2DFU4DCC.js.map → program-GQ3YWR5W.js.map} +0 -0
@@ -1,3 +1,3 @@
1
- import{q as x,s as A}from"./chunk-BLWVMGSJ.js";import{a as w,e as D}from"./chunk-VQRY4IDI.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
1
+ import{q as x,s as A}from"./chunk-XPZSEDE3.js";import{a as w,e as D}from"./chunk-VQRY4IDI.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
2
2
  `)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
3
- //# sourceMappingURL=chunk-JJ7FHH53.js.map
3
+ //# sourceMappingURL=chunk-BIYEGA7Q.js.map
@@ -1,4 +1,4 @@
1
- import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Fn,J as Gn,k as U}from"./chunk-DSIPKP2D.js";import{f as Hn,g as zn,h as Xn,k as Kn}from"./chunk-NHW4IY6N.js";import{b as Wn}from"./chunk-2VDO2HEK.js";import{a as jn,i as qn,l as Bn,n as Ve,o as He,q as Y,r as B,t as Vn}from"./chunk-BLWVMGSJ.js";import{t as Mn,u as Un}from"./chunk-2V6ZGE74.js";import{d as Pn,e as On}from"./chunk-AQASR6KR.js";import{a as kn,b as vn,d as Sn,e as $n}from"./chunk-MNG2AMKZ.js";import{h as J,j as _n,l as En,m as An,n as Rn}from"./chunk-RX5O5637.js";import{a as In,c as Tn,e as Dn,f as We,h as Cn,j as Nn,k as Ln,l as je,m as qe,n as Be}from"./chunk-5ELIX7BQ.js";import{h as hn,i as bn,j as yn,l as wn,m as xn}from"./chunk-V4IOGISL.js";import{a as fn,c as mn}from"./chunk-KP7KDLZ2.js";import{Aa as Ue,Ca as Fe,b as Pe,s as Oe,u as Me,xa as gn,za as de}from"./chunk-2GIYVYIM.js";import{r as pn}from"./chunk-RTIGD4NG.js";import{a as dn,b as ce,e as un}from"./chunk-NS2HSAHF.js";import{a as cn}from"./chunk-QUFIUXMQ.js";import{A as Ss,Gb as ln,d as De,f as Zt,j as vs,la as tn,ma as nn,nb as Le,oa as rn,pa as on,wb as sn,x as le,xb as an,y as Qt,z as en}from"./chunk-BZJF7DJR.js";import{a as Ce,h as $s}from"./chunk-VJ5HC63R.js";import{j as Ne,r as _s}from"./chunk-UEEB3UTU.js";import{existsSync as Es,readdirSync as As,readFileSync as Rs,statSync as Is}from"fs";import{resolve as Ts}from"path";function Jn(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],l=a.filter(f=>n-f.at<=o),c=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&d*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:d,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ue=new Map;function ad(t,e=1e3){if(!Es(t))return[];let n=As(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ts(t,s);return{path:i,mtime:Is(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ue.keys())r.has(s)||ue.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=ue.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let l=Ds(s,i);ue.set(s,{mtime:i,summary:l}),l&&o.push(l)}return o}function Ds(t,e){try{let n=Rs(t,"utf-8").split(`
1
+ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Fn,J as Gn,k as U}from"./chunk-ZRC2ZHHE.js";import{f as Hn,g as zn,h as Xn,k as Kn}from"./chunk-NHW4IY6N.js";import{b as Wn}from"./chunk-2VDO2HEK.js";import{a as jn,i as qn,l as Bn,n as Ve,o as He,q as Y,r as B,t as Vn}from"./chunk-XPZSEDE3.js";import{t as Mn,u as Un}from"./chunk-2V6ZGE74.js";import{d as Pn,e as On}from"./chunk-AQASR6KR.js";import{a as kn,b as vn,d as Sn,e as $n}from"./chunk-MNG2AMKZ.js";import{h as J,j as _n,l as En,m as An,n as Rn}from"./chunk-RX5O5637.js";import{a as In,c as Tn,e as Dn,f as We,h as Cn,j as Nn,k as Ln,l as je,m as qe,n as Be}from"./chunk-5ELIX7BQ.js";import{h as hn,i as bn,j as yn,l as wn,m as xn}from"./chunk-V4IOGISL.js";import{a as fn,c as mn}from"./chunk-KP7KDLZ2.js";import{Aa as Ue,Ca as Fe,b as Pe,s as Oe,u as Me,xa as gn,za as de}from"./chunk-2GIYVYIM.js";import{r as pn}from"./chunk-RTIGD4NG.js";import{a as dn,b as ce,e as un}from"./chunk-NS2HSAHF.js";import{a as cn}from"./chunk-QUFIUXMQ.js";import{A as Ss,Gb as ln,d as De,f as Zt,j as vs,la as tn,ma as nn,nb as Le,oa as rn,pa as on,wb as sn,x as le,xb as an,y as Qt,z as en}from"./chunk-BZJF7DJR.js";import{a as Ce,h as $s}from"./chunk-VJ5HC63R.js";import{j as Ne,r as _s}from"./chunk-UEEB3UTU.js";import{existsSync as Es,readdirSync as As,readFileSync as Rs,statSync as Is}from"fs";import{resolve as Ts}from"path";function Jn(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],l=a.filter(f=>n-f.at<=o),c=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&d*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:d,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ue=new Map;function ad(t,e=1e3){if(!Es(t))return[];let n=As(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ts(t,s);return{path:i,mtime:Is(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ue.keys())r.has(s)||ue.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=ue.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let l=Ds(s,i);ue.set(s,{mtime:i,summary:l}),l&&o.push(l)}return o}function Ds(t,e){try{let n=Rs(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Yn=7,Cs={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Ns=(t,e,n)=>{try{return pn(t,e,n)}catch{return null}},Zn=864e5;function ud(t){let e=t.now??Date.now(),n={...Cs,...t.thresholds},r=t.nextFire??Ns,o=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",d=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:T(a.id,k.text),trigger:{schedule:T(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Xe(a.nextRun)??Xe(r(a.schedule,new Date(e),c)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Fs(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Qn(d),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Yn).map(g=>({at:g.startedAt,status:g.status}))};p.flags=er(p,d,a.schedule,c,null,e,n,r),o.push(tr(p))}let s=new Map(Jn(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(x=>x.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((x,Te)=>Te.at-x.at),g=p.map(x=>({at:x.at,status:Os(x.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",$=typeof c.timezone=="string"?c.timezone:"UTC",q={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:T(a.title||a.id,k.text),trigger:m?{schedule:T(b,k.text),timezone:$}:{event:T(typeof c.event=="string"?c.event:"",k.text),filters:Us(c.filter,a)},agent:Ms(a),enabled:u,state:d,nextRunAt:m&&u&&b?Xe(r(b,new Date(e),$)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(Te=>Te.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:Qn(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Yn).map(x=>({at:new Date(x.at).toISOString(),status:x.status}))},ae=Date.parse(a.updated||a.created||"");q.flags=m?er(q,g,b,$,Number.isFinite(ae)?ae:null,e,n,r):Ls(q,s.get(a.id)?.state==="dormant",Number.isFinite(ae)?ae:null,e,n),o.push(tr(q))}return o.sort(Ps).slice(0,k.routines)}function Qn(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function er(t,e,n,r,o,s,i,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=rr(c,o,s,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let d=new Date(c),u=null;for(let p=0;p<i.missedFires&&(u=a(n,d,r),!!u);p++)d=u;return u&&s>u.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Ls(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=rr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function rr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Zn?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Zn)} days`:"Disabled and never ran"}}function tr(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var nr={critical:0,warning:1,info:2};function Ps(t,e){let n=t.attention?nr[t.attention]:3,r=e.attention?nr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Os(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Ms(t){if(t.ownerAgent)return T(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?T(String(e.config.agentId),k.text):null}function Us(t,e){let n=[],r=e?.project;if(r&&n.push(T(`project=${r}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(T(`${o}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Xe(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function T(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Fs(t,e){return t===void 0?void 0:T(t,e)}import{mkdirSync as Ws,readFileSync as js,renameSync as qs,writeFileSync as Bs}from"fs";import{resolve as Vs}from"path";function or(t){return Vs(He(t),"_state.json")}function _(t){try{let e=JSON.parse(js(or(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function Z(t,e){Ws(He(t),{recursive:!0});let n=or(t),r=`${n}.${process.pid}.tmp`;Bs(r,JSON.stringify(e,null,2)+`
3
3
  `),qs(r,n)}function sr(t,e,n,r=Date.now()){let o=_(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),Z(t,{...o,snoozed:s})}function hd(t,e){Z(t,{..._(t),lastDigest:e})}function Ke(t,e,n,r=Date.now()){let o=_(t),s=new Set(n),i={};for(let[l,c]of Object.entries(o.popped??{}))s.has(l)&&(i[l]=c);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(l=>l!==e&&s.has(l));Z(t,{...o,popped:i,wanted:a})}function ir(t,e){let n=_(t);Z(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function bd(t,e=Date.now()){Z(t,{..._(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Hs,readFileSync as zs}from"fs";ln();$s();function ar(t){let e=dn(t),n={};if(Hs(e))try{n=sn(JSON.parse(zs(e,"utf-8")))}catch{n={}}let r=Le.safeParse(n?.requests);return r.success?r.data:Le.parse(void 0)}async function Sd(t,e={}){let n=(t.channels??[]).filter(r=>!Ce.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Ce].join(", ")}`}:ce(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as Q,readdirSync as fi,readFileSync as Qe}from"fs";import{dirname as mi,resolve as E}from"path";import{randomBytes as dr}from"crypto";import{existsSync as Ks,mkdirSync as Gs,readdirSync as Js,readFileSync as Ys,renameSync as ur,unlinkSync as Zs,writeFileSync as Qs}from"fs";import{resolve as pr}from"path";function lr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Xs=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function cr(t,e,n,r=ze){let o=await r(t.bin,[...lr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Xs(o.stderr||o.stdout)}`}}async function Ed(t,e,n,r,o=ze){return(await o(t.bin,[...lr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var ei=2e3,ti=t=>cr(t.wacli,t.to,t.text);function Ge(t){return pr(t,".agentx","whatsapp-triage","drafts")}var ni=t=>/^[a-z0-9-]{8,64}$/.test(t),pe=(t,e)=>pr(Ge(t),`${e}.json`);function gr(t,e){Gs(Ge(t),{recursive:!0});let n=pe(t,e.id),r=`${n}.${process.pid}.tmp`;Qs(r,JSON.stringify(e,null,2)+`
@@ -885,4 +885,4 @@ Document the arguments, commands, or files the skill expects. Example:
885
885
  claude-code ${Yt(t)} --arg value
886
886
  \`\`\`
887
887
  `}ln();var ys={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function ws(t){return{...ys,...t??{},regions:{...t?.regions??{}},buffer:{...ys.buffer,...t?.buffer??{}}}}function Xf(t){try{return ws(an(t).screen)}catch{return ws(void 0)}}var od=/^[a-z][\w-]*$/,xs=["window","screen","menubar","notifications"];function ie(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Ie=(t,e)=>ie(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ks(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Kf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ie(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ie(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ie(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ie(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ie(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!od.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=ks(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ie(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ie(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ie(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!xs.includes(r)&&!n.regions?.[r])try{ks(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...xs,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Jn as a,ad as b,It as c,Ya as d,Za as e,Lp as f,Pp as g,Op as h,Fp as i,Wp as j,jp as k,yo as l,wo as m,qp as n,xo as o,Vp as p,zp as q,O as r,ko as s,k as t,ud as u,$o as v,Zp as w,tg as x,Eo as y,ng as z,Ao as A,rg as B,ne as C,_l as D,og as E,sg as F,Io as G,Ed as H,ti as I,Cd as J,mr as K,Ld as L,_ as M,hd as N,bd as O,qd as P,fe as Q,Bd as R,ar as S,Sd as T,F as U,gu as V,Rr as W,Tr as X,Ci as Y,Ni as Z,hu as _,bu as $,Wi as aa,ku as ba,Do as ca,lg as da,$u as ea,_u as fa,fo as ga,xt as ha,Va as ia,v as ja,Vo as ka,Fg as la,Wg as ma,dc as na,Vg as oa,Jo as pa,Hg as qa,zg as ra,Zg as sa,kc as ta,Qg as ua,Au as va,Ru as wa,Iu as xa,Tu as ya,Du as za,Cu as Aa,Lu as Ba,Pu as Ca,Uu as Da,Fu as Ea,Wu as Fa,qu as Ga,Bu as Ha,Vu as Ia,Hu as Ja,zu as Ka,Xu as La,Ku as Ma,rp as Na,ut as Oa,op as Pa,sp as Qa,ee as Ra,te as Sa,Ac as Ta,cf as Ua,df as Va,uf as Wa,pf as Xa,Ft as Ya,gf as Za,ft as _a,mt as $a,ve as ab,ha as bb,ya as cb,dp as db,bt as eb,yt as fb,wa as gb,xa as hb,no as ib,io as jb,up as kb,Sa as lb,pp as mb,Da as nb,La as ob,wt as pb,Oa as qb,ao as rb,M as sb,as as tb,ls as ub,cs as vb,jt as wb,wf as xb,Oc as yb,us as zb,ps as Ab,Tf as Bb,Df as Cb,Zc as Db,Cf as Eb,fs as Fb,Se as Gb,$p as Hb,At as Ib,Dp as Jb,Of as Kb,Mf as Lb,Uf as Mb,Ff as Nb,Wf as Ob,jf as Pb,qf as Qb,Bf as Rb,Vf as Sb,ys as Tb,ws as Ub,Xf as Vb,xs as Wb,Kf as Xb};
888
- //# sourceMappingURL=chunk-LZVQ4N2Z.js.map
888
+ //# sourceMappingURL=chunk-BXTSO66H.js.map
@@ -1,7 +1,7 @@
1
- import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-DSIPKP2D.js";import{a as E}from"./chunk-OSH2PEBH.js";import{Gb as F,xb as j}from"./chunk-BZJF7DJR.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-ZRC2ZHHE.js";import{a as E}from"./chunk-OSH2PEBH.js";import{Gb as F,xb as j}from"./chunk-BZJF7DJR.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
3
  `)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{G(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function de(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=le(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ue(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
6
6
  `))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
7
- //# sourceMappingURL=chunk-Z5DHUJIL.js.map
7
+ //# sourceMappingURL=chunk-MYFTR4NH.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ge,b as k,c as D,d as Xe,e as ge,f as ue,g as j,h as me,i as N,j as L,n as Ve,o as Qe,p as Ze,q as ea}from"./chunk-EFGAPAYZ.js";import{e as Ye,i as Je}from"./chunk-QAWKN2N4.js";import{b as xe}from"./chunk-DODL5POT.js";import{a as Q,b as Ke}from"./chunk-A4PW7EIK.js";import{Ia as We,Ja as Be,Ka as Ue,Ma as Fe,ja as _,oa as Le,wb as qe}from"./chunk-LZVQ4N2Z.js";import{a as X}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as Me,e as He}from"./chunk-LQE73AZR.js";import{b as Ne}from"./chunk-MRIVENBY.js";import{q as pe,s as je}from"./chunk-BLWVMGSJ.js";import{ga as G}from"./chunk-2GIYVYIM.js";import{a as q,b as J}from"./chunk-NS2HSAHF.js";import{a as De}from"./chunk-FJMTCU4S.js";import{c as Ee,d as Re}from"./chunk-OWNQ2FD4.js";import{a as Oe}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Gb as ce,Ta as Ie,_a as Va,ea as de,fa as Te,pa as Xa,tb as le,wb as F,xb as ze}from"./chunk-BZJF7DJR.js";import{existsSync as K,readFileSync as da,writeFileSync as la,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var fe=`:root {
1
+ import{a as Ge,b as k,c as D,d as Xe,e as ge,f as ue,g as j,h as me,i as N,j as L,n as Ve,o as Qe,p as Ze,q as ea}from"./chunk-EFGAPAYZ.js";import{e as Ye,i as Je}from"./chunk-QAWKN2N4.js";import{b as xe}from"./chunk-DODL5POT.js";import{a as Q,b as Ke}from"./chunk-A4PW7EIK.js";import{Ia as We,Ja as Be,Ka as Ue,Ma as Fe,ja as _,oa as Le,wb as qe}from"./chunk-BXTSO66H.js";import{a as X}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as Me,e as He}from"./chunk-LQE73AZR.js";import{b as Ne}from"./chunk-MRIVENBY.js";import{q as pe,s as je}from"./chunk-XPZSEDE3.js";import{ga as G}from"./chunk-2GIYVYIM.js";import{a as q,b as J}from"./chunk-NS2HSAHF.js";import{a as De}from"./chunk-FJMTCU4S.js";import{c as Ee,d as Re}from"./chunk-OWNQ2FD4.js";import{a as Oe}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Gb as ce,Ta as Ie,_a as Va,ea as de,fa as Te,pa as Xa,tb as le,wb as F,xb as ze}from"./chunk-BZJF7DJR.js";import{existsSync as K,readFileSync as da,writeFileSync as la,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var fe=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2900,4 +2900,4 @@ ${a}=${t}
2900
2900
  WHERE person = ? AND state IN (${t.map(()=>"?").join(",")})
2901
2901
  ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Zo(e,a){return Wa(e,a,de,"ORDER BY created_at")}function ei(e,a,t=50){return Wa(e,a,[...de,...Te],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Va();var Ce="member:",mr=90,fr="members",hr="tailscale-user-login",br=400,vr=60*60*1e3;function wr(e){let a=e.scopes.find(t=>t.startsWith(Ce));return a?a.slice(Ce.length):null}function Ua(e,a){if(!e)return null;let t=a.verify(e),r=t?wr(t):null;return t&&r?{rec:t,personId:r}:null}function si(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${Ce}${t.id}`],expiresInDays:mr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var yr=Math.round(Me/6e4);function kr(e){return e==="client"?"Your project":"My work"}function di(e){let a=kr(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${He(e.code)}`,` The code works once, for ${yr} 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(`
2902
2902
  `)}var _r="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",$r="Too many machines are waiting for the owner's answer. Try again later.",Ba="That code didn't work. Check it, or ask the person who invited you for a new one.",Fa=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function qa(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function Sr(e){if(!qa(e))return null;let a=Fa(e,hr).toLowerCase();return a?a.slice(0,80):null}function Ar(e){let a=e.socket?.remoteAddress||"unknown";if(!qa(e))return a;let t=Fa(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function Cr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Tr(e){return e.identities.map(Ie).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function li(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=Ar(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await V(e,2048);s=b.code,d=Cr(b.machine)}catch{}let l=a.codes.redeem(s),c=l?Ua(l.token,a.tokens):null;if(await zr(t,a.minMs??br),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Ba}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Ba}};let x=Sr(e),f=Tr(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:_r}};let C=d||"Unnamed machine",w=u.name.slice(0,40),v=je(a.root,{title:`New machine for ${w}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${w}'s own work?`,recommend:`Yes if ${w} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:fr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:$r}})}var se="this machine is not paired",Ir="waiting for the owner to approve this machine";function Ka(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function ci(e,a){return a.state==="pending"&&a.cardId?Ka(pe(e,a.cardId)):null}function pi(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=Ua(e,a.tokens);if(!o)return{ok:!1,status:401,error:se};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:se};if(a.people&&!a.people().some(c=>c.id===s))return Ya(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:se};if(d.state==="pending"){let c=d.cardId?pe(a.root,d.cardId):null,m=Ka(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:se}}else return{ok:!1,status:403,error:Ir,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=vr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Ya(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function xi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Ya(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function zr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ja=["gitlab","github"];function Pr(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ja.includes(r))throw new Error(`Request status works on ${Ja.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function mi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function fi(e){let{summary:a}=Q(t=>Pr(t,e?.channel,!!e?.enabled));return{summary:a}}var bi="https://myaccount.google.com/apppasswords";function vi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function wi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function yi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function _i(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function $i(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Si(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Ai(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Er="https://ntfy.sh";function Ti(e){return{enabled:!!e?.enabled,server:e?.server||Er,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ii(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}export{fe as a,na as b,be as c,Za as d,et as e,at as f,tt as g,rt as h,nt as i,ot as j,it as k,ca as l,mt as m,yn as n,kn as o,_n as p,vo as q,dr as r,_o as s,Co as t,La as u,Jo as v,Go as w,zn as x,Pn as y,It as z,Et as A,ve as B,En as C,Rn as D,Rt as E,Nn as F,Ln as G,Wn as H,Qo as I,Zo as J,ei as K,mr as L,si as M,yr as N,kr as O,di as P,Ar as Q,li as R,ci as S,pi as T,Ya as U,xi as V,Ja as W,Pr as X,mi as Y,fi as Z,bi as _,vi as $,wi as aa,yi as ba,_i as ca,$i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,Qt as ia,co as ja,fo as ka,ho as la};
2903
- //# sourceMappingURL=chunk-P7K5ZQVT.js.map
2903
+ //# sourceMappingURL=chunk-TAZIS2VP.js.map
@@ -1,4 +1,4 @@
1
- import{$a as ve,A as Vp,Ab as gm,B as Jp,Ba as Wa,Bb as pm,C as Xt,Ca as Ff,Cb as fm,D as Js,E as Kp,Eb as mm,F as zp,Fa as Wf,G as Yp,Ga as Jf,H as nf,I as sf,J as rf,Jb as ym,K as of,Kb as wm,L as af,M as cf,N as lf,Na as Ga,O as df,Oa as kt,P as uf,Pa as Kf,Q as hf,Qa as zf,R as Da,Ta as vt,Tb as qa,U as gf,Ua as Yf,Ub as Xa,Va as Qf,W as pf,Wa as Zf,Wb as bm,Xa as em,Ya as tm,Za as nm,a as $p,ab as Zs,b as xa,ba as Ys,bb as Ha,ca as Rf,cb as sm,db as Dn,ea as Ef,eb as rm,f as Aa,fa as La,fb as De,g as Ip,gb as im,h as Tp,hb as om,i as Ra,ia as Cf,ib as am,j as xp,jb as er,k as On,kb as tr,l as Ap,la as Pf,lb as cm,m as Rp,mb as lm,n as Ep,o as Ze,oa as _f,p as Cp,pa as Mf,q as Pp,qa as Of,ra as ja,rb as dm,s as _p,sa as Df,u as Mp,ua as Nf,v as et,va as Fa,vb as um,w as Ca,wa as Lf,x as Bp,xa as Oe,xb as nr,y as qp,ya as jf,yb as Ba,z as Xp,za as Qs,zb as hm}from"./chunk-LZVQ4N2Z.js";import{d as kp,g as vp,h as Sp}from"./chunk-NBWSZ53L.js";import{a as Op}from"./chunk-ZVP6GB4G.js";import{A as jp,B as Fp,D as qs,E as Pa,F as Xs,G as qt,K as ff,c as ep,d as tp,f as np,g as Mn,h as Bs,i as $a,j as sp,k as ze,z as Lp}from"./chunk-DSIPKP2D.js";import{a as xf,b as Af}from"./chunk-VZLIBDLH.js";import{b as Uf,c as Gf,d as Ua,e as Hf,f as Bf,g as qf,h as Xf,i as Vf}from"./chunk-EKJG63EJ.js";import{d as Wp}from"./chunk-6V5JBHUN.js";import{g as Up}from"./chunk-LQE73AZR.js";import{b as Gp,c as Hp}from"./chunk-2D3RYIDU.js";import{b as mf}from"./chunk-MRIVENBY.js";import{i as yf,m as Na,n as wf,p as bf,q as kf,r as vf,s as Sf,t as $f,u as If}from"./chunk-JJ7FHH53.js";import{h as _a,n as Ma,o as Qp,p as Ks,q as bt,r as Vt,s as Me,u as Zp,v as ef,w as tf,x as Oa,y as zs}from"./chunk-BLWVMGSJ.js";import{a as Tf}from"./chunk-PPUN7YHA.js";import{a as Dp,b as Np}from"./chunk-A5GYG56I.js";import{o as Ea}from"./chunk-2V6ZGE74.js";import{b as Vs}from"./chunk-UKUH662W.js";import{a as Qe}from"./chunk-MNG2AMKZ.js";import{c as dp,d as up,f as hp,g as gp,i as pp,k as fp,l as mp}from"./chunk-RX5O5637.js";import{d as yp}from"./chunk-5ELIX7BQ.js";import{b as wp,c as bp}from"./chunk-X7UQY7CH.js";import{a as Ia,b as rp,c as ip}from"./chunk-QPABR72X.js";import{a as op,b as Ye,c as ap,d as cp,e as lp}from"./chunk-AJ5HMDRW.js";import{c as Bt}from"./chunk-KP7KDLZ2.js";import{$ as va,A as B,C as Mh,D as Oh,E as Dh,F as Nh,G as ge,H as jh,I as Fh,J as Wh,K as Uh,L as zh,M as Yh,N as Qh,O as Fg,P as Wg,Q as Ug,R as Gg,S as Hg,T as Bg,V as _n,W as qg,Z as ie,_ as Ke,a as sh,aa as Ut,b as ca,ba as Sa,c as ih,ca as Gs,d as gh,da as Gt,e as ph,ea as Ht,f as Rn,fa as me,ga as wt,h as da,ha as oe,i as ua,ia as Xg,j as ha,ja as Vg,k as ga,l as fh,ma as zg,s as yh,t as vh,u as mt,v as Sh,w as $h,x as Ih,y as Wt,ya as Yg,z as Ah}from"./chunk-UASRZKZQ.js";import{$ as Ag,Da as Kg,G as Jh,H as Kh,N as Zh,P as eg,R as fg,S as mg,T as Sg,U as $g,V as Ig,W as Tg,Y as ka,Z as Us,_ as xg,a as wh,aa as Rg,ba as Eg,c as Th,ca as Cg,d as xh,da as Pg,e as yt,ea as _g,f as _e,fa as Mg,h as Gh,ha as Og,i as Hh,j as Bh,k as fa,ka as Dg,l as qh,m as Xh,p as Vh,pa as Ng,q as js,qa as Lg,ta as jg,xa as Jg}from"./chunk-2GIYVYIM.js";import{a as pa,b as kh}from"./chunk-MEFPXHQJ.js";import{A as Qg,B as Hs,C as Zg,h as qd,n as Xd,o as Fo}from"./chunk-2LTZUZJU.js";import{b as Gd}from"./chunk-SFQUP3BP.js";import{a as Ta}from"./chunk-6TTGRTDO.js";import{a as tg,b as ma,c as ng,d as sg,e as rg,i as ig,j as og}from"./chunk-VE3SSOQX.js";import{b as Lh}from"./chunk-W4YR2RO2.js";import{b as cg,c as lg,d as ya,f as Fs,g as dg,h as ug,i as hg,j as Pn,k as Ws,m as wa,n as gg,o as pg}from"./chunk-VJVXEVZ7.js";import{b as he,d as qe,f as Xe,g as En,i as fe,j as ag,k as Ve,l as Je,m as bg,p as kg,r as vg,t as ba}from"./chunk-RTIGD4NG.js";import{a as yg,b as wg}from"./chunk-NS2HSAHF.js";import{b as bh}from"./chunk-PE5V2LI7.js";import{d as Rh,e as Eh,f as Ch,g as Ph,h as _h,j as Cn}from"./chunk-X5C5W3E4.js";import{c as Ls}from"./chunk-OWNQ2FD4.js";import{c as mh}from"./chunk-LUOW2YHY.js";import{d as Jd,e as dT,m as Zu,n as IT,q as eh,v as th,x as aa,y as Be,z as An}from"./chunk-LR4QUAJT.js";import{a as Pe,b as xn,f as Ds}from"./chunk-72SZI2UW.js";import{a as $n,b as Vd}from"./chunk-FCPTN6NF.js";import{c as nh}from"./chunk-MYVHVJWZ.js";import{f as rh}from"./chunk-QUFIUXMQ.js";import{d as oh,e as ah,f as la,g as Ns,h as ch,i as lh,j as dh,k as uh,q as hh}from"./chunk-AV7T3SYT.js";import{o as jo,p as lT}from"./chunk-DCIYOPJF.js";import{a as xs,b as cT}from"./chunk-7I7IEX4S.js";import{b as Hd,e as Bd}from"./chunk-JHCI6XCJ.js";import{e as ut}from"./chunk-DSYKYZMT.js";import{$ as pt,A as pT,Aa as sa,B as Cs,Ba as ra,C as tu,D as fT,Da as Os,E as nu,Ea as Wu,F as su,G as ru,Ga as Uu,Gb as $T,Ha as Gu,Ia as Hu,J as Vo,Ja as Tn,K as cu,Ka as Bu,L as lu,La as qu,M as In,Ma as Xu,N as Ps,Na as Vu,O as du,Oa as Ju,P as uu,Pa as kT,Q as Su,R as yT,S as $u,Sa as Ku,U as Yo,V as Iu,Va as zu,W as Tu,Wa as Yu,X as wT,Y as xu,Z as bT,_a as vT,aa as Au,ab as ia,ca as Qo,cb as ST,d as Wo,da as Zo,e as Uo,ea as He,f as Kd,fa as Ft,g as zd,ga as Ru,h as Yd,ia as ea,j as uT,ja as ta,ka as Eu,la as Cu,n as jt,na as Pu,o as Zd,oa as _u,p as Ho,pa as ft,q as hT,qa as na,r as As,ra as Mu,s as Bo,sa as Ou,t as Rs,ta as _s,ua as Du,v as ht,va as Ms,w as qo,wa as Nu,x as eu,xa as Lu,xb as oa,y as gT,ya as ju,z as Es,za as Fu,zb as Qu}from"./chunk-BZJF7DJR.js";import{a as iu,e as gt,f as ou,g as au,h as Xo}from"./chunk-VJ5HC63R.js";import{a as hu,b as gu,c as pu,e as fu,f as mu,i as mT,j as Jo,k as yu,l as wu,m as Ko,n as bu,o as ku,q as zo,r as vu}from"./chunk-UEEB3UTU.js";import{b as Go,e as Qd}from"./chunk-VQRY4IDI.js";import{d as Lt}from"./chunk-QIJLFPWE.js";import{existsSync as Za,readFileSync as ec}from"fs";ru();var km=["answer","narration","line"],vm=5e3;function Sm(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function $m(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let l=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!l||!d||!km.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${km.join(" | ")}`}};if(l.length>vm)return{status:413,body:{error:`text is over ${vm} characters`}};let h=e(d);if(!h)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:f,done:y}=r.enqueue({voice:h,text:l,agentId:d,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:f}}:{status:200,body:{item:f,played:await y}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,o,a,c]=n.split("/");if(t!=="POST"||!o||c!==void 0)return{status:404,body:{error:"Not found"}};switch(a){case"skip":return r.skip(o)?{status:200,body:r.view()}:Va(o);case"front":return r.front(o)?{status:200,body:r.view()}:Va(o);case"replay":{let l=r.replay(o);return l?{status:202,body:{item:l}}:Va(o)}default:return{status:404,body:{error:"Not found"}}}}function Im(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`,t=r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.";return[...r.floor?.held?[su(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$a as ve,A as Vp,Ab as gm,B as Jp,Ba as Wa,Bb as pm,C as Xt,Ca as Ff,Cb as fm,D as Js,E as Kp,Eb as mm,F as zp,Fa as Wf,G as Yp,Ga as Jf,H as nf,I as sf,J as rf,Jb as ym,K as of,Kb as wm,L as af,M as cf,N as lf,Na as Ga,O as df,Oa as kt,P as uf,Pa as Kf,Q as hf,Qa as zf,R as Da,Ta as vt,Tb as qa,U as gf,Ua as Yf,Ub as Xa,Va as Qf,W as pf,Wa as Zf,Wb as bm,Xa as em,Ya as tm,Za as nm,a as $p,ab as Zs,b as xa,ba as Ys,bb as Ha,ca as Rf,cb as sm,db as Dn,ea as Ef,eb as rm,f as Aa,fa as La,fb as De,g as Ip,gb as im,h as Tp,hb as om,i as Ra,ia as Cf,ib as am,j as xp,jb as er,k as On,kb as tr,l as Ap,la as Pf,lb as cm,m as Rp,mb as lm,n as Ep,o as Ze,oa as _f,p as Cp,pa as Mf,q as Pp,qa as Of,ra as ja,rb as dm,s as _p,sa as Df,u as Mp,ua as Nf,v as et,va as Fa,vb as um,w as Ca,wa as Lf,x as Bp,xa as Oe,xb as nr,y as qp,ya as jf,yb as Ba,z as Xp,za as Qs,zb as hm}from"./chunk-BXTSO66H.js";import{d as kp,g as vp,h as Sp}from"./chunk-NBWSZ53L.js";import{a as Op}from"./chunk-ZVP6GB4G.js";import{A as jp,B as Fp,D as qs,E as Pa,F as Xs,G as qt,K as ff,c as ep,d as tp,f as np,g as Mn,h as Bs,i as $a,j as sp,k as ze,z as Lp}from"./chunk-ZRC2ZHHE.js";import{a as xf,b as Af}from"./chunk-VZLIBDLH.js";import{b as Uf,c as Gf,d as Ua,e as Hf,f as Bf,g as qf,h as Xf,i as Vf}from"./chunk-EKJG63EJ.js";import{d as Wp}from"./chunk-6V5JBHUN.js";import{g as Up}from"./chunk-LQE73AZR.js";import{b as Gp,c as Hp}from"./chunk-2D3RYIDU.js";import{b as mf}from"./chunk-MRIVENBY.js";import{i as yf,m as Na,n as wf,p as bf,q as kf,r as vf,s as Sf,t as $f,u as If}from"./chunk-BIYEGA7Q.js";import{h as _a,n as Ma,o as Qp,p as Ks,q as bt,r as Vt,s as Me,u as Zp,v as ef,w as tf,x as Oa,y as zs}from"./chunk-XPZSEDE3.js";import{a as Tf}from"./chunk-PPUN7YHA.js";import{a as Dp,b as Np}from"./chunk-A5GYG56I.js";import{o as Ea}from"./chunk-2V6ZGE74.js";import{b as Vs}from"./chunk-UKUH662W.js";import{a as Qe}from"./chunk-MNG2AMKZ.js";import{c as dp,d as up,f as hp,g as gp,i as pp,k as fp,l as mp}from"./chunk-RX5O5637.js";import{d as yp}from"./chunk-5ELIX7BQ.js";import{b as wp,c as bp}from"./chunk-X7UQY7CH.js";import{a as Ia,b as rp,c as ip}from"./chunk-QPABR72X.js";import{a as op,b as Ye,c as ap,d as cp,e as lp}from"./chunk-AJ5HMDRW.js";import{c as Bt}from"./chunk-KP7KDLZ2.js";import{$ as va,A as B,C as Mh,D as Oh,E as Dh,F as Nh,G as ge,H as jh,I as Fh,J as Wh,K as Uh,L as zh,M as Yh,N as Qh,O as Fg,P as Wg,Q as Ug,R as Gg,S as Hg,T as Bg,V as _n,W as qg,Z as ie,_ as Ke,a as sh,aa as Ut,b as ca,ba as Sa,c as ih,ca as Gs,d as gh,da as Gt,e as ph,ea as Ht,f as Rn,fa as me,ga as wt,h as da,ha as oe,i as ua,ia as Xg,j as ha,ja as Vg,k as ga,l as fh,ma as zg,s as yh,t as vh,u as mt,v as Sh,w as $h,x as Ih,y as Wt,ya as Yg,z as Ah}from"./chunk-UASRZKZQ.js";import{$ as Ag,Da as Kg,G as Jh,H as Kh,N as Zh,P as eg,R as fg,S as mg,T as Sg,U as $g,V as Ig,W as Tg,Y as ka,Z as Us,_ as xg,a as wh,aa as Rg,ba as Eg,c as Th,ca as Cg,d as xh,da as Pg,e as yt,ea as _g,f as _e,fa as Mg,h as Gh,ha as Og,i as Hh,j as Bh,k as fa,ka as Dg,l as qh,m as Xh,p as Vh,pa as Ng,q as js,qa as Lg,ta as jg,xa as Jg}from"./chunk-2GIYVYIM.js";import{a as pa,b as kh}from"./chunk-MEFPXHQJ.js";import{A as Qg,B as Hs,C as Zg,h as qd,n as Xd,o as Fo}from"./chunk-2LTZUZJU.js";import{b as Gd}from"./chunk-SFQUP3BP.js";import{a as Ta}from"./chunk-6TTGRTDO.js";import{a as tg,b as ma,c as ng,d as sg,e as rg,i as ig,j as og}from"./chunk-VE3SSOQX.js";import{b as Lh}from"./chunk-W4YR2RO2.js";import{b as cg,c as lg,d as ya,f as Fs,g as dg,h as ug,i as hg,j as Pn,k as Ws,m as wa,n as gg,o as pg}from"./chunk-VJVXEVZ7.js";import{b as he,d as qe,f as Xe,g as En,i as fe,j as ag,k as Ve,l as Je,m as bg,p as kg,r as vg,t as ba}from"./chunk-RTIGD4NG.js";import{a as yg,b as wg}from"./chunk-NS2HSAHF.js";import{b as bh}from"./chunk-PE5V2LI7.js";import{d as Rh,e as Eh,f as Ch,g as Ph,h as _h,j as Cn}from"./chunk-X5C5W3E4.js";import{c as Ls}from"./chunk-OWNQ2FD4.js";import{c as mh}from"./chunk-LUOW2YHY.js";import{d as Jd,e as dT,m as Zu,n as IT,q as eh,v as th,x as aa,y as Be,z as An}from"./chunk-LR4QUAJT.js";import{a as Pe,b as xn,f as Ds}from"./chunk-72SZI2UW.js";import{a as $n,b as Vd}from"./chunk-FCPTN6NF.js";import{c as nh}from"./chunk-MYVHVJWZ.js";import{f as rh}from"./chunk-QUFIUXMQ.js";import{d as oh,e as ah,f as la,g as Ns,h as ch,i as lh,j as dh,k as uh,q as hh}from"./chunk-AV7T3SYT.js";import{o as jo,p as lT}from"./chunk-DCIYOPJF.js";import{a as xs,b as cT}from"./chunk-7I7IEX4S.js";import{b as Hd,e as Bd}from"./chunk-JHCI6XCJ.js";import{e as ut}from"./chunk-DSYKYZMT.js";import{$ as pt,A as pT,Aa as sa,B as Cs,Ba as ra,C as tu,D as fT,Da as Os,E as nu,Ea as Wu,F as su,G as ru,Ga as Uu,Gb as $T,Ha as Gu,Ia as Hu,J as Vo,Ja as Tn,K as cu,Ka as Bu,L as lu,La as qu,M as In,Ma as Xu,N as Ps,Na as Vu,O as du,Oa as Ju,P as uu,Pa as kT,Q as Su,R as yT,S as $u,Sa as Ku,U as Yo,V as Iu,Va as zu,W as Tu,Wa as Yu,X as wT,Y as xu,Z as bT,_a as vT,aa as Au,ab as ia,ca as Qo,cb as ST,d as Wo,da as Zo,e as Uo,ea as He,f as Kd,fa as Ft,g as zd,ga as Ru,h as Yd,ia as ea,j as uT,ja as ta,ka as Eu,la as Cu,n as jt,na as Pu,o as Zd,oa as _u,p as Ho,pa as ft,q as hT,qa as na,r as As,ra as Mu,s as Bo,sa as Ou,t as Rs,ta as _s,ua as Du,v as ht,va as Ms,w as qo,wa as Nu,x as eu,xa as Lu,xb as oa,y as gT,ya as ju,z as Es,za as Fu,zb as Qu}from"./chunk-BZJF7DJR.js";import{a as iu,e as gt,f as ou,g as au,h as Xo}from"./chunk-VJ5HC63R.js";import{a as hu,b as gu,c as pu,e as fu,f as mu,i as mT,j as Jo,k as yu,l as wu,m as Ko,n as bu,o as ku,q as zo,r as vu}from"./chunk-UEEB3UTU.js";import{b as Go,e as Qd}from"./chunk-VQRY4IDI.js";import{d as Lt}from"./chunk-QIJLFPWE.js";import{existsSync as Za,readFileSync as ec}from"fs";ru();var km=["answer","narration","line"],vm=5e3;function Sm(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function $m(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let l=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!l||!d||!km.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${km.join(" | ")}`}};if(l.length>vm)return{status:413,body:{error:`text is over ${vm} characters`}};let h=e(d);if(!h)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:f,done:y}=r.enqueue({voice:h,text:l,agentId:d,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:f}}:{status:200,body:{item:f,played:await y}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,o,a,c]=n.split("/");if(t!=="POST"||!o||c!==void 0)return{status:404,body:{error:"Not found"}};switch(a){case"skip":return r.skip(o)?{status:200,body:r.view()}:Va(o);case"front":return r.front(o)?{status:200,body:r.view()}:Va(o);case"replay":{let l=r.replay(o);return l?{status:202,body:{item:l}}:Va(o)}default:return{status:404,body:{error:"Not found"}}}}function Im(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`,t=r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.";return[...r.floor?.held?[su(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Va=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});var TT=20,Ja=120,xT=80,AT=new Set(["waiting_owner","needs_attention"]);function Ka(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function sr(r){return{total:r.length,items:r.slice(0,TT)}}var za=r=>new Date(r).toISOString();function Tm(r){return{id:r.id,agentId:r.agentId,kind:r.kind,text:Ka(r.text,xT),enqueuedAt:za(r.enqueuedAt)}}function xm(r){let e=r.cards.filter(i=>i.status==="pending").sort((i,o)=>String(i.created_at??"").localeCompare(String(o.created_at??""))).map(i=>({id:i.id,title:Ka(i.title,Ja),raised_by:i.raised_by,node:i.node??null,createdAt:i.created_at})),t=[...r.held].sort((i,o)=>i.at.localeCompare(o.at)).map(i=>({id:i.id,title:Ka(i.title,Ja),from:i.from,at:i.at,heldBecause:i.heldBecause})),n=(r.requests??[]).filter(i=>AT.has(i.state)).sort((i,o)=>i.createdAt-o.createdAt).map(i=>({id:i.id,title:ze(i,Ja).headline,agentId:i.agentId,state:i.state,since:za(i.stateChangedAt??i.updatedAt)})),s=r.voice;return{ts:za(r.now),cards:sr(e),held:sr(t),voice:s?{paused:s.paused,reserved:s.reserved,playing:s.playing?Tm(s.playing):null,waiting:sr(s.waiting.map(Tm))}:null,requests:sr(n),errors:r.errors??[]}}function Am(r){let e=[],t=n=>n.total>n.items.length?[` \u2026 and ${n.total-n.items.length} more`]:[];e.push(`Decision cards waiting for an answer: ${r.cards.total}`);for(let n of r.cards.items)e.push(` - ${n.title} (by ${n.raised_by}${n.node?` on ${n.node}`:""}, ${n.createdAt}, ${n.id})`);e.push(...t(r.cards)),e.push(`Notices held by Focus or a call: ${r.held.total}`);for(let n of r.held.items)e.push(` - ${n.title} (from ${n.from}, ${n.at})`);if(e.push(...t(r.held)),r.voice){let n=r.voice.paused?", paused":r.voice.reserved?", the floor is held":"";e.push(`Speaking now: ${r.voice.playing?`${r.voice.playing.agentId??"the host"}: ${r.voice.playing.text}`:"nothing"}${n}`),e.push(`Lines waiting to be spoken: ${r.voice.waiting.total}`);for(let s of r.voice.waiting.items)e.push(` - ${s.agentId??"the host"} (${s.kind}): ${s.text}`);e.push(...t(r.voice.waiting))}e.push(`Open requests waiting on the owner: ${r.requests.total}`);for(let n of r.requests.items)e.push(` - ${n.title} (${n.agentId}, ${n.state.replace("_"," ")} since ${n.since}, ${n.id})`);e.push(...t(r.requests));for(let n of r.errors)e.push(`Could not read: ${n}`);return e.join(`
3
3
  `)}import{resolve as tc}from"path";ST();var RT={name:"agentx",version:"0.1.0"},ET=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],CT="2024-11-05";function PT(r){return typeof r=="string"&&ET.includes(r)?r:CT}var _T={tools:{},elicitation:{form:{}}},MT=0;async function Rm(r,e){let t=++MT;return St({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Ln.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Ln.has(`elicit-${t}`)&&(Ln.delete(`elicit-${t}`),n(null))},6e4)})}var Ln=new Map,OT="http://localhost:18800",Ya;function DT(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=tc(process.cwd(),r);if(!Za(e))continue;let t=JSON.parse(ec(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 OT}function X(){return Ya===void 0&&(Ya=DT()),Ya}var Qa;function NT(r){try{let e=tc(process.cwd(),".env");if(!Za(e))return"";for(let t of ec(e,"utf-8").split(`
4
4
  `)){let n=t.trim().replace(/^export\s+/,"");if(!n.startsWith(`${r}=`))continue;let s=n.slice(r.length+1).trim();return/^(["']).*\1$/.test(s)?s.slice(1,-1):s}}catch{}return""}function LT(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=NT("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=tc(process.cwd(),t);if(!Za(n))continue;let s=JSON.parse(ec(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function jT(){return Qa===void 0&&(Qa=LT()),Qa}var V=(r,e)=>{let t=jT();if(!t)return fetch(r,e);let n=new Headers(e?.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${t}`),fetch(r,{...e,headers:n})};function Nn(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 FT(){let r=process.env.AGENTX_AGENT_ID,e=Nn();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await V(`${X()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var WT=1e4,UT=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function GT(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&UT.has(n))return`Error: the AgentX daemon could not be reached (${n}); the message to ${r} was not sent.`;let s=t?.name==="TimeoutError"||t?.name==="AbortError"?"no answer in time":t?.message||String(e);return`Probably delivered to ${r}: the daemon did not confirm (${s}), but the request was sent and is most likely queued. Do not treat this as a failure. If unsure, send the same message again: within 10 minutes a repeat returns the existing task id instead of a second task, and delivers it if the first never arrived. A busy ${r} shows no trace until its turn starts; later, \`agentx trace list --agent ${r} --since 1h\` or the daemon log ("[send/agent]") shows it.`}var HT=/\x1B\[[0-9;]*[A-Za-z]/g;function Jt(r){return r.replace(HT,"")}async function BT(r,e,t){let n=await V(`${X()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:qT(i,!!s.hasMore)}]}}function qT(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
@@ -531,7 +531,7 @@ ${l}`)}let S={agentId:o,message:w,context:{channel:g,sender:y?"opencode":"openai
531
531
 
532
532
  `)}}function Hy(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function By(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
533
533
 
534
- `)}function qy(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);xc(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function xc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Jn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Jn(`${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(Jn.levelOrder[e]<Jn.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)}},Vn=Jn;Lt(Vn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as QA,statSync as ZA}from"fs";var tt={version:"0.185.0",commit:"c462b3c",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function eR(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 Vy(){let r=null;try{r=ZA(QA(process.argv[1])).mtimeMs}catch{}let e=fy().version;return eR(tt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as tR}from"crypto";var Pr=class{constructor(e=new Ah){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!nR.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};rR(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:tR(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=sR(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}},nR=["run","task","signal","mesh","channel","status"];function sR(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 rR(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 Jy(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 _r,timingSafeEqual as Ky}from"crypto";var Mr=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,S]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=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 h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
534
+ `)}function qy(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);xc(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function xc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Jn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Jn(`${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(Jn.levelOrder[e]<Jn.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)}},Vn=Jn;Lt(Vn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as QA,statSync as ZA}from"fs";var tt={version:"0.185.1",commit:"0b0efec",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function eR(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 Vy(){let r=null;try{r=ZA(QA(process.argv[1])).mtimeMs}catch{}let e=fy().version;return eR(tt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as tR}from"crypto";var Pr=class{constructor(e=new Ah){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!nR.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};rR(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:tR(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=sR(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}},nR=["run","task","signal","mesh","channel","status"];function sR(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 rR(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 Jy(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 _r,timingSafeEqual as Ky}from"crypto";var Mr=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,S]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=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 h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
535
535
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
536
536
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
537
537
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+_r("sha256",a).update(t).digest("hex");return Zt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Zt(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=_r("sha256",a).update(`${u.t}.${t}`).digest("hex");return Zt(h,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-h;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let y="POST",g=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],w=e.host,S=e["x-forwarded-proto"]||"https",k=new Set;b&&g&&k.add(`${S}://${b}${g}`),w&&g&&k.add(`https://${w}${g}`),w&&g&&k.add(`http://${w}${g}`),g&&k.add(g),k.add("");for(let x of k){let E=_r("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(d.length===E.length&&Ky(Buffer.from(d),Buffer.from(E)))return null}return`signature mismatch (tried ${k.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let h=_r("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return Zt(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Zt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Zt(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 Zt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Ky(t,n)?null:"signature mismatch"}vu();Vd();fu();mT();function iR(r){return{insertTaskHistory:r.prepare(`
@@ -1336,4 +1336,4 @@ data: ${JSON.stringify(z)}
1336
1336
  `)}catch{}},L=setInterval(()=>{try{t.write(`: ping
1337
1337
 
1338
1338
  `)}catch{}},15e3);L.unref?.();let H=new AbortController;t.on("close",()=>{t.writableEnded||H.abort()});try{for await(let W of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:H.signal,vouchOwner:$}))C(W.event,W.data)}catch(W){C("error",{error:W?.message??String(W)})}finally{clearInterval(L);try{t.end()}catch{}}break}let _=p.context,M=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(J$(p,!0)==="callback"){let C=this.delegationGate(e,p,{callee:p.agent,peer:p.peer,message:p.message,calleeContext:_});if(!("track"in C)){let L=wo(C);this.json(t,L.status,L.body);break}}if(p.async===!0){let C=_?.channel,L=_?.chatId;if(!C||!L){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let H=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:H,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let W=p.peer,z=p.agent,Se=this.mesh;(async()=>{let J=Date.now(),Y;try{Y=await Se.sendTask(W,p.message,z,{vouchOwner:$,context:_,senderAgentId:M}),this.log(`[mesh/task async ${H}] ${W}/${z??"default"} finished in ${Date.now()-J}ms`)}catch(K){Y=`Delegation to ${W}/${z??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${H}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:Y,agentId:_?.agentId??M,accountId:_?.accountId})}catch(K){this.log(`[mesh/task async ${H}] delivery failed: ${K?.message??K}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:_,senderAgentId:M,vouchOwner:$});this.json(t,200,{response:N});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=await this.webrtc.handleOutgoing(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=this.webrtc.handleIncoming(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let p=await U(e),m=p.callId,v=p.target,$=p.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!v||!$){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:v,agentId:$});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let p=this.config.channels.webrtc;if(!p?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...p.stunServers.map(m=>({urls:m})),...p.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:p.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(p=>{let m=this.config.agents[p.id]||{},v=typeof m.description=="string"&&m.description.trim()||aj(m.systemPrompt)||`Agent "${p.name}" (${p.tier})`,$=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:p.id,name:p.name,description:v,tags:[p.tier,...$],color:we(p.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let p=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:p.summary()});break}case"GET /wiki/entries":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,v=n.searchParams.get("after")||void 0,$=m?p.getAgentEntries(m):p.getSharedStore().listEntries({after:v});this.json(t,200,{nodeId:this.config.node.id,count:$.length,entries:$.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let $=p.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:$.articles});break}case"GET /wiki/article":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent"),v=n.searchParams.get("path");if(!m||!v){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=p.getAgentWiki(m).readArticle(v);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /wiki/notes":{let{NoteStore:p}=await import("./notes-WJJEJ4CJ.js"),m=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(m)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let v=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new p(this.registry.getWikiHub().getBaseDir()).list(m==="all"?void 0:m);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:I.length,notes:I.slice(-v).reverse()});break}case"POST /wiki/notes":{let{NoteStore:p,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),v=this.config.wikiNotes;if(!v.enabled||!v.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let $=await U(e),I=m({...$,to:v.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let R=I.note;if(this.registry.getAgent(v.inbox)){try{let{note:N,added:C}=new p(this.registry.getWikiHub().getBaseDir()).add(R);this.json(t,C?201:200,{ok:!0,added:C,note:N,node:this.config.node.id})}catch(N){this.json(t,507,{error:N?.message??String(N)})}break}if($.forwarded===!0){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node`});break}let _=this.mesh?.findAgentPeer(v.inbox);if(!_){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node or any known peer`});break}let M=this.mesh.directory().find(N=>N.peer===_.peer)?.peerUrl;if(!_.healthy||!M){this.json(t,503,{error:`the node hosting "${v.inbox}" (${_.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${M.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(_.peer)},body:JSON.stringify({...R,fromNode:R.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await N.json().catch(()=>({}));this.json(t,N.status,{...C,peer:_.peer})}catch(N){this.json(t,502,{error:`forward to ${_.peer} failed: ${N?.message??N}`,peer:_.peer})}break}case"GET /graph/schema":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:p.loadSchema()});break}case"GET /graph/nodes":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...p.loadNodes()});break}case"GET /graph/classifications":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",v=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),$=p.listByStatus(m,v);this.json(t,200,{nodeId:this.config.node.id,status:m,count:$.length,classifications:$});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await Xy(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=af(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=vw();if(e==="json")return this.registry.getTodayUsage();let t=kw(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||!vn(n)))try{let s=te(n,".claude","skills");iT(s,{recursive:!0});let i=te(s,xS);if(!vn(i))jd(i,Ml(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=RS(Is(i,"utf-8"),e);o&&(jd(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||!vn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||Og(this.config.workflows,e)),i=Yh(oh(t),this.config.requests.enabled||s?zh():null);try{switch(Qh(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return iS(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(y=>y.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-NR7SLHGX.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return Wp(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-NR7SLHGX.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await TS({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Fd=Wd;Lt(Fd,"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 aj(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function cj(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}function oT(r){let e=r.business;return JSON.stringify([e?.roles,e?.orgChart,e?.relations,e?.projects,(r.people??[]).map(t=>t.id)])}cT();function Jz(r){typeof r=="string"&&(xs.error(r),process.exit(1)),r instanceof Error&&(xs.error(r.message),process.exit(1)),xs.error("Something went wrong. Please try again."),process.exit(1)}export{xj as a,nc as b,$t as c,Fn as d,Un as e,xt as f,pr as g,fy as h,cw as i,fR as j,mR as k,gw as l,Te as m,mw as n,yw as o,Dr as p,b2 as q,k2 as r,Kr as s,LU as t,EC as u,CC as v,zc as w,gb as x,jU as y,$b as z,_C as A,Ib as B,Tb as C,xb as D,FU as E,WU as F,UU as G,ni as H,je as I,VG as J,CP as K,Hk as L,Bk as M,y_ as N,av as O,uv as P,iM as Q,xl as R,WB as S,UB as T,GB as U,pS as V,LM as W,VB as X,JB as Y,os as Z,un as _,as as $,b4 as aa,qS as ba,xO as ca,uq as da,Gi as ea,Xl as fa,Vl as ga,Vi as ha,we as ia,N0 as ja,Yi as ka,TD as la,K0 as ma,AD as na,Z0 as oa,eo as pa,fs as qa,ro as ra,oo as sa,i$ as ta,ad as ua,h$ as va,ct as wa,Ee as xa,y$ as ya,w$ as za,b$ as Aa,k$ as Ba,xo as Ca,mI as Da,Ed as Ea,wI as Fa,uL as Ga,M3 as Ha,Fd as Ia,Jz as Ja};
1339
- //# sourceMappingURL=chunk-2HZXLYWQ.js.map
1339
+ //# sourceMappingURL=chunk-UXWG4DMD.js.map
@@ -9,4 +9,4 @@ To do: ${n}`}function le(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTi
9
9
  `),we(r,n)}function _e(e,t){Q(x(e),{recursive:!0});for(let n=1;;n++){let r=n===1?t:{...t,id:`${t.id}-${n}`},i=N(e,r.id),o=`${i}.${process.pid}.tmp`;Z(o,JSON.stringify(r,null,2)+`
10
10
  `);try{return fe(o,i),r}catch(s){if(s.code!=="EEXIST")throw s}finally{ke(o)}}}function b(e,t){if(!re(t))return null;try{let n=JSON.parse(he(N(e,t),"utf-8")),r=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:T(n.if_silent)??"keep",...n.outcome?{outcome:T(n.outcome)??"keep"}:{},...r?{if_silent_asked:"approve"}:{}}}catch{return null}}function m(e,t){let n=x(e);if(!ge(n))return[];let r=[];for(let i of pe(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=b(e,i.slice(0,-5));o&&(!t||o.status===t)&&r.push(o)}return r}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function be(e,t,n){let r=t+n.maxExpiryDays*864e5,i,o=a(e);if(!o)i=t+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=t+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=t?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,r)).toISOString()}}function $e(e,t={}){let n=t.now??Date.now(),r=t.settings??ye,i=a(e.title),o=a(e.ask),s=a(e.recommend),c=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!c)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>l.title)return{ok:!1,error:`title is longer than ${l.title} characters`};if(o.length>l.ask)return{ok:!1,error:`ask is longer than ${l.ask} characters`};if(s.length>l.recommend)return{ok:!1,error:`recommend is longer than ${l.recommend} characters`};let g=a(e.if_silent).toLowerCase(),h=T(g);if(!h)return{ok:!1,error:`if_silent must be one of ${te.join(", ")}`};let d=be(e.expires,n,r);if(!d.ok)return d;let p=a(e.source);if(p.length>l.source)return{ok:!1,error:`source is longer than ${l.source} characters`};if(p&&/^[a-z][a-z0-9+.-]*:/i.test(p)&&!/^https?:\/\//i.test(p))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let $=A(e);if(!$.ok)return $;let w=a(e.followup).toLowerCase();if(w&&!R.includes(w))return{ok:!1,error:`followup must be one of ${R.join(", ")}`};let S,f=e.reply;return f&&typeof f=="object"&&a(f.channel)&&a(f.chatId)&&(S={channel:a(f.channel),chatId:a(f.chatId),...a(f.accountId)?{accountId:a(f.accountId)}:{}}),{ok:!0,card:{id:xe(n,i),title:i,ask:o,recommend:s,if_silent:h,...g==="approve"?{if_silent_asked:"approve"}:{},expires:d.at,...p?{source:p}:{},raised_by:c,...t.node?{node:t.node}:{},created_at:new Date(n).toISOString(),...S?{reply:S}:{},...$.value,...t.origin?{origin:t.origin}:{},...w?{followup:w}:{},status:"pending"}}}function Se(e,t){if(!(!t.source||t.origin))return e.find(n=>!n.origin&&n.source===t.source&&n.raised_by===t.raised_by&&(n.node??"")===(t.node??""))}function Me(e,t,n={}){let r=$e(t,n);if(!r.ok)return r;let i=H(r.card);if(i)return{ok:!1,error:i};if(r.card.followup){let d=X(m(e),r.card.followup,n.now??Date.now());if(d)return{ok:!1,error:d}}let o=m(e,"pending"),s=Se(o,r.card);if(s)return{ok:!1,error:`a card from you on this source is still pending: ${s.id}. Wait for its answer, or resolve it first and then raise the new one.`};let c=d=>U(d.origin),g=c(r.card),h=o.filter(d=>d.raised_by===r.card.raised_by&&c(d)===g).length;if(h>=l.pendingPerAgent){let d=g?"retro cards":"cards";return{ok:!1,error:`${r.card.raised_by} already has ${h} ${d} waiting; wait for decisions before raising more`}}return{ok:!0,card:_e(e,r.card)}}function Ue(e,t,n,r={}){let i=b(e,t);if(!i)return{ok:!1,error:`no card "${t}"`};if(i.status!=="pending")return{ok:!1,error:`card "${t}" is already ${i.status}`};let o=q(i,n,r);if(!o.ok)return o;let s=a(r.note).slice(0,l.note),c={...i,status:"decided",verdict:n,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.suggested?{choice_suggested:!0}:{},...o.text?{text:o.text}:{}};return _(e,c),{ok:!0,card:c}}var Ce=new Set([void 0,"reminder"]);function Je(e,t,n){let r=b(e,t);if(!r)return{ok:!1,status:404,error:`no card "${t}"`};if(r.raised_by!==n.by||(r.node??"")!==(n.node??"")){let c=r.node?`${r.raised_by} on node "${r.node}"`:r.raised_by,g=r.node?"it closes it through its own node's daemon":"it closes it from one of its running turns";return{ok:!1,status:403,error:`card "${t}" was raised by another agent (${c}): only that agent can close it (${g}), or the operator answers it in Approvals`}}if(!Ce.has(r.origin?.kind))return{ok:!1,status:409,error:`card "${t}" is answered by the operator only`};if(r.status!=="pending")return{ok:!1,status:409,error:`card "${t}" is already ${r.status}`};let i=a(n.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(n.now??Date.now()).toISOString(),s={...r,status:"resolved",decided_by:n.by,decided_at:o,resolution:i.slice(0,l.resolution),agent_notified_at:o};return _(e,s),W(e,{key:`card:${t}`,kind:"card",title:r.title,raised_by:r.raised_by,answer:"closed",text:s.resolution,by:n.node?`${n.by} on ${n.node}`:n.by,at:o}),{ok:!0,card:s}}function Ve(e,t=Date.now()){let n=[];for(let r of m(e,"pending")){if(Date.parse(r.expires)>t)continue;let i={...r,status:"expired",outcome:r.if_silent,decided_by:"expiry",decided_at:new Date(t).toISOString()};_(e,i),n.push(i)}return n}function Ge(e){return m(e).filter(t=>t.status!=="pending"&&!t.agent_notified_at)}function ze(e,t,n=Date.now()){let r=b(e,t);!r||r.agent_notified_at||_(e,{...r,agent_notified_at:new Date(n).toISOString()})}var Ie="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function Ye(e){let t=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?t&&!v(e)?`The operator picked "${E}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,r=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!t&&!i&&r.push(...F(e)),e.note&&r.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!t&&!i&&r.push(Ie),e.source&&r.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&r.push(...z(e.origin,e.status==="decided"&&e.verdict==="yes")),t||i){let o=g=>g.replace(/\s+/g," ").trim(),s=L(e.draft,e.choice),c=e.text&&o(e.text)!==o(s)?e.text:void 0;r.push(...t?G(t,e,c):J(i,e,c))}return e.reply&&r.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&r.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),r.push("Act on this result now. Do not raise the same card again."),r.join(`
11
11
  `)}export{W as a,ce as b,Ee as c,U as d,M as e,v as f,E as g,Y as h,H as i,Ne as j,Ae as k,Le as l,te as m,l as n,x as o,re as p,b as q,m as r,Me as s,Ue as t,Je as u,Ve as v,Ge as w,ze as x,Ye as y};
12
- //# sourceMappingURL=chunk-BLWVMGSJ.js.map
12
+ //# sourceMappingURL=chunk-XPZSEDE3.js.map