agentix-cli 0.226.1 → 0.226.2

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.
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,r=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await ne.readFile(r,"utf8"),l=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await ne.writeFile(r,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${l.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-NTS5PNO4.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-77HLNAQF.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,r=t;return o?.length&&(r+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function Oe(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:p=!1,dryRun:c=!1,onProgress:d,abortSignal:u}=n,m=u?{...r,abortSignal:u}:r;if(!e.generateRaw)return mt(n);let I=new se(s,{interactive:a,overwrite:p,dryRun:c,acmeContext:n.acmeContext,abortSignal:u}),D=be(l);if(n.acmeContext)for(let g of ct)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(n.mcpTools?.length)for(let g of n.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,O=0,A="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),k.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let S=null,H=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?S=x.result:x.type==="error"&&(H=x.error);if(H&&!S)throw new Error(H);if(!S)throw new Error("generateRawStream returned no raw_result event");g=S,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(S){if(S.message?.includes("not available"))return mt(n);throw S}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,O+=g.usage.output_tokens;let P=g._streamedText;for(let S of g.content)S.type==="text"&&(A+=S.text,P===void 0&&d?.({type:"text_delta",text:S.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let S=g.content.filter(v=>v.type==="tool_use");if(S.length===0)break;C.push({role:"assistant",content:g.content});let H=[];for(let v of S){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),k.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&n.mcpDispatch){let h=await n.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),H.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:H}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:A,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:O||void 0,iterations:_}}async function mt(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,maxIterations:s=5}=n,l=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${n.projectInstructions}`),n.memoryContext&&o.push(n.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{We as a,Xt as b,Qt as c,Je as d,Ke as e,Xe as f,Qe as g,Pe as h,ee as i,Re as j,ce as k,te as l,Pt as m,oe as n,Et as o,f as p,ot as q,rt as r,Me as s,de as t,W as u,re as v,lt as w,Ee as x,$e as y,se as z,gt as A,tn as B,on as C};
126
- //# sourceMappingURL=chunk-IXOJEEGR.js.map
126
+ //# sourceMappingURL=chunk-W7PIHJHH.js.map
@@ -1,4 +1,4 @@
1
- import{$ as uw,A as un,Aa as _w,Ab as lb,B as Kr,Ba as Mw,Bb as ub,C as Yy,Ca as Ow,D as Qy,Da as rd,E as Zy,Ea as Zr,F as ew,Fa as Dw,G as tw,Gb as hb,H as nw,Ha as Nw,I as sw,Ia as id,J as rw,Ja as Lw,K as iw,Ka as Re,Kb as gb,L as ow,La as jw,Ma as Ww,Mb as ri,Na as Fw,Nb as dd,O as aw,Oa as hn,Ob as pb,Pb as fb,Q as cw,Qa as ei,Qb as mb,Ra as Uw,Rb as yb,S as td,Tb as wb,Ua as qw,Va as zw,Vb as bb,Xb as kb,Yb as vb,_ as lw,a as Iy,aa as zr,ab as ad,b as Kc,ba as Yr,bb as Pt,bc as Sb,cb as Yw,cc as $b,db as Qw,f as zc,g as Ty,gb as _t,h as Ay,ha as Qr,hb as Zw,i as Yc,ia as gw,ib as eb,j as xy,jb as tb,k as ds,ka as pw,kb as nb,l as Ry,lb as sb,lc as ld,m as Ey,ma as fw,mb as rb,mc as ud,n as Cy,na as Rw,o as Py,ob as Ee,oc as Ib,pa as sd,pb as ti,q as _y,qa as Ew,qb as cd,ra as dt,rb as ib,s as My,sb as ls,t as Ct,tb as ob,u as Zc,ua as Cw,ub as He,v as Xy,vb as ab,w as Jy,wb as cb,x as Vy,xa as Pw,xb as db,y as Ky,yb as ni,z as zy,zb as si}from"./chunk-M3K5B3WH.js";import{e as vy,h as Sy,i as $y}from"./chunk-2TVJTWFC.js";import{N as Wy,O as Fy,Q as Xr,R as ed,S as Jr,T as ln,X as hw,a as Ur,b as Wm,c as qc,d as Fm,e as qr,f as Um,g as qm,h as Gm,k as Hm,l as Bm,n as Xm,o as as,p as Me,q as Gc,r as Jm,s as Oe,x as Ly,z as jy}from"./chunk-BDHWTWD7.js";import{a as Oy}from"./chunk-ZVP6GB4G.js";import{b as mw}from"./chunk-MRIVENBY.js";import{i as yw,m as nd,n as ww,p as bw,q as kw,r as vw,s as Sw,t as $w,u as Iw}from"./chunk-KQ3LPQ2Z.js";import{a as Tw}from"./chunk-PPUN7YHA.js";import{a as Aw,b as xw}from"./chunk-VZLIBDLH.js";import{b as Gw,c as Hw,d as od,e as Bw,f as Xw,g as Jw,h as Vw,i as Kw}from"./chunk-EKJG63EJ.js";import{b as Vr}from"./chunk-UKUH662W.js";import{d as qy}from"./chunk-3Q6MRG3P.js";import{a as Uy}from"./chunk-2P5NP4H6.js";import{g as Gy}from"./chunk-LQE73AZR.js";import{b as Hy,c as By}from"./chunk-2D3RYIDU.js";import{a as dw}from"./chunk-A24QXLEG.js";import{a as Dy,b as Ny}from"./chunk-A5GYG56I.js";import{o as Qc}from"./chunk-7K7ZQU3C.js";import{c as ey,d as ty,f as ny,g as sy,i as ry,k as iy,l as oy}from"./chunk-RX5O5637.js";import{d as ay}from"./chunk-5ELIX7BQ.js";import{b as cy,c as dy}from"./chunk-X7UQY7CH.js";import{a as ly,b as cs,c as uy,d as Gr,e as Hr,f as hy,g as Xc,h as gy,i as py,k as fy,l as my,m as yy,p as wy,q as Jc,r as by}from"./chunk-EYVPRIO3.js";import{a as Br,d as ky,e as Vc}from"./chunk-LTOSEP7C.js";import{a as Hc,b as Vm,c as Km}from"./chunk-QPABR72X.js";import{a as zm,b as Ge,c as Ym,d as Qm,e as Zm}from"./chunk-IFUAP7UD.js";import{c as dn}from"./chunk-KP7KDLZ2.js";import{$ as kf,A as Lp,Aa as de,B as xt,Ba as Am,C as jp,Ca as xm,D as Wp,Da as Em,E as Fp,Ea as Uc,F as Up,Fa as Cm,G as qp,Ga as Pm,H as Cr,Ha as _m,I as Gp,J as nt,K as Pr,Ka as Om,L as nn,M as Vp,N as B,Na as Dm,P as ef,Q as tf,R as nf,S as sf,T as we,U as of,V as af,W as cf,Wa as Nm,X as rn,Y as df,Z as _r,_ as bf,a as qh,aa as vf,b as ip,ba as gm,c as ap,ca as pm,d as cp,da as fm,e as dp,ea as mm,f as lp,fa as ym,g as hp,ga as wm,h as Sc,i as Rp,ia as vm,j as Ep,ja as Sm,k as ss,ka as $m,la as Im,m as xc,ma as os,n as Rc,na as Tm,o as Ec,p as Cc,q as Cp,qa as ce,ra as ct,sa as jc,ta as on,ua as Wc,va as jr,wa as an,xa as cn,ya as Te,z as Mp,za as Et}from"./chunk-TO7ZERY3.js";import{$ as Lr,Ca as km,Ea as Wr,G as yf,Ga as Fc,H as wf,Ha as Rm,Ka as Mm,N as Sf,P as $f,R as If,S as Tf,T as Gf,U as Hf,V as zf,W as Yf,X as Qf,Y as Zf,_ as Lc,a as Op,aa as em,ba as tm,c as Hp,ca as nm,d as Bp,da as sm,e as Rt,ea as rm,f as qe,fa as im,ga as om,h as uf,ha as am,i as hf,j as gf,ja as cm,k as _c,l as pf,m as ff,ma as dm,p as mf,q as Or,ra as lm,sa as um,va as hm,ya as bm}from"./chunk-7GDFB4FS.js";import{a as Pc,b as Np}from"./chunk-MEFPXHQJ.js";import{a as it,d as lf,e as Mr}from"./chunk-7AB3QUGH.js";import{A as Lm,B as Fr,C as jm,h as Fh,n as Uh,o as Qa}from"./chunk-IXOJEEGR.js";import{b as Lh}from"./chunk-SFQUP3BP.js";import{a as Bc}from"./chunk-6TTGRTDO.js";import{a as Ef,b as Mc,c as Cf,d as Pf,e as _f,i as Mf,j as Of}from"./chunk-VE3SSOQX.js";import{b as rf}from"./chunk-W4YR2RO2.js";import{b as Nf,c as Lf,d as Oc,f as Dr,g as jf,h as Wf,i as Ff,j as is,k as Nr,m as Dc,n as Uf,o as qf}from"./chunk-IH65GDJR.js";import{e as ye,f as Xp,h as st,i as Jp,j as rt,k as rs,m as Ie,n as Df,o as ot,p as at,q as Jf,t as Vf,v as Kf,x as Nc}from"./chunk-CF2R6BOX.js";import{a as Bf,b as Xf}from"./chunk-Q6TGKWZE.js";import{d as Kp,e as zp,f as Yp,g as Qp,h as Zp,j as sn}from"./chunk-X5C5W3E4.js";import{g as Af,h as xf,i as Rf}from"./chunk-FG2FPOML.js";import{c as _p}from"./chunk-LUOW2YHY.js";import{b as Dp}from"./chunk-5ONH4ITT.js";import{c as up}from"./chunk-MYVHVJWZ.js";import{d as gp,e as pp,f as $c,g as Ar,h as fp,i as mp,j as yp,k as wp,l as Tp,m as tn,o as Ap,z as xp}from"./chunk-74MHOALB.js";import{A as Rr,d as kp,i as Ic,o as Tc,p as vp,q as xr,s as At,t as en,u as $e,w as Sp,x as $p,y as Ip,z as Ac}from"./chunk-3323WFVK.js";import{a as tt}from"./chunk-4NZ4T3TQ.js";import{e as bp}from"./chunk-LY4G7PCW.js";import{c as Pp}from"./chunk-A7JSRDJL.js";import{c as Er}from"./chunk-OWNQ2FD4.js";import{d as Hh,e as xE,m as np,n as UE,q as sp,v as rp,x as vc,y as et,z as ns}from"./chunk-BTLADRMY.js";import{a as Ue,b as ts,f as Tr}from"./chunk-72SZI2UW.js";import{a as Xn,b as Gh}from"./chunk-FCPTN6NF.js";import{f as op}from"./chunk-QUFIUXMQ.js";import{o as Bn,p as AE}from"./chunk-DCIYOPJF.js";import{a as or,b as TE}from"./chunk-7I7IEX4S.js";import{b as jh,e as Wh}from"./chunk-JHCI6XCJ.js";import{e as $t}from"./chunk-DSYKYZMT.js";import{$ as ac,$a as Yn,Aa as hg,Ab as Sr,Ba as zn,Bb as Bg,Cb as es,Db as $r,Dc as FE,Ea as gg,Eb as Xg,F as ec,Fa as Ye,Fb as Jg,G as cr,Ga as pg,Gb as Vg,H as tc,Ha as lc,Hb as Kg,Ia as Tg,Ib as zg,J as nc,Ja as DE,K as dr,Ka as Ag,La as NE,Lb as Yg,M as sc,Ma as xg,N as zh,Na as LE,O as Yh,Ob as Qg,P as Qh,Pa as _e,Pb as Ir,Qa as Rg,R as Vn,Ra as Eg,S as rc,Sa as pc,Tb as Zg,Ua as fc,Va as Qe,Vb as bc,W as Qt,Wa as Ze,X as eg,Xa as Cg,Xb as jE,Y as oc,Ya as Pg,Z as CE,_ as lr,_a as mc,aa as ur,ab as _g,ba as hr,bb as Qn,c as Bh,cb as Mg,da as It,ea as cc,fa as tg,fb as Og,ga as PE,gb as Dg,ha as gr,hb as Fe,ia as _E,ib as yc,ja as pr,jb as Ng,ka as ng,kb as Lg,l as RE,la as ME,lb as wr,ma as sg,mb as jg,na as rg,nb as br,o as Jn,oa as ig,ob as Wg,pb as Fg,q as ar,qb as Ug,r as Za,ra as dc,rb as qg,sa as cg,sb as wc,ta as dg,tb as Zn,tc as kc,u as Xh,ua as Kn,ub as kr,v as Jh,va as yr,w as Vh,wa as lg,wb as Zt,wc as tp,x as Kh,xa as ug,xb as vr,y as EE,yb as Gg,zb as Hg}from"./chunk-FWNP27H4.js";import{a as og,e as Tt,f as ag,g as fr,h as mr}from"./chunk-KEUW6YLL.js";import{a as fg,b as mg,c as yg,e as wg,f as bg,i as OE,j as uc,k as kg,l as vg,m as hc,n as Sg,o as $g,q as gc,r as Ig}from"./chunk-N47Y5ADQ.js";import{b as ic,e as Zh}from"./chunk-VQRY4IDI.js";import{b as ep,c as WE}from"./chunk-YSCT6DPR.js";import{d as Yt}from"./chunk-QIJLFPWE.js";import{existsSync as bd,readFileSync as kd}from"fs";ig();var Tb=["answer","narration","line"],Ab=5e3;function xb(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Rb(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let d=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!d||!l||!Tb.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${Tb.join(" | ")}`}};if(d.length>Ab)return{status:413,body:{error:`text is over ${Ab} characters`}};let h=e(l);if(!h)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:y}=r.enqueue({voice:h,text:d,agentId:l,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,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()}:hd(o);case"front":return r.front(o)?{status:200,body:r.view()}:hd(o);case"replay":{let d=r.replay(o);return d?{status:202,body:{item:d}}:hd(o)}default:return{status:404,body:{error:"Not found"}}}}function Eb(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?[rg(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$ as uw,A as un,Aa as _w,Ab as lb,B as Kr,Ba as Mw,Bb as ub,C as Yy,Ca as Ow,D as Qy,Da as rd,E as Zy,Ea as Zr,F as ew,Fa as Dw,G as tw,Gb as hb,H as nw,Ha as Nw,I as sw,Ia as id,J as rw,Ja as Lw,K as iw,Ka as Re,Kb as gb,L as ow,La as jw,Ma as Ww,Mb as ri,Na as Fw,Nb as dd,O as aw,Oa as hn,Ob as pb,Pb as fb,Q as cw,Qa as ei,Qb as mb,Ra as Uw,Rb as yb,S as td,Tb as wb,Ua as qw,Va as zw,Vb as bb,Xb as kb,Yb as vb,_ as lw,a as Iy,aa as zr,ab as ad,b as Kc,ba as Yr,bb as Pt,bc as Sb,cb as Yw,cc as $b,db as Qw,f as zc,g as Ty,gb as _t,h as Ay,ha as Qr,hb as Zw,i as Yc,ia as gw,ib as eb,j as xy,jb as tb,k as ds,ka as pw,kb as nb,l as Ry,lb as sb,lc as ld,m as Ey,ma as fw,mb as rb,mc as ud,n as Cy,na as Rw,o as Py,ob as Ee,oc as Ib,pa as sd,pb as ti,q as _y,qa as Ew,qb as cd,ra as dt,rb as ib,s as My,sb as ls,t as Ct,tb as ob,u as Zc,ua as Cw,ub as He,v as Xy,vb as ab,w as Jy,wb as cb,x as Vy,xa as Pw,xb as db,y as Ky,yb as ni,z as zy,zb as si}from"./chunk-LLVVT5OB.js";import{e as vy,h as Sy,i as $y}from"./chunk-2TVJTWFC.js";import{N as Wy,O as Fy,Q as Xr,R as ed,S as Jr,T as ln,X as hw,a as Ur,b as Wm,c as qc,d as Fm,e as qr,f as Um,g as qm,h as Gm,k as Hm,l as Bm,n as Xm,o as as,p as Me,q as Gc,r as Jm,s as Oe,x as Ly,z as jy}from"./chunk-BDHWTWD7.js";import{a as Oy}from"./chunk-ZVP6GB4G.js";import{b as mw}from"./chunk-MRIVENBY.js";import{i as yw,m as nd,n as ww,p as bw,q as kw,r as vw,s as Sw,t as $w,u as Iw}from"./chunk-KQ3LPQ2Z.js";import{a as Tw}from"./chunk-PPUN7YHA.js";import{a as Aw,b as xw}from"./chunk-VZLIBDLH.js";import{b as Gw,c as Hw,d as od,e as Bw,f as Xw,g as Jw,h as Vw,i as Kw}from"./chunk-EKJG63EJ.js";import{b as Vr}from"./chunk-UKUH662W.js";import{d as qy}from"./chunk-3Q6MRG3P.js";import{a as Uy}from"./chunk-2P5NP4H6.js";import{g as Gy}from"./chunk-LQE73AZR.js";import{b as Hy,c as By}from"./chunk-2D3RYIDU.js";import{a as dw}from"./chunk-A24QXLEG.js";import{a as Dy,b as Ny}from"./chunk-A5GYG56I.js";import{o as Qc}from"./chunk-7K7ZQU3C.js";import{c as ey,d as ty,f as ny,g as sy,i as ry,k as iy,l as oy}from"./chunk-RX5O5637.js";import{d as ay}from"./chunk-5ELIX7BQ.js";import{b as cy,c as dy}from"./chunk-X7UQY7CH.js";import{a as ly,b as cs,c as uy,d as Gr,e as Hr,f as hy,g as Xc,h as gy,i as py,k as fy,l as my,m as yy,p as wy,q as Jc,r as by}from"./chunk-EYVPRIO3.js";import{a as Br,d as ky,e as Vc}from"./chunk-LTOSEP7C.js";import{a as Hc,b as Vm,c as Km}from"./chunk-QPABR72X.js";import{a as zm,b as Ge,c as Ym,d as Qm,e as Zm}from"./chunk-IFUAP7UD.js";import{c as dn}from"./chunk-KP7KDLZ2.js";import{$ as kf,A as Lp,Aa as de,B as xt,Ba as Am,C as jp,Ca as xm,D as Wp,Da as Em,E as Fp,Ea as Uc,F as Up,Fa as Cm,G as qp,Ga as Pm,H as Cr,Ha as _m,I as Gp,J as nt,K as Pr,Ka as Om,L as nn,M as Vp,N as B,Na as Dm,P as ef,Q as tf,R as nf,S as sf,T as we,U as of,V as af,W as cf,Wa as Nm,X as rn,Y as df,Z as _r,_ as bf,a as qh,aa as vf,b as ip,ba as gm,c as ap,ca as pm,d as cp,da as fm,e as dp,ea as mm,f as lp,fa as ym,g as hp,ga as wm,h as Sc,i as Rp,ia as vm,j as Ep,ja as Sm,k as ss,ka as $m,la as Im,m as xc,ma as os,n as Rc,na as Tm,o as Ec,p as Cc,q as Cp,qa as ce,ra as ct,sa as jc,ta as on,ua as Wc,va as jr,wa as an,xa as cn,ya as Te,z as Mp,za as Et}from"./chunk-TEYFN6YL.js";import{$ as Lr,Ca as km,Ea as Wr,G as yf,Ga as Fc,H as wf,Ha as Rm,Ka as Mm,N as Sf,P as $f,R as If,S as Tf,T as Gf,U as Hf,V as zf,W as Yf,X as Qf,Y as Zf,_ as Lc,a as Op,aa as em,ba as tm,c as Hp,ca as nm,d as Bp,da as sm,e as Rt,ea as rm,f as qe,fa as im,ga as om,h as uf,ha as am,i as hf,j as gf,ja as cm,k as _c,l as pf,m as ff,ma as dm,p as mf,q as Or,ra as lm,sa as um,va as hm,ya as bm}from"./chunk-TA437DWX.js";import{a as Pc,b as Np}from"./chunk-MEFPXHQJ.js";import{a as it,d as lf,e as Mr}from"./chunk-7AB3QUGH.js";import{A as Lm,B as Fr,C as jm,h as Fh,n as Uh,o as Qa}from"./chunk-W7PIHJHH.js";import{b as Lh}from"./chunk-SFQUP3BP.js";import{a as Bc}from"./chunk-6TTGRTDO.js";import{a as Ef,b as Mc,c as Cf,d as Pf,e as _f,i as Mf,j as Of}from"./chunk-VE3SSOQX.js";import{b as rf}from"./chunk-W4YR2RO2.js";import{b as Nf,c as Lf,d as Oc,f as Dr,g as jf,h as Wf,i as Ff,j as is,k as Nr,m as Dc,n as Uf,o as qf}from"./chunk-IH65GDJR.js";import{e as ye,f as Xp,h as st,i as Jp,j as rt,k as rs,m as Ie,n as Df,o as ot,p as at,q as Jf,t as Vf,v as Kf,x as Nc}from"./chunk-CF2R6BOX.js";import{a as Bf,b as Xf}from"./chunk-Q6TGKWZE.js";import{d as Kp,e as zp,f as Yp,g as Qp,h as Zp,j as sn}from"./chunk-X5C5W3E4.js";import{g as Af,h as xf,i as Rf}from"./chunk-FG2FPOML.js";import{c as _p}from"./chunk-LUOW2YHY.js";import{b as Dp}from"./chunk-5ONH4ITT.js";import{c as up}from"./chunk-MYVHVJWZ.js";import{d as gp,e as pp,f as $c,g as Ar,h as fp,i as mp,j as yp,k as wp,l as Tp,m as tn,o as Ap,z as xp}from"./chunk-74MHOALB.js";import{A as Rr,d as kp,i as Ic,o as Tc,p as vp,q as xr,s as At,t as en,u as $e,w as Sp,x as $p,y as Ip,z as Ac}from"./chunk-3323WFVK.js";import{a as tt}from"./chunk-4NZ4T3TQ.js";import{e as bp}from"./chunk-LY4G7PCW.js";import{c as Pp}from"./chunk-A7JSRDJL.js";import{c as Er}from"./chunk-OWNQ2FD4.js";import{d as Hh,e as xE,m as np,n as UE,q as sp,v as rp,x as vc,y as et,z as ns}from"./chunk-BTLADRMY.js";import{a as Ue,b as ts,f as Tr}from"./chunk-72SZI2UW.js";import{a as Xn,b as Gh}from"./chunk-FCPTN6NF.js";import{f as op}from"./chunk-QUFIUXMQ.js";import{o as Bn,p as AE}from"./chunk-DCIYOPJF.js";import{a as or,b as TE}from"./chunk-7I7IEX4S.js";import{b as jh,e as Wh}from"./chunk-JHCI6XCJ.js";import{e as $t}from"./chunk-DSYKYZMT.js";import{$ as ac,$a as Yn,Aa as hg,Ab as Sr,Ba as zn,Bb as Bg,Cb as es,Db as $r,Dc as FE,Ea as gg,Eb as Xg,F as ec,Fa as Ye,Fb as Jg,G as cr,Ga as pg,Gb as Vg,H as tc,Ha as lc,Hb as Kg,Ia as Tg,Ib as zg,J as nc,Ja as DE,K as dr,Ka as Ag,La as NE,Lb as Yg,M as sc,Ma as xg,N as zh,Na as LE,O as Yh,Ob as Qg,P as Qh,Pa as _e,Pb as Ir,Qa as Rg,R as Vn,Ra as Eg,S as rc,Sa as pc,Tb as Zg,Ua as fc,Va as Qe,Vb as bc,W as Qt,Wa as Ze,X as eg,Xa as Cg,Xb as jE,Y as oc,Ya as Pg,Z as CE,_ as lr,_a as mc,aa as ur,ab as _g,ba as hr,bb as Qn,c as Bh,cb as Mg,da as It,ea as cc,fa as tg,fb as Og,ga as PE,gb as Dg,ha as gr,hb as Fe,ia as _E,ib as yc,ja as pr,jb as Ng,ka as ng,kb as Lg,l as RE,la as ME,lb as wr,ma as sg,mb as jg,na as rg,nb as br,o as Jn,oa as ig,ob as Wg,pb as Fg,q as ar,qb as Ug,r as Za,ra as dc,rb as qg,sa as cg,sb as wc,ta as dg,tb as Zn,tc as kc,u as Xh,ua as Kn,ub as kr,v as Jh,va as yr,w as Vh,wa as lg,wb as Zt,wc as tp,x as Kh,xa as ug,xb as vr,y as EE,yb as Gg,zb as Hg}from"./chunk-FWNP27H4.js";import{a as og,e as Tt,f as ag,g as fr,h as mr}from"./chunk-KEUW6YLL.js";import{a as fg,b as mg,c as yg,e as wg,f as bg,i as OE,j as uc,k as kg,l as vg,m as hc,n as Sg,o as $g,q as gc,r as Ig}from"./chunk-N47Y5ADQ.js";import{b as ic,e as Zh}from"./chunk-VQRY4IDI.js";import{b as ep,c as WE}from"./chunk-YSCT6DPR.js";import{d as Yt}from"./chunk-QIJLFPWE.js";import{existsSync as bd,readFileSync as kd}from"fs";ig();var Tb=["answer","narration","line"],Ab=5e3;function xb(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Rb(r,e,t,n,s,i){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:{...r.view(),...i?{floor:i.view()}:{}}};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let d=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),u=String(s.kind??"line");if(!d||!l||!Tb.includes(u))return{status:400,body:{error:`Required: text and agentId; kind is ${Tb.join(" | ")}`}};if(d.length>Ab)return{status:413,body:{error:`text is over ${Ab} characters`}};let h=e(l);if(!h)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:y}=r.enqueue({voice:h,text:d,agentId:l,kind:u,...typeof s.floor=="string"?{floor:s.floor}:{}});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,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()}:hd(o);case"front":return r.front(o)?{status:200,body:r.view()}:hd(o);case"replay":{let d=r.replay(o);return d?{status:202,body:{item:d}}:hd(o)}default:return{status:404,body:{error:"Not found"}}}}function Eb(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?[rg(r.floor)]:[],t,...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var hd=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});var qE=20,gd=120,GE=80,HE=new Set(["waiting_owner","needs_attention"]);function pd(r,e){let t=String(r??"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function ii(r){return{total:r.length,items:r.slice(0,qE)}}var fd=r=>new Date(r).toISOString();function Cb(r){return{id:r.id,agentId:r.agentId,kind:r.kind,text:pd(r.text,GE),enqueuedAt:fd(r.enqueuedAt)}}function Pb(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:pd(i.title,gd),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:pd(i.title,gd),from:i.from,at:i.at,heldBecause:i.heldBecause})),n=(r.requests??[]).filter(i=>HE.has(i.state)).sort((i,o)=>i.createdAt-o.createdAt).map(i=>({id:i.id,title:Oe(i,gd).headline,agentId:i.agentId,state:i.state,since:fd(i.stateChangedAt??i.updatedAt)})),s=r.voice;return{ts:fd(r.now),cards:ii(e),held:ii(t),voice:s?{paused:s.paused,reserved:s.reserved,playing:s.playing?Cb(s.playing):null,waiting:ii(s.waiting.map(Cb))}:null,requests:ii(n),errors:r.errors??[]}}function _b(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 vd}from"path";jE();var BE={name:"agentx",version:"0.1.0"},XE=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],JE="2024-11-05";function VE(r){return typeof r=="string"&&XE.includes(r)?r:JE}var KE={tools:{},elicitation:{form:{}}},zE=0;async function Mb(r,e){let t=++zE;return Mt({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{us.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{us.has(`elicit-${t}`)&&(us.delete(`elicit-${t}`),n(null))},6e4)})}var us=new Map,YE="http://localhost:18800",md;function QE(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=vd(process.cwd(),r);if(!bd(e))continue;let t=JSON.parse(kd(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 YE}function X(){return md===void 0&&(md=QE()),md}var yd;function ZE(r){try{let e=vd(process.cwd(),".env");if(!bd(e))return"";for(let t of kd(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 eC(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=ZE("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=vd(process.cwd(),t);if(!bd(n))continue;let s=JSON.parse(kd(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function tC(){return yd===void 0&&(yd=eC()),yd}var J=(r,e)=>{let t=tC();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 pn(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 nC(){let r=process.env.AGENTX_AGENT_ID,e=pn();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await J(`${X()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}function wd(r,e){let t=e.agentId;return t||r==="gitlab"&&process.env.AGENTX_AGENT_ID||void 0}var sC=1e4,rC=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function iC(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&rC.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 oC=/\x1B\[[0-9;]*[A-Za-z]/g;function gn(r){return r.replace(oC,"")}async function aC(r,e,t){let n=await J(`${X()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:cC(i,!!s.hasMore)}]}}function cC(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}:
@@ -541,7 +541,7 @@ ${d}`)}let S={agentId:o,message:b,context:{channel:p,sender:y?"opencode":"openai
541
541
 
542
542
  `)}}function iv(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function ov(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}]})}
543
543
 
544
- `)}function av(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Yd(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 Yd(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Is(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Is.levelOrder[e]<Is.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},$s=Is;Yt($s,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as j_,statSync as W_}from"fs";var Je={version:"0.226.1",commit:"2f2a6ce",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function F_(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 dv(){let r=null;try{r=W_(j_(process.argv[1])).mtimeMs}catch{}let e=kk().version;return F_(Je,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{existsSync as lv,mkdirSync as U_,readFileSync as q_,statSync as G_,writeFileSync as H_}from"fs";import{homedir as uv}from"os";import{dirname as B_,join as Qd,resolve as Zd}from"path";var hv=(r=uv())=>Qd(r,".agentx","daemon-root");function gv(r,e=uv()){let t=hv(e);U_(B_(t),{recursive:!0}),H_(t,Zd(r)+`
544
+ `)}function av(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Yd(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 Yd(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Is(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Is.levelOrder[e]<Is.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},$s=Is;Yt($s,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as j_,statSync as W_}from"fs";var Je={version:"0.226.2",commit:"db658d7",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function F_(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 dv(){let r=null;try{r=W_(j_(process.argv[1])).mtimeMs}catch{}let e=kk().version;return F_(Je,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{existsSync as lv,mkdirSync as U_,readFileSync as q_,statSync as G_,writeFileSync as H_}from"fs";import{homedir as uv}from"os";import{dirname as B_,join as Qd,resolve as Zd}from"path";var hv=(r=uv())=>Qd(r,".agentx","daemon-root");function gv(r,e=uv()){let t=hv(e);U_(B_(t),{recursive:!0}),H_(t,Zd(r)+`
545
545
  `)}var X_=r=>lv(Qd(r,"agentx.json"))||lv(Qd(r,".agentx","config.json"));function J_(r){try{return G_(r).isDirectory()}catch{return!1}}function KB(r={}){let e=Zd(r.cwd??process.cwd()),t=r.env??process.env;if(t.AGENTX_ROOT?.trim())return Zd(t.AGENTX_ROOT.trim());if(X_(e))return e;let n="";try{n=q_(hv(r.home),"utf-8").trim()}catch{}return n&&J_(n)?n:e}import{randomUUID as V_}from"crypto";var Li=class{constructor(e=new Vp){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!K_.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Y_(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:V_(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=z_(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}},K_=["run","task","signal","mesh","channel","status"];function z_(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 Y_(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 pv(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 ji,timingSafeEqual as fv}from"crypto";var Wi=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let w={};for(let[b,S]of Object.entries(e.headers))(b.startsWith("x-hubspot")||b.startsWith("x-hub")||b.startsWith("x-github")||b.startsWith("x-gitlab")||b.startsWith("stripe")||b.startsWith("sentry")||b.startsWith("x-vercel")||b.startsWith("x-odoo")||b.startsWith("x-webhook")||b==="user-agent"||b==="content-type"||b==="host"||b==="x-forwarded-host"||b==="x-forwarded-proto"||b==="x-forwarded-for")&&(w[b]=S);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(d,c,e.headers),g=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===d),y=h&&g?.triggers?.[h]||g?.defaultWorkflow||null;if(await this.fireHookSafe(d,h,i,c),y&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${d}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:h,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${h??"\u2014"}] -> workflow=${y} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:h,workflow:y,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${d}/${h}/${y}]: ${w.message}`)}let p=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===d);if(p?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:p.node,status:"accepted"}),this.mesh.sendTask(p.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(w=>this.log(`Mesh-forwarded webhook [${d}] -> ${p.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${d}] -> ${p.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:d,response:w.content?.slice(0,500),error:w.error,duration:w.duration})}catch(w){this.sendJson(t,500,{error:w.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
546
546
  `)[0]||"no message"} (${l.author?.name||""})`)}let d=t.object_attributes;if(d?.title&&(s.push(`Title: ${d.title}`),s.push(`State: ${d.state||""}`),s.push(`Action: ${d.action||""}`),d.source_branch&&s.push(`Branch: ${d.source_branch} -> ${d.target_branch}`),d.url&&s.push(`URL: ${d.url}`)),d?.iid&&!d?.source_branch&&(s.push(`Issue #${d.iid}: ${d.title||""}`),d.description&&s.push(`Description: ${d.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
547
547
  `)[0]||""} (${u.author?.name||""})`);let d=t.pull_request;d&&(s.push(`PR #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${d.head?.ref} -> ${d.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let d of a.slice(0,3)){let l=d.subscriptionType??"?",u=d.objectId??"?",h=d.changeFlag??d.changeSource??"";s.push(` - ${l} (object ${u}${h?`, ${h}`:""})`)}}else{let d=t.subscriptionType??"event",l=t.objectId??"?";s.push(`Event: ${d} (object ${l})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
@@ -1394,4 +1394,4 @@ data: ${JSON.stringify(F)}
1394
1394
  `)}catch{}},G=setInterval(()=>{try{t.write(`: ping
1395
1395
 
1396
1396
  `)}catch{}},15e3);G.unref?.();let K=new AbortController;t.on("close",()=>{t.writableEnded||K.abort()});try{for await(let Y of this.mesh.sendTaskStream(f.peer,f.message,f.agent,{context:f.context,signal:K.signal,vouchOwner:x}))U(Y.event,Y.data)}catch(Y){U("error",{error:Y?.message??String(Y)})}finally{clearInterval(G);try{t.end()}catch{}}break}let _=f.context,O=typeof f.senderAgentId=="string"?f.senderAgentId:void 0;if(fh(f,!0)==="callback"){let U=this.delegationGate(e,f,{callee:f.agent,peer:f.peer,message:f.message,calleeContext:_});if(!("track"in U)){let G=Ca(U);this.json(t,G.status,G.body);break}}if(f.async===!0){let U=_?.channel,G=_?.chatId;if(!U||!G){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let K=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:K,deliverTo:`${U}:${G}`,note:"result will be delivered to the originating chat when the peer finishes"});let Y=f.peer,F=f.agent,z=this.mesh;(async()=>{let te=Date.now(),Q;try{Q=await z.sendTask(Y,f.message,F,{vouchOwner:x,context:_,senderAgentId:O}),this.log(`[mesh/task async ${K}] ${Y}/${F??"default"} finished in ${Date.now()-te}ms`)}catch(me){Q=`Delegation to ${Y}/${F??"default"} failed: ${me?.message??me}`,this.log(`[mesh/task async ${K}] failed: ${me?.message??me}`)}try{await this.router.sendOutbound({channel:U,chatId:G,text:Q,agentId:_?.agentId??O,accountId:_?.accountId})}catch(me){this.log(`[mesh/task async ${K}] delivery failed: ${me?.message??me}`)}})();break}let j=await this.mesh.sendTask(f.peer,f.message,f.agent,{context:_,senderAgentId:O,vouchOwner:x});this.json(t,200,{response:j});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await q(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=await this.webrtc.handleOutgoing(m);this.json(t,k.ok?200:400,k);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await q(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=this.webrtc.handleIncoming(m);this.json(t,k.ok?200:400,k);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 f=await q(e),m=f.callId,k=f.target,$=f.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!k||!$){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:k,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 f=this.config.channels.webrtc;if(!f?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...f.stunServers.map(m=>({urls:m})),...f.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:f.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(f=>{let m=this.config.agents[f.id]||{},k=typeof m.description=="string"&&m.description.trim()||kq(m.systemPrompt)||`Agent "${f.name}" (${f.tier})`,$=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:f.id,name:f.name,description:k,tags:[f.tier,...$],color:Se(f.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let f=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:f.summary()});break}case"GET /wiki/entries":{let f=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,k=n.searchParams.get("after")||void 0,$=m?f.getAgentEntries(m):f.getSharedStore().listEntries({after:k});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 f=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let $=f.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:$.articles});break}case"GET /wiki/article":{let f=this.registry.getWikiHub(),m=n.searchParams.get("agent"),k=n.searchParams.get("path");if(!m||!k){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=f.getAgentWiki(m).readArticle(k);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:f}=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 k=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new f(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(-k).reverse()});break}case"POST /wiki/notes":{let{NoteStore:f,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),k=this.config.wikiNotes;if(!k.enabled||!k.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let $=await q(e),I=m({...$,to:k.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let x=I.note;if(this.registry.getAgent(k.inbox)){try{let{note:_,added:O}=new f(this.registry.getWikiHub().getBaseDir()).add(x);this.json(t,O?201:200,{ok:!0,added:O,note:_,node:this.config.node.id})}catch(_){this.json(t,507,{error:_?.message??String(_)})}break}if($.forwarded===!0){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node`});break}let D=this.mesh?.findAgentPeer(k.inbox);if(!D){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node or any known peer`});break}let L=this.mesh.directory().find(_=>_.peer===D.peer)?.peerUrl;if(!D.healthy||!L){this.json(t,503,{error:`the node hosting "${k.inbox}" (${D.peer}) is unreachable; try again later`});break}try{let _=await fetch(`${L.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(D.peer)},body:JSON.stringify({...x,fromNode:x.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),O=await _.json().catch(()=>({}));this.json(t,_.status,{...O,peer:D.peer})}catch(_){this.json(t,502,{error:`forward to ${D.peer} failed: ${_?.message??_}`,peer:D.peer})}break}case"GET /graph/schema":{let f=this.registry.getGraphStore();if(!f){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:f.loadSchema()});break}case"GET /graph/nodes":{let f=this.registry.getGraphStore();if(!f){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...f.loadNodes()});break}case"GET /graph/classifications":{let f=this.registry.getGraphStore();if(!f){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",k=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),$=f.listByStatus(m,k);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 q(e);await cv(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let d=this.registry.list().find(l=>l.id===i)?.runningTasks.filter(l=>l.channel===o&&l.chatId===a)||[];for(let l of d)this.registry.cancelRunningTask(l.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){return cp(this.config,e)}resolveTodayUsage(){let e=Gv();if(e==="json")return this.registry.getTodayUsage();let t=qv(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||!Fn(n)))try{let s=ne(n,".claude","skills");$E(s,{recursive:!0});let i=ne(s,NT);if(!Fn(i))Oh(i,Su(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=jT(sr(i,"utf-8"),e);o&&(Oh(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||!Fn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||cm(this.config.workflows,e)),i=kf(gp(t),this.config.requests.enabled||Gt(this.config.requests)||s?bf():null);try{switch(vf(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 cT(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async wakeWorkflows(e){try{await this.workflowDispatcher?.wake(e)}catch(n){this.log(`[workflows] wake failed: ${n.message}`)}let t=this.mesh?.directory().filter(n=>n.healthy)??[];await Promise.allSettled(t.map(async n=>{try{let s=await fetch(`${n.peerUrl}/workflow/event`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(n.peer)},body:JSON.stringify({kind:"wake",fromPeer:this.config.node.id,wake:e}),signal:AbortSignal.timeout(5e3)});s.ok||this.log(`[workflows/mesh] wake ${n.peer} -> ${s.status}`)}catch(s){this.log(`[workflows/mesh] wake ${n.peer} failed: ${s.message}`)}}))}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 re(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}if(n?.kind==="wake"){let c=Tf(n.wake);if(!c){this.json(t,400,{error:"invalid wake"});return}let d=await this.workflowDispatcher.wake(c);this.json(t,202,{ok:!0,mode:"wake",results:d});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 g=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${g.claimed.length} ${g.claimed.length?`(${g.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:g.claimed.map(y=>y.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await re(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-T5HZZRA2.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 qy(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await re(e)}catch(d){this.json(t,400,{error:"invalid JSON body",message:d.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let d=this.pushBridgeCaller(e);if("origin"in d)c=d.origin;else if(i!=="default"){this.json(t,403,{error:d.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:d}=await import("./push-bridge-T5HZZRA2.js"),l=d(i,this.pushBridgeCaller(e));if("error"in l){this.json(t,403,{error:l.error});return}}try{let d=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,open:typeof n.open=="string"&&n.open.startsWith("/")?n.open:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:d??null})}catch(d){this.log(`[mesh] /channel/send "${s}" failed: ${d.message}`),this.json(t,500,{error:d.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(d,l)=>{let u=0;for(let h of d)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:l}),u++);u>0&&o.push(`${l}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(d=>({id:d.jid,name:d.name,kind:d.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let d=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(d.map(async l=>{try{let u=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(l.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(g=>({id:g.id,name:g.name,kind:g.kind??"dm",accountId:g.accountId})),`mesh:${l.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await re(e)}catch{s={}}try{let i=await DT({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})}}},Dh=Nh;Yt(Dh,"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 kq(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 re(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 vq(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function q(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}function IE(r){let e=r.business;return JSON.stringify([e?.roles,e?.orgChart,e?.relations,e?.projects,(r.people??[]).map(t=>t.id),[...Vn(r)]])}TE();function Xne(r){typeof r=="string"&&(or.error(r),process.exit(1)),r instanceof Error&&(or.error(r.message),process.exit(1)),or.error("Something went wrong. Please try again."),process.exit(1)}export{Fq as a,Sd as b,Ot as c,gs as d,fs as e,Lt as f,mi as g,kk as h,KB as i,Rv as j,cM as k,dM as l,Mv as m,Ne as n,Lv as o,jv as p,Ui as q,tX as r,nX as s,no as t,DJ as u,CD as v,PD as w,Al as x,s0 as y,NJ as z,g0 as A,MD as B,p0 as C,f0 as D,m0 as E,LJ as F,jJ as G,WJ as H,co as I,_l as J,H0 as K,je as L,m3 as M,oL as N,X$ as O,J$ as P,zL as Q,lI as R,pI as S,jj as T,pu as U,$K as V,IK as W,TK as X,yT as Y,bW as Z,CK as _,PK as $,CT as aa,js as ba,Pn as ca,Ws as da,f5 as ea,Pu as fa,RF as ga,EF as ha,cz as ia,Qo as ja,Lu as ka,ju as la,sa as ma,Se as na,YA as oa,Bs as pa,MU as qa,ux as ra,DU as sa,fx as ta,la as ua,Vs as va,pa as wa,ma as xa,vx as ya,eh as za,Rx as Aa,kt as Ba,Ce as Ca,dh as Da,Ox as Ea,Dx as Fa,Nx as Ga,Lx as Ha,ja as Ia,OR as Ja,Th as Ka,NR as La,$2 as Ma,W9 as Na,Dh as Oa,Xne as Pa};
1397
- //# sourceMappingURL=chunk-HSBGTRKV.js.map
1397
+ //# sourceMappingURL=chunk-X2LFAJ5D.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-SUQ5ILYR.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
2
+ import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-YIKCSZBC.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-HSBGTRKV.js";import"./chunk-M3K5B3WH.js";import"./chunk-GTJIKXDB.js";import"./chunk-2TVJTWFC.js";import"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-EYVPRIO3.js";import"./chunk-LTOSEP7C.js";import"./chunk-QPABR72X.js";import"./chunk-QU7ICYFR.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Wa as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-TO7ZERY3.js";import"./chunk-7GDFB4FS.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-IXOJEEGR.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-EFXZACH4.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{x as ut}from"./chunk-CF2R6BOX.js";import"./chunk-Q6TGKWZE.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-MM7U4PWY.js";import{a as ht}from"./chunk-6ECXITK2.js";import{f as gt,g as ft}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{j as it,k as rt,l as at}from"./chunk-BTLADRMY.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Dc as nt,rc as tt,tc as st,wc as ot}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-X2LFAJ5D.js";import"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import"./chunk-2TVJTWFC.js";import"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-EYVPRIO3.js";import"./chunk-LTOSEP7C.js";import"./chunk-QPABR72X.js";import"./chunk-QU7ICYFR.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Wa as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-TEYFN6YL.js";import"./chunk-TA437DWX.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-W7PIHJHH.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-EFXZACH4.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{x as ut}from"./chunk-CF2R6BOX.js";import"./chunk-Q6TGKWZE.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-MM7U4PWY.js";import{a as ht}from"./chunk-6ECXITK2.js";import{f as gt,g as ft}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{j as it,k as rt,l as at}from"./chunk-BTLADRMY.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Dc as nt,rc as tt,tc as st,wc as ot}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,4 +1,4 @@
1
- import{a as Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-SJXWBL72.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-HSBGTRKV.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-M3K5B3WH.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Wa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-TO7ZERY3.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-7GDFB4FS.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-IXOJEEGR.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{xa();let t=O(),o=lf(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
1
+ import{a as Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-ATZRBMUZ.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-X2LFAJ5D.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Wa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-TEYFN6YL.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-TA437DWX.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-W7PIHJHH.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{xa();let t=O(),o=lf(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
2
2
  Computer-use helper \u2192 ${yt(i,na)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -608,7 +608,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
608
608
  Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${rs(r.createdAt)}`)}`),Hv(s.steps(e)),console.log(`
609
609
  Log`);for(let i of s.events(e))console.log(q.dim(` ${rs(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Fo.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(l=>o[l]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=fr();if(!s)return;let r=Sl();if(!r){process.exitCode=1;return}let i=Number(t),a=Yf(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(q.red(` ${a}`)),process.exitCode=1;return}console.log(q.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+q.dim(" (the daemon goes on within a minute)")),Hv(r.steps(e))});function Gv(e,t,o,n){let s=Fo.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=fr();if(!a)return;let l=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!l){console.error(q.red(` ${n}`)),process.exitCode=1;return}let c=a.get(r);if(!c||c.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}let u=process.env.AGENTX_AGENT_ID?.trim()||pm;if(!a.close(r,e==="done"?"done":"dropped",l,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${Gu[c.state]??c.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Gv("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");Gv("drop","drop a request you no longer want","--reason <text>","");Fo.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${Ui.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(y,w)=>{if(w===void 0)return;let $=Number(w);if(!($>0))throw new Error(`${y} must be a positive number`);return $},d=(y,w)=>y===void 0?void 0:y===w?[]:y.split(",").map($=>$.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let y=u("--catch-cap",e.catchCap);if(y!==void 0&&!Number.isInteger(y))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...y!==void 0?{dailyCap:y}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let p={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");p.enabled=e.plans==="on"}if(p.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let y=Number(e.maxNudges);if(!Number.isInteger(y)||y<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=y}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let y=Number(e.planOver);if(!(y>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=y}Object.values(p).some(y=>y!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let y=g.filter(w=>!Ui.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ui.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(y=>y!==void 0)&&(t.checkers=f);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let y=Number(e.resendAfter);if(!(y>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=y}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(y=>y!==void 0)&&(t.autoResend=h),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(q.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Cf(t);if(!u.success){console.error(q.red(` ${u.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(u.reloaded?q.dim(" (daemon reloaded)"):""))}let o=Pr();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??da;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??da.requireOverMinutes,i=s.requireForWork??da.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.autoResend??zf;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??Nc).timeZone} days`);let l=o.checkers??Wi;console.log(` Loop checks ${l.enabled.length?l.enabled.join(", "):"off"}, every ${l.checkEveryMinutes} minute(s)`);let c=Object.keys(l.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as NI}from"commander";import hr from"chalk";Z();var zv=new NI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",nd.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(hr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=fy(r,e,t==="on")});s.success||(console.error(hr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(hr.green(`\u2713 ${n}`)),s.reloaded&&console.log(hr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of nd)console.log(` ${n.padEnd(8)} ${o.includes(n)?hr.green("on"):hr.dim("off")}`)});import{Command as aN}from"commander";import yr from"chalk";import Ee from"chalk";import wi from"prompts";import{readFileSync as jI,writeFileSync as _I,existsSync as DI}from"fs";import{resolve as Yv}from"path";var PI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function MI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Yu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Kv(e=".env"){let t=Yv(e);if(!DI(t))return[];let o=jI(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(PI);r?n.push({kind:"kv",key:r[1],value:MI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function LI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Yu(t.value)}`:t.raw).join(`
610
610
  `)+`
611
- `}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function FI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function QI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await ex({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await ox({url:e.url,configPath:e.config})});sx.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});cs.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});cs.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});cs.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});cs.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y23TE5AN.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-SUQ5ILYR.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-B3NC26BR.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
611
+ `}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function FI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function QI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await ex({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await ox({url:e.url,configPath:e.config})});sx.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});cs.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});cs.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});cs.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});cs.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y23TE5AN.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-YIKCSZBC.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-B6QSOGCC.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
612
612
  `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}fn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ke.dim(`
613
613
  No boards configured.
614
614
  `));return}console.log();for(let t of e.boards){console.log(` ${Ke.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ke.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ke.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ke.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ke.red(` ${e.message}`)),process.exit(1)}});fn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{bi(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{bi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});var Zu=fn.command("column").description("manage a board's columns (add / remove / edit / list)");Zu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(dN("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Ke.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ke.dim(r)}`)}}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});Zu.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{bi(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Ke.red(` ${n.message}`)),process.exit(1)}});Zu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{bi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bi(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});function bi(e){let{summary:t,backupPath:o}=Ut(n=>e(n));console.log(Ke.green(`
@@ -912,7 +912,7 @@ Restart the daemon to activate.
912
912
  dist/
913
913
  *.log
914
914
  .env
915
- `}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-SUQ5ILYR.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tc(n)?aS(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tc(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),lS(n,u.join(`
915
+ `}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-YIKCSZBC.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tc(n)?aS(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tc(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),lS(n,u.join(`
916
916
  `)+`
917
917
  `),console.log(ut.green("\u2713 Patched ~/.zshrc")),console.log(ut.dim("Reload your shell: exec zsh"));return}console.log(ut.dim("Add this to ~/.zshrc if not already present:")),l&&console.log(ut.cyan(` ${r}`)),c&&console.log(ut.cyan(` ${i}`)),console.log(),console.log(ut.dim("Then reload: exec zsh")),console.log(ut.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Rr(qg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((tc(n)?aS(n,"utf-8"):"").includes(t)){console.log(ut.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&tc(n)){lS(n,`
918
918
  # agentx completion
@@ -928,4 +928,4 @@ ${lD({...t,category:e.category})}`),u&&a.set(c.id,u)}let l=`https://github.com/$
928
928
  ${o.url}`)}catch(t){console.error(Cr.red(` ${t.message}`)),process.exitCode=1}});ji.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Ug).action(async(e,t)=>{try{let o=await Jg(t.models);if(!Wg(t.model,o)){console.log(Bg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await uD():await dD(e,"utf8"),s=JSON.parse(n),{version:r}=await ea(),i=hS({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Cr.red(` ${o.message}`)),process.exitCode=1}});async function uD(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function V5(){let e=await ea(),t=new gD().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=ky(n);vy(s)&&$y("cli",s)});for(let o of[vb,Dw,_w,ls,Ws,yo,Wt,ty,zk,Kk,$o,La,qo,_n,ts,So,Fo,si,zv,pn,Ca,W0,dn,N$,j$,W$,gi,Z$,sk,C$,ak,lk,Ek,Ck,Ok,zt,cs,Y0,Xr,nn,gS,ji])t.addCommand(o);for(let o of wS)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=wS.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,mD(o,74," "),""].join(`
929
929
  `)}),t}var wS=[X,$r,Bo,lo,Qr,cr,rt,Wo,fn,es,ps,vr,wn,an,At,er,tl,hl,Qn,yl,wl,M0,F0,Lo,Ei,Jt,By,qn,Ii,Md,$n,xt,Qs,Ld,Jl,To,yg,Jo,eS,Er,tS,G0];function mD(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
930
930
  `)}export{V5 as buildProgram};
931
- //# sourceMappingURL=program-SUQ5ILYR.js.map
931
+ //# sourceMappingURL=program-YIKCSZBC.js.map