agentix-cli 0.101.2 → 0.102.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/Character.swift +11 -4
- package/apps/mac-voice/Sources/AgentXVoice/Guide.swift +12 -5
- package/apps/mac-voice/Sources/AgentXVoice/GuideMath.swift +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +24 -4
- package/apps/mac-voice/Sources/AgentXVoice/PanelBubble.swift +20 -1
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +18 -2
- package/dist/{chunk-AZGV6KOT.js → chunk-4KERZKTO.js} +180 -180
- package/dist/{chunk-AZGV6KOT.js.map → chunk-4KERZKTO.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-I546NXHR.js → program-N3CSTSJM.js} +5 -5
- package/dist/program-N3CSTSJM.js.map +1 -0
- package/package.json +1 -1
- package/dist/program-I546NXHR.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-N3CSTSJM.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,ga as Tt,h as bt,ha as Mt}from"./chunk-
|
|
1
|
+
import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,ga as Tt,h as bt,ha as Mt}from"./chunk-4KERZKTO.js";import"./chunk-MWLX3QCD.js";import"./chunk-GTJIKXDB.js";import"./chunk-ZJXDBVBT.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-S337S2M7.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-ACFQBLPX.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{Z as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-TXFIMVVF.js";import"./chunk-EXPIKLUN.js";import"./chunk-GLQLCBJS.js";import"./chunk-DP7RTNDM.js";import{a as L}from"./chunk-C245D4BZ.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-HMDM5MCR.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-V6W3FFW7.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-Y6POV2X5.js";import"./chunk-5UO6BBDG.js";import"./chunk-VWTBHLMX.js";import"./chunk-EEZI2K7S.js";import{a as ht}from"./chunk-AYNZAOJN.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-GSFB46YC.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-YOCQ2MWL.js";import{f as gt,g as ft}from"./chunk-XO55WKCX.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-RWSCQMLD.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.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{ba as tt,da as st,ea as ot,ga as nt}from"./chunk-ECM2QEXF.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as od,b as Ns,g as td}from"./chunk-PYCTWI2I.js";import{A as ed,a as so,b as Ll,f as Pt,g as Fl,h as Wl,i as Bl,j as Jl,l as Hl,m as Gl,r as zl,s as Vl,t as tr,u as Yl,x as nr,y as Zl}from"./chunk-N57ES35J.js";import{a as Xl,c as Kl,d as Ql}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as ql,c as Ul}from"./chunk-HQJW3BC5.js";import{a as Ui,b as mc}from"./chunk-RKPAVWXF.js";import{$ as Il,A as dl,B as gl,C as ml,D as pl,E as ul,F as fl,G as vl,H as As,I as Yi,J as Nt,K as Ts,L as js,M as Xi,N as xl,O as Sl,P as El,Q as Al,R as Tl,S as jl,T as Rt,U as _t,V as Ol,W as Cl,X as Le,Y as Os,Z as On,_ as Ki,a as bc,aa as _l,b as kc,ba as er,ca as Pl,da as Cs,ea as Dt,fa as Is,ga as or,h as fs,ha as Ml,i as Ec,j as An,k as hs,l as jc,m as Oc,n as Fc,o as Wc,p as vs,q as Wi,r as Vc,s as ol,t as tl,u as il,v as rl,w as al,x as cl,y as ll,z as Ji}from"./chunk-
|
|
1
|
+
import{a as od,b as Ns,g as td}from"./chunk-PYCTWI2I.js";import{A as ed,a as so,b as Ll,f as Pt,g as Fl,h as Wl,i as Bl,j as Jl,l as Hl,m as Gl,r as zl,s as Vl,t as tr,u as Yl,x as nr,y as Zl}from"./chunk-N57ES35J.js";import{a as Xl,c as Kl,d as Ql}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as ql,c as Ul}from"./chunk-HQJW3BC5.js";import{a as Ui,b as mc}from"./chunk-RKPAVWXF.js";import{$ as Il,A as dl,B as gl,C as ml,D as pl,E as ul,F as fl,G as vl,H as As,I as Yi,J as Nt,K as Ts,L as js,M as Xi,N as xl,O as Sl,P as El,Q as Al,R as Tl,S as jl,T as Rt,U as _t,V as Ol,W as Cl,X as Le,Y as Os,Z as On,_ as Ki,a as bc,aa as _l,b as kc,ba as er,ca as Pl,da as Cs,ea as Dt,fa as Is,ga as or,h as fs,ha as Ml,i as Ec,j as An,k as hs,l as jc,m as Oc,n as Fc,o as Wc,p as vs,q as Wi,r as Vc,s as ol,t as tl,u as il,v as rl,w as al,x as cl,y as ll,z as Ji}from"./chunk-4KERZKTO.js";import{$a as Dl,A as xs,C as el,Ia as Nl,Ja as Qi,Ka as Rl,La as Zi,R as Tn,U as Hi,V as Ss,W as hl,Za as ko,ba as Fo,ca as yl,da as Gi,fa as zi,ha as wl,ia as $l,ja as jn,na as Es,qa as bl,ra as kl,sa as Vi,w as Bi,x as Qc,z as Zc}from"./chunk-MWLX3QCD.js";import"./chunk-GTJIKXDB.js";import{a as vc,d as xc,e as Sc}from"./chunk-ZJXDBVBT.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import{a as ys,b as ws,c as Cc,d as Ic,e as Nc,g as Rc,h as _c,j as Dc,k as Pc,l as Mc,m as Lc,p as $s,s as qc,t as Uc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as nl,b as sl}from"./chunk-EKJG63EJ.js";import{a as Ac,p as Tc}from"./chunk-S337S2M7.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as Bc,e as bs,g as ks}from"./chunk-LQE73AZR.js";import{a as Jc,b as Hc,c as Gc,d as zc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Yc,e as Xc,g as Kc}from"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{I as Uo,O as ac,Z as lc,g as Ha,r as Ga,y as Mi,z as Xa}from"./chunk-TXFIMVVF.js";import{b as At,g as jt,h as ps,i as us,j as Ot,k as Ka,l as it,m as Sn,u as cc}from"./chunk-EXPIKLUN.js";import{e as nc,f as qi,k as sc}from"./chunk-GLQLCBJS.js";import{b as Tt}from"./chunk-DP7RTNDM.js";import"./chunk-HMDM5MCR.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as En}from"./chunk-LLNPKE7H.js";import{a as dc,b as gc}from"./chunk-SHEUCITK.js";import{a as Fi,e as pc,f as uc,h as fc,i as hc,k as yc,l as wc,m as $c}from"./chunk-V6W3FFW7.js";import{c as Za}from"./chunk-SZDACK6O.js";import{f as ec,g as oc,h as Li}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Va,k as tc}from"./chunk-Y6POV2X5.js";import{a as ic,b as re,c as Ie,d as It,e as rc}from"./chunk-5UO6BBDG.js";import"./chunk-VWTBHLMX.js";import{a as Di}from"./chunk-EEZI2K7S.js";import"./chunk-AYNZAOJN.js";import"./chunk-KA2UIZXG.js";import{a as Pi,b as za}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ya}from"./chunk-X5C5W3E4.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{e as Qa}from"./chunk-GSX4NK2N.js";import"./chunk-GSFB46YC.js";import"./chunk-MYVHVJWZ.js";import{h as Ja}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-YOCQ2MWL.js";import{g as qo,i as ms}from"./chunk-XO55WKCX.js";import"./chunk-WPNRDEHW.js";import{b as Et,d as Ba}from"./chunk-2GIDVZ4H.js";import{a as Ni,b as Ea,c as Lp,d as ls,e as Aa,f as Ma,g as Bp,h as La,i as Jp,m as St,n as Ua,o as Fa,s as Wa,v as bo,w as xn}from"./chunk-RWSCQMLD.js";import{a as jo,b as xt,e as _a,f as vn}from"./chunk-72SZI2UW.js";import{a as qa,b as Hp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as To,b as Mp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{J as Ri,L as _i,S as Fp,ba as Na,ca as Ra,da as T,ea as gs,ga as te,h as Ta,i as ja,j as Oa,k as Ca,l as qp,v as Ia,w as Up}from"./chunk-ECM2QEXF.js";import{a as Lo,i as ds}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Da,k as Pa,l as Wp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Gp}from"commander";var nd=new Gp().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 kc({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()});te();import{Command as zp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as sd,existsSync as rr,mkdirSync as sr,mkdtempSync as Vp,readdirSync as Yp,rmSync as id,writeFileSync as rd}from"node:fs";import{dirname as ad,join as qe}from"node:path";import{homedir as Rs,release as Xp,tmpdir as Kp}from"node:os";import{setTimeout as Qp}from"node:timers/promises";function _s(){let e=Cc(process.platform,process.arch,Xp());if(e)throw new Error(e)}function Ds(){let e=qe(Rs(),"Library/LaunchAgents"),o=[];try{o=Yp(e).filter(Rc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return _c(e,t)}function Cn(e){return`gui/${process.getuid()}/${e.label}`}async function ir(e){try{ao("launchctl",["bootout",Cn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{return}await Qp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function cd(e){if(!rr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",Cn(e)],{stdio:"pipe"})}function Zp(){let e=Lc();if(e&&rr(qe(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 Mt=new zp("desktop").description("install and control the macOS desktop assistant");Mt.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=>{_s();let o=T(),t=Ic(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Zp(),r=qe(Rs(),"Applications"),{keep:a,remove:c}=Ds();if(console.log(`Desktop assistant \u2192 ${qe(r,ys)}
|
|
2
2
|
Computer-use helper \u2192 ${qe(r,ws)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -290,7 +290,7 @@ rules:
|
|
|
290
290
|
message: "coder-agent is not permitted to run commands against production."
|
|
291
291
|
`,Jd=[{relPath:"policy.yaml",content:pf},{relPath:"environments/production.yaml",content:uf},{relPath:"agents/coder-agent.yaml",content:ff}];var Yo=new hf().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Tr(e){return e==="deny"?he.red:e==="escalate"||e==="ask"?he.yellow:e==="warn"?he.magenta:he.green}function Gs(e){return e.root?Gd(e.root):fl()}Yo.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await ul({root:Gs(e),agentId:e.agent,env:e.env}),process.exit(0)});Yo.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=Gs(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=pl({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}kf(s,i,r)});function kf(e,o,t){let n=Tr(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":he.dim(" (no rule matched)")}`),console.log(` enforced as ${Tr(e.effectiveAction)(e.effectiveAction)} ${he.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${he.cyan(e.ruleId)}${e.severity?he.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${he.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${he.dim(`evaluated in ${t}ms`)}`),console.log()}Yo.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Ha({root:Gs(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(he.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Tr(t.verdict),i=t.effective_action!==t.verdict?he.dim(`->${t.effective_action}`):"";console.log(` ${he.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${he.cyan((t.agent_id??"?").padEnd(16))} ${he.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(he.dim(` target: ${t.resolved_target}`))}});Yo.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Hd(Gd(e.root),gl),t=0;for(let n of Jd){let s=Hd(o,n.relPath);if(yf(s)&&!e.force){console.log(he.dim(` skip (exists) ${n.relPath}`));continue}wf(bf(s),{recursive:!0}),$f(s,n.content),console.log(he.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${he.cyan(o)}`),console.log(he.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(he.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Yo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(he.green(` daemon reloaded (${e.url})`)):console.log(he.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(he.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Yo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=ml(Gs(e),e.agent);console.log(JSON.stringify(o,null,2))});xn();import{Command as Af}from"commander";import{execFile as Tf}from"child_process";import{promisify as jf}from"util";import{existsSync as Of}from"fs";import eo from"chalk";vn();var Un="ui-element";function zs(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:qn(t.tried,80),screenChanged:t.changed,note:t.note?qn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:zd(t.role),label:qn(t.label,120),value:t.value?qn(t.value,80):null,enabled:t.enabled}))}}function Vs(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${zd(t.role)}: ${qn(n,80)}`}return{target:xt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:jo("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function Ys(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function zd(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function qn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{Command as Ht}from"commander";import mo from"chalk";var Vd=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function Ze(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${Vd}${o}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:t===void 0?void 0:JSON.stringify(t)}).catch(a=>{throw new Error(`daemon not reachable at ${Vd}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function vf(e,o,t){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(o);return t===s?`${o} is ${t?"already":"not"} in calls.allow`:(e.calls.allow=t?[...n,o]:n.filter(i=>i!==o),t?`${o} may now call you`:`${o} may no longer call you`)}function Or(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?mo.yellow("missed"):e.status==="ringing"?mo.green("ringing"):mo.dim(e.status),n=e.note?mo.dim(` (${e.note})`):"";return` ${mo.dim(e.id)} ${o} ${e.agentId} ${t}${n}
|
|
292
292
|
${e.reason}${e.summary?mo.dim(`
|
|
293
|
-
summary: ${e.summary}`):""}`}async function Fn(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var xf=new Ht("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Fn(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await Ze("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},En());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?mo.green("\u260E"):mo.yellow("\u23F8")} ${t.call.id} ${n}`)})),Sf=new Ht("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Fn(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await Ze("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(mo.dim(" no calls"));return}for(let n of t)console.log(Or(n))}));function jr(e,o){return new Ht(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Fn(async()=>{let{call:n}=await Ze("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Or(n))}))}var Ef=new Ht("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Fn(async()=>{let{call:t}=await Ze("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Or(t))}));function Yd(e,o){return new Ht(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>Fn(()=>{let{summary:s}=so(i=>vf(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var Xd=new Ht("call").description("agents ring you for a live voice call").addCommand(xf).addCommand(Sf).addCommand(jr("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(jr("decline","decline a ringing call")).addCommand(Ef).addCommand(jr("hangup","end an answered call")).addCommand(Yd("allow",!0)).addCommand(Yd("disallow",!1));var Cf=jf(Tf);async function Kd(e,o,t){await Ze("POST","/voice/guide",{rect:e,mark:t.mark,...t.hold?{hold:Number(t.hold)}:{}}).then(s=>s?.shown===!0,()=>!1)||await Cf(Le,["point","--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height),"--label",o])}var Qd=new Af().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").option("--mark <kind>",`how the character marks it: ${As.join(", ")}`,"box").option("--hold <seconds>","how long the character stays there (8 by default)").action(async(e,o)=>{As.includes(o.mark)||(console.log(eo.red(` --mark is one of: ${As.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Yi.max)&&(console.log(eo.red(` --hold is a number of seconds, up to ${Yi.max}`)),process.exit(1)),Of(Le)||(console.log(eo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Os({max:Number(o.max)||40})}catch(d){console.log(eo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(eo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=On(t,n[0].id);d&&(console.log(eo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+eo.bold(n[0].label)),await Kd(d,n[0].label,o));return}let s=await bo(Un,zs({request:e,app:t.app,window:t.window,candidates:n}),Vs(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(eo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Un}.mode`)),process.exit(1));let i=Ys(s.answers,n),r=On(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(eo.yellow(` nothing on screen matches "${e}"`)+eo.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${eo.green("\u2192")} ${eo.bold(g)} `+eo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Kd(r,g,o)});import{Command as Qf}from"commander";import ze from"chalk";import{readFileSync as Zd}from"fs";import{homedir as If}from"os";import{join as Nf}from"path";var eg=12e5,Rf="https://openrouter.ai/api/v1/chat/completions",_f=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Df(e={kind:"window"},o=eg,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Dt(e,{},n);try{return await Dt(e,{untilStable:!0},n)}catch(s){if(s instanceof Pl)return Dt(e,{},n);throw s}}var Pf=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
293
|
+
summary: ${e.summary}`):""}`}async function Fn(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var xf=new Ht("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Fn(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await Ze("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},En());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?mo.green("\u260E"):mo.yellow("\u23F8")} ${t.call.id} ${n}`)})),Sf=new Ht("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Fn(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await Ze("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(mo.dim(" no calls"));return}for(let n of t)console.log(Or(n))}));function jr(e,o){return new Ht(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Fn(async()=>{let{call:n}=await Ze("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Or(n))}))}var Ef=new Ht("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Fn(async()=>{let{call:t}=await Ze("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Or(t))}));function Yd(e,o){return new Ht(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>Fn(()=>{let{summary:s}=so(i=>vf(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var Xd=new Ht("call").description("agents ring you for a live voice call").addCommand(xf).addCommand(Sf).addCommand(jr("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(jr("decline","decline a ringing call")).addCommand(Ef).addCommand(jr("hangup","end an answered call")).addCommand(Yd("allow",!0)).addCommand(Yd("disallow",!1));var Cf=jf(Tf);async function Kd(e,o,t){await Ze("POST","/voice/guide",{rect:e,mark:t.mark,...t.hold?{hold:Number(t.hold)}:{},...t.text?{text:t.text}:{}}).then(s=>s?.shown===!0,()=>!1)||await Cf(Le,["point","--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height),"--label",o])}var Qd=new Af().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").option("--mark <kind>",`how the character marks it: ${As.join(", ")}`,"box").option("--hold <seconds>","how long the character stays there (8 by default)").option("--text <words>","what the character's bubble says there (no bubble without it)").action(async(e,o)=>{As.includes(o.mark)||(console.log(eo.red(` --mark is one of: ${As.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Yi.max)&&(console.log(eo.red(` --hold is a number of seconds, up to ${Yi.max}`)),process.exit(1)),Of(Le)||(console.log(eo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Os({max:Number(o.max)||40})}catch(d){console.log(eo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(eo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=On(t,n[0].id);d&&(console.log(eo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+eo.bold(n[0].label)),await Kd(d,n[0].label,o));return}let s=await bo(Un,zs({request:e,app:t.app,window:t.window,candidates:n}),Vs(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(eo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Un}.mode`)),process.exit(1));let i=Ys(s.answers,n),r=On(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(eo.yellow(` nothing on screen matches "${e}"`)+eo.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${eo.green("\u2192")} ${eo.bold(g)} `+eo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Kd(r,g,o)});import{Command as Qf}from"commander";import ze from"chalk";import{readFileSync as Zd}from"fs";import{homedir as If}from"os";import{join as Nf}from"path";var eg=12e5,Rf="https://openrouter.ai/api/v1/chat/completions",_f=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Df(e={kind:"window"},o=eg,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Dt(e,{},n);try{return await Dt(e,{untilStable:!0},n)}catch(s){if(s instanceof Pl)return Dt(e,{},n);throw s}}var Pf=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
294
294
|
|
|
295
295
|
Report only what is visible in this image.
|
|
296
296
|
|
|
@@ -448,7 +448,7 @@ return aid ?? null`}function Vh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
448
448
|
Latest runs (${s.length})`),s.length===0&&console.log(z.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?z.green("ok"):r.status==="in-flight"?z.yellow("running"):z.red(r.status);console.log(` ${z.dim(dm(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${gm(r.messagePreview)}`)}console.log()});ds();Up();import{Command as tw}from"commander";import{existsSync as nw}from"fs";import ye from"chalk";var en=new tw("requests").description("what you asked agents for that is not finished, oldest first"),hm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Hr(){if(!nw(ic()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=Lo();return e?new Ia(e):(process.exitCode=1,null)}var ci=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function ym(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${hm[e.state]??e.state}]`)} ${ye.dim(`${ci(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}en.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Hr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Bi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)ym(n);console.log(ye.dim(`
|
|
449
449
|
${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});en.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Hr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}ym(t),console.log(ye.dim(` Last activity ${ci(t.updatedAt)}${t.closedAt?` \xB7 closed ${ci(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${ci(n.at)})`))});function wm(e,o,t,n){en.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Hr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${hm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}wm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");wm("drop","drop a request you no longer want","--reason <text>","");en.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").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Qc(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=Bi();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as sw}from"commander";import on from"chalk";te();var $m=new sw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",tr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(on.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=Yl(i,e,o==="on")});s.success||(console.error(on.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(on.green(`\u2713 ${n}`)),s.reloaded&&console.log(on.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of tr)console.log(` ${n.padEnd(8)} ${t.includes(n)?on.green("on"):on.dim("off")}`)});import{Command as Tw}from"commander";import tn from"chalk";import ce from"chalk";import Xn from"prompts";import{readFileSync as iw,writeFileSync as rw,existsSync as aw}from"fs";import{resolve as bm}from"path";var cw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function lw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Gr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function km(e=".env"){let o=bm(e);if(!aw(o))return[];let t=iw(o,"utf-8"),n=[];for(let s of t.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 i=s.match(cw);i?n.push({kind:"kv",key:i[1],value:lw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function dw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Gr(o.value)}`:o.raw).join(`
|
|
450
450
|
`)+`
|
|
451
|
-
`}function Yn(e,o,t=".env"){let n=bm(t),s=km(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`})),rw(n,dw(s))}function zr(e,o=".env"){return km(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var vm="https://t.me/BotFather";async function gw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function mw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 xm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${vm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Xn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&ct(vm);let{token:t}=await Xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await gw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Yn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await mw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Vr from"prompts";import{existsSync as Xr,mkdirSync as pw,readdirSync as uw,readFileSync as Sm}from"fs";import{resolve as Yr}from"path";var fw=".agentx/whatsapp-sessions";function hw(){let e=Yr(process.cwd(),".agentx/daemon.pid");if(!Xr(e))return!1;try{let o=parseInt(Sm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function yw(e){if(!Xr(e))return!1;try{return uw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ww(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;pw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Em(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Yr(process.cwd(),"agentx.json");Xr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Sm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||fw,s=Yr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Vr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yw(s)&&a){let{keep:l}=await Vr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ww(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as $w}from"crypto";import je from"chalk";import Am from"prompts";var li="agentx-mesh:",di="//join/";function bw(e){return Buffer.from(e,"utf-8").toString("base64url")}function kw(e){return Buffer.from(e,"base64url").toString("utf-8")}function vw(e){return`${li}${di}${bw(JSON.stringify(e))}`}function xw(e){if(!e.startsWith(`${li}${di}`))throw new Error(`Not a mesh invite link \u2014 expected ${li}${di}\u2026`);let o=e.slice(li.length+di.length),t=JSON.parse(kw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Sw(){return $w(32).toString("hex")}function Ew(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Aw(e){return e?.node?.name||e?.node?.id||"node"}async function Tm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=zr("MESH_TOKEN");r||(r=Sw(),Yn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ew(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Am({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=vw({url:a,token:r,name:Aw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jm(e,o={}){let t;try{t=xw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=zr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Am({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Yn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var nn=new Tw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");nn.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 xm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});nn.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 Em({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Om=nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Om.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 Tm({url:e.url,configPath:e.config})});Om.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jm(e,{configPath:o.config})});nn.action(()=>{console.log(),console.log(tn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as jw}from"commander";import oe from"chalk";var sn=new jw().name("usage").description("token usage analysis and reporting");sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});sn.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});sn.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});sn.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-I546NXHR.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ow}from"commander";import xe from"chalk";import{readFileSync as Cw}from"fs";import{resolve as Iw}from"path";te();var Zo=new Ow().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Zo.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{Ba(Iw(process.cwd(),".env"))}catch{}let o=Nw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-TVSOWW32.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Nw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
451
|
+
`}function Yn(e,o,t=".env"){let n=bm(t),s=km(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`})),rw(n,dw(s))}function zr(e,o=".env"){return km(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var vm="https://t.me/BotFather";async function gw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function mw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 xm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${vm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Xn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&ct(vm);let{token:t}=await Xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await gw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Yn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await mw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Vr from"prompts";import{existsSync as Xr,mkdirSync as pw,readdirSync as uw,readFileSync as Sm}from"fs";import{resolve as Yr}from"path";var fw=".agentx/whatsapp-sessions";function hw(){let e=Yr(process.cwd(),".agentx/daemon.pid");if(!Xr(e))return!1;try{let o=parseInt(Sm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function yw(e){if(!Xr(e))return!1;try{return uw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ww(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;pw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Em(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Yr(process.cwd(),"agentx.json");Xr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Sm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||fw,s=Yr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Vr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yw(s)&&a){let{keep:l}=await Vr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ww(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as $w}from"crypto";import je from"chalk";import Am from"prompts";var li="agentx-mesh:",di="//join/";function bw(e){return Buffer.from(e,"utf-8").toString("base64url")}function kw(e){return Buffer.from(e,"base64url").toString("utf-8")}function vw(e){return`${li}${di}${bw(JSON.stringify(e))}`}function xw(e){if(!e.startsWith(`${li}${di}`))throw new Error(`Not a mesh invite link \u2014 expected ${li}${di}\u2026`);let o=e.slice(li.length+di.length),t=JSON.parse(kw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Sw(){return $w(32).toString("hex")}function Ew(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Aw(e){return e?.node?.name||e?.node?.id||"node"}async function Tm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=zr("MESH_TOKEN");r||(r=Sw(),Yn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ew(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Am({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=vw({url:a,token:r,name:Aw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jm(e,o={}){let t;try{t=xw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=zr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Am({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Yn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var nn=new Tw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");nn.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 xm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});nn.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 Em({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Om=nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Om.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 Tm({url:e.url,configPath:e.config})});Om.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jm(e,{configPath:o.config})});nn.action(()=>{console.log(),console.log(tn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as jw}from"commander";import oe from"chalk";var sn=new jw().name("usage").description("token usage analysis and reporting");sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});sn.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});sn.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});sn.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-N3CSTSJM.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ow}from"commander";import xe from"chalk";import{readFileSync as Cw}from"fs";import{resolve as Iw}from"path";te();var Zo=new Ow().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Zo.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{Ba(Iw(process.cwd(),".env"))}catch{}let o=Nw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-TVSOWW32.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Nw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
452
452
|
`)),{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:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Zo.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
|
|
453
453
|
No boards configured.
|
|
454
454
|
`));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Zo.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,o)=>{try{Kn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Zo.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,o)=>{try{Kn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});var Kr=Zo.command("column").description("manage a board's columns (add / remove / edit / list)");Kr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Cw("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(xe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Kr.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,o,t)=>{try{Kn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(xe.red(` ${n.message}`)),process.exit(1)}});Kr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Kn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Zo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Kn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});function Kn(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
|
|
@@ -675,7 +675,7 @@ Restart the daemon to activate.
|
|
|
675
675
|
dist/
|
|
676
676
|
*.log
|
|
677
677
|
.env
|
|
678
|
-
`}import{Command as xb}from"commander";import Pe from"chalk";import{writeFileSync as Sb,mkdirSync as Eb,existsSync as Ti,readFileSync as Ep,appendFileSync as Ap}from"fs";import{resolve as wn,dirname as Op}from"path";import{homedir as $a}from"os";var Cp=new xb().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:o}=await import("./program-
|
|
678
|
+
`}import{Command as xb}from"commander";import Pe from"chalk";import{writeFileSync as Sb,mkdirSync as Eb,existsSync as Ti,readFileSync as Ep,appendFileSync as Ap}from"fs";import{resolve as wn,dirname as Op}from"path";import{homedir as $a}from"os";var Cp=new xb().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:o}=await import("./program-N3CSTSJM.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=jb(t);break;case"bash":s=Rb(t);break;case"fish":s=_b(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?wn(String(e.output)):Ab(n);Eb(Op(i),{recursive:!0}),Sb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Tb(n,i,!!e.yes)});function Ab(e){let o=$a();switch(e){case"zsh":return wn(o,".zsh","completions","_agentx");case"bash":return wn(o,".bash_completion.d","agentx.bash");case"fish":return wn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Tb(e,o,t){if(e==="zsh"){let n=wn($a(),".zshrc"),s=Op(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ti(n)?Ep(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ti(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ap(n,g.join(`
|
|
679
679
|
`)+`
|
|
680
680
|
`),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=wn($a(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ti(n)?Ep(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ti(n)){Ap(n,`
|
|
681
681
|
# agentx completion
|
|
@@ -691,4 +691,4 @@ ${Db({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
691
691
|
${t.url}`)}catch(o){console.error(bn.red(` ${o.message}`)),process.exitCode=1}});cs.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",ka).action(async(e,o)=>{try{let t=await Sa(o.models);if(!va(o.model,t)){console.log(xa(o.model,t)),process.exitCode=1;return}let n=e==="-"?await Lb():await Mb(e,"utf8"),s=JSON.parse(n),{version:i}=await fs(),r=_p({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(bn.red(` ${t.message}`)),process.exitCode=1}});async function Lb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function lI(){let e=await fs(),o=new qb().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");o.hook("preAction",(t,n)=>{let s=Kl(n);Ql(s)&&Xl("cli",s)});for(let t of[jd,Td,nn,Mt,Ut,co,Ul,lt,Fs,Io,Ro,en,$m,Qo,Us,np,Yo,Qd,ag,Jn,wg,vg,Xd,Eg,Ag,Bg,zg,Vg,Co,sn,cp,Dn,Jo,Cp,cs])o.addCommand(t);for(let t of Pp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Pp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Ub(t,74," "),""].join(`
|
|
692
692
|
`)}),o}var Pp=[ne,cn,tt,$o,Ln,Kt,Xe,Do,Zo,yt,mn,pn,zo,Ge,Jt,ri,ep,op,Oo,io,nd,gt,rs,wr,ot,oo,Wt,$r,bi,Ao,Po,wp,bp,ap];function Ub(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
693
693
|
`)}export{lI as buildProgram};
|
|
694
|
-
//# sourceMappingURL=program-
|
|
694
|
+
//# sourceMappingURL=program-N3CSTSJM.js.map
|